hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4eebbe2162ead05950720b51dd843359298ae7f4 | 30,511 | cpp | C++ | ESMF/src/Infrastructure/Mesh/src/Moab/Range.cpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2018-07-05T16:48:58.000Z | 2018-07-05T16:48:58.000Z | ESMF/src/Infrastructure/Mesh/src/Moab/Range.cpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2022-03-04T16:12:02.000Z | 2022-03-04T16:12:02.000Z | ESMF/src/Infrastructure/Mesh/src/Moab/Range.cpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | null | null | null | /**
* MOAB, a Mesh-Oriented datABase, is a software component for creating,
* storing and accessing finite element mesh data.
*
* Copyright 2004 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
/****************************************************
* File : Range.cpp
*
* Purpose : Stores contiguous or partially
* contiguous values in an optimized
* fashion. Partially contiguous
* accessing patterns is also optimized.
*
* Creator : Clinton Stimpson
*
* Date : 15 April 2002
*
*******************************************************/
#include <assert.h>
#include "moab/Range.hpp"
#include "Internals.hpp"
#include "moab/CN.hpp"
#include <iostream>
#include <string>
#ifdef HAVE_BOOST_POOL_SINGLETON_POOL_HPP
# include <boost/pool/singleton_pool.hpp>
typedef boost::singleton_pool< moab::Range::PairNode , sizeof(moab::Range::PairNode) >
PairAlloc;
// static inline moab::Range::PairNode* alloc_pair()
// { return new (PairAlloc::malloc()) moab::Range::PairNode; }
static inline moab::Range::PairNode* alloc_pair(moab::Range::PairNode* n, moab::Range::PairNode* p, moab::EntityHandle f, moab::EntityHandle s)
{ return new (PairAlloc::malloc()) moab::Range::PairNode(n,p,f,s); }
static inline void free_pair( moab::Range::PairNode* node )
{ node->~PairNode(); PairAlloc::free( node ); }
#else
// static inline moab::Range::PairNode* alloc_pair()
// { return new moab::Range::PairNode; }
static inline moab::Range::PairNode* alloc_pair(moab::Range::PairNode* n, moab::Range::PairNode* p, moab::EntityHandle f, moab::EntityHandle s)
{ return new moab::Range::PairNode(n,p,f,s); }
static inline void free_pair( moab::Range::PairNode* node )
{ delete node; }
#endif
namespace moab {
/*!
returns the number of values this list represents
*/
size_t Range::size() const
{
// go through each pair and add up the number of values
// we have.
size_t sz=0;
for(PairNode* iter = mHead.mNext; iter != &mHead; iter = iter->mNext)
{
sz += ((iter->second - iter->first) + 1);
}
return sz;
}
/*!
advance iterator
*/
Range::const_iterator& Range::const_iterator::operator+=( EntityID sstep )
{
// Check negative now to avoid infinite loop below.
if (sstep < 0)
{
return operator-=( -sstep );
}
EntityHandle step = sstep;
// Handle current PairNode. Either step is within the current
// node or need to remove the remainder of the current node
// from step.
EntityHandle this_node_rem = mNode->second - mValue;
if (this_node_rem >= step)
{
mValue += step;
return *this;
}
step -= this_node_rem + 1;
// For each node we are stepping past, decrement step
// by the size of the node.
PairNode* node = mNode->mNext;
EntityHandle node_size = node->second - node->first + 1;
while (step >= node_size)
{
step -= node_size;
node = node->mNext;
node_size = node->second - node->first + 1;
}
// Advance into the resulting node by whatever is
// left in step.
mNode = node;
mValue = mNode->first + step;
return *this;
}
/*!
regress iterator
*/
Range::const_iterator& Range::const_iterator::operator-=( EntityID sstep )
{
// Check negative now to avoid infinite loop below.
if (sstep < 0)
{
return operator+=( -sstep );
}
EntityHandle step = sstep;
// Handle current PairNode. Either step is within the current
// node or need to remove the remainder of the current node
// from step.
EntityHandle this_node_rem = mValue - mNode->first;
if (this_node_rem >= step)
{
mValue -= step;
return *this;
}
step -= this_node_rem + 1;
// For each node we are stepping past, decrement step
// by the size of the node.
PairNode* node = mNode->mPrev;
EntityHandle node_size = node->second - node->first + 1;
while (step >= node_size)
{
step -= node_size;
node = node->mPrev;
node_size = node->second - node->first + 1;
}
// Advance into the resulting node by whatever is
// left in step.
mNode = node;
mValue = mNode->second - step;
return *this;
}
//! another constructor that takes an initial range
Range::Range( EntityHandle val1, EntityHandle val2 )
{
mHead.mNext = mHead.mPrev = alloc_pair(&mHead, &mHead, val1, val2);
mHead.first = mHead.second = 0;
}
//! copy constructor
Range::Range(const Range& copy)
{
// set the head node to point to itself
mHead.mNext = mHead.mPrev = &mHead;
mHead.first = mHead.second = 0;
const PairNode* copy_node = copy.mHead.mNext;
PairNode* new_node = &mHead;
for(; copy_node != &(copy.mHead); copy_node = copy_node->mNext)
{
PairNode* tmp_node = alloc_pair(new_node->mNext, new_node, copy_node->first,
copy_node->second);
new_node->mNext->mPrev = tmp_node;
new_node->mNext = tmp_node;
new_node = tmp_node;
}
}
//! clears the contents of the list
void Range::clear()
{
PairNode* tmp_node = mHead.mNext;
while(tmp_node != &mHead)
{
PairNode* to_delete = tmp_node;
tmp_node = tmp_node->mNext;
free_pair( to_delete );
}
mHead.mNext = &mHead;
mHead.mPrev = &mHead;
}
Range& Range::operator=(const Range& copy)
{
clear();
const PairNode* copy_node = copy.mHead.mNext;
PairNode* new_node = &mHead;
for(; copy_node != &(copy.mHead); copy_node = copy_node->mNext)
{
PairNode* tmp_node = alloc_pair(new_node->mNext, new_node, copy_node->first,
copy_node->second);
new_node->mNext->mPrev = tmp_node;
new_node->mNext = tmp_node;
new_node = tmp_node;
}
return *this;
}
/*!
inserts a single value into this range
*/
Range::iterator Range::insert( Range::iterator hint, EntityHandle val )
{
// don't allow zero-valued handles in Range
if(val == 0)
return end();
// if this is empty, just add it and return an iterator to it
if(&mHead == mHead.mNext)
{
mHead.mNext = mHead.mPrev = alloc_pair(&mHead, &mHead, val, val);
return iterator(mHead.mNext, val);
}
// find the location in the list where we can safely insert
// new items and keep it ordered
PairNode* hter = hint.mNode;
PairNode* jter = hter->first <= val ? hter : mHead.mNext;
for( ; (jter != &mHead) && (jter->second < val); jter=jter->mNext);
PairNode* iter = jter;
jter = jter->mPrev;
// if this val is already in the list
if( (iter->first <= val && iter->second >= val) && (iter != &mHead) )
{
// return an iterator pointing to this location
return iterator( iter, val );
}
// one of a few things can happen at this point
// 1. this range needs to be backwardly extended
// 2. the previous range needs to be forwardly extended
// 3. a new range needs to be added
// extend this range back a bit
else if( (iter->first == (val+1)) && (iter != &mHead) )
{
iter->first = val;
// see if we need to merge two ranges
if( (iter != mHead.mNext) && (jter->second == (val-1)))
{
jter->second = iter->second;
iter->mPrev->mNext = iter->mNext;
iter->mNext->mPrev = iter->mPrev;
free_pair( iter );
return iterator( jter, val );
}
else
{
return iterator( iter, val );
}
}
// extend the previous range forward a bit
else if( (jter->second == (val-1)) && (iter != mHead.mNext) )
{
jter->second = val;
return iterator(jter, val);
}
// make a new range
else
{
PairNode* new_node = alloc_pair(iter, iter->mPrev, val, val);
iter->mPrev = new_node->mPrev->mNext = new_node;
return iterator(new_node, val);
}
}
Range::iterator Range::insert( Range::iterator prev,
EntityHandle val1,
EntityHandle val2 )
{
if(val1 == 0 || val1 > val2)
return end();
// Empty
if (mHead.mNext == &mHead)
{
assert( prev == end() );
PairNode* new_node = alloc_pair( &mHead, &mHead, val1, val2 );
mHead.mNext = mHead.mPrev = new_node;
return iterator( mHead.mNext, val1 );
}
PairNode* iter = prev.mNode;
// If iterator is at end, set it to last.
// Thus if the hint was to append, we start searching
// at the end of the list.
if (iter == &mHead)
iter = mHead.mPrev;
// if hint (prev) is past insert position, reset it to the beginning.
if (iter != &mHead && iter->first > val2+1)
iter = mHead.mNext;
// If hint is bogus then search backwards
while (iter != mHead.mNext && iter->mPrev->second >= val1-1)
iter = iter->mPrev;
// Input range is before beginning?
if (iter->mPrev == &mHead && val2 < iter->first - 1)
{
PairNode* new_node = alloc_pair( iter, &mHead, val1, val2 );
mHead.mNext = iter->mPrev = new_node;
return iterator( mHead.mNext, val1 );
}
// Find first intersecting list entry, or the next entry
// if none intersects.
while (iter != &mHead && iter->second+1 < val1)
iter = iter->mNext;
// Need to insert new pair (don't intersect any existing pair)?
if (iter == &mHead || iter->first-1 > val2)
{
PairNode* new_node = alloc_pair( iter, iter->mPrev, val1, val2 );
iter->mPrev = iter->mPrev->mNext = new_node;
return iterator( iter->mPrev, val1 );
}
// Make the first intersecting pair the union of itself with [val1,val2]
if (iter->first > val1)
iter->first = val1;
if (iter->second >= val2)
return iterator( iter, val1 );
iter->second = val2;
// Merge any remaining pairs that intersect [val1,val2]
while (iter->mNext != &mHead && iter->mNext->first <= val2 + 1)
{
PairNode* dead = iter->mNext;
iter->mNext = dead->mNext;
dead->mNext->mPrev = iter;
if (dead->second > val2)
iter->second = dead->second;
free_pair( dead );
}
return iterator( iter, val1 );
}
/*!
erases an item from this list and returns an iterator to the next item
*/
Range::iterator Range::erase(iterator iter)
{
// one of a few things could happen
// 1. shrink a range
// 2. split a range
// 3. remove a range
if(iter == end())
return end();
// the iterator most likely to be returned
iterator new_iter = iter;
++new_iter;
PairNode* kter = iter.mNode;
// just remove the range
if(kter->first == kter->second)
{
kter->mNext->mPrev = kter->mPrev;
kter->mPrev->mNext = kter->mNext;
free_pair( kter );
return new_iter;
}
// shrink it
else if(kter->first == iter.mValue)
{
kter->first++;
return new_iter;
}
// shrink it the other way
else if(kter->second == iter.mValue)
{
kter->second--;
return new_iter;
}
// split the range
else
{
PairNode* new_node = alloc_pair(iter.mNode->mNext, iter.mNode, iter.mValue+1, kter->second);
new_node->mPrev->mNext = new_node->mNext->mPrev = new_node;
iter.mNode->second = iter.mValue - 1;
new_iter = const_iterator(new_node, new_node->first);
return new_iter;
}
}
//! remove a range of items from the list
Range::iterator Range::erase( iterator iter1, iterator iter2)
{
iterator result;
if (iter1.mNode == iter2.mNode) {
if (iter2.mValue <= iter1.mValue) {
// empty range OK, otherwise invalid input
return iter2;
}
// If both iterators reference the same pair node, then
// we're either removing values from the front of the
// node or splitting the node. We can never be removing
// the last value in the node in this case because iter2
// points *after* the last entry to be removed.
PairNode* node = iter1.mNode;
if (iter1.mValue == node->first) {
node->first = iter2.mValue;
result = iter2;
}
else {
PairNode* new_node = alloc_pair( node->mNext, node, iter2.mValue, node->second );
new_node->mNext->mPrev = new_node;
new_node->mPrev->mNext = new_node;
node->second = iter1.mValue - 1;
result = iterator( new_node, new_node->first );
}
}
else {
if (iter1.mNode == &mHead)
return iter1;
PairNode* dn = iter1.mNode;
if (iter1.mValue > dn->first) {
dn->second = iter1.mValue-1;
dn = dn->mNext;
}
if (iter2.mNode != &mHead)
iter2.mNode->first = iter2.mValue;
while (dn != iter2.mNode) {
PairNode* dead = dn;
dn = dn->mNext;
dead->mPrev->mNext = dead->mNext;
dead->mNext->mPrev = dead->mPrev;
dead->mPrev = dead->mNext = 0;
delete dead;
}
result = iter2;
}
return result;
}
void Range::delete_pair_node( PairNode* node )
{
if (node != &mHead) { // pop_front() and pop_back() rely on this check
node->mPrev->mNext = node->mNext;
node->mNext->mPrev = node->mPrev;
free_pair( node );
}
}
//! remove first entity from range
EntityHandle Range::pop_front()
{
EntityHandle retval = front();
if (mHead.mNext->first == mHead.mNext->second) // need to remove pair from range
delete_pair_node( mHead.mNext );
else
++(mHead.mNext->first); // otherwise just adjust start value of pair
return retval;
}
//! remove last entity from range
EntityHandle Range::pop_back()
{
EntityHandle retval = back();
if (mHead.mPrev->first == mHead.mPrev->second) // need to remove pair from range
delete_pair_node( mHead.mPrev );
else
--(mHead.mPrev->second); // otherwise just adjust end value of pair
return retval;
}
/*!
finds a value in the list.
this method is preferred over other algorithms because
it can be found faster this way.
*/
Range::const_iterator Range::find(EntityHandle val) const
{
// iterator through the list
PairNode* iter = mHead.mNext;
for( ; iter != &mHead && (val > iter->second); iter=iter->mNext );
return ((iter->second >= val) && (iter->first <= val)) ? const_iterator(iter,val) : end();
}
/*!
merges another Range with this one
*/
void Range::insert( Range::const_iterator begini,
Range::const_iterator endi )
{
if (begini == endi)
return;
PairNode* node = begini.mNode;
if (endi.mNode == node)
{
insert( *begini, (*endi)-1 );
return;
}
Range::iterator hint = insert( *begini, node->second );
node = node->mNext;
while (node != endi.mNode)
{
hint = insert( hint, node->first, node->second );
node = node->mNext;
}
if (*endi > node->first)
{
if (*endi <= node->second)
insert( hint, node->first, *(endi) - 1 );
else
insert( hint, node->first, node->second );
}
}
#include <algorithm>
// checks the range to make sure everything is A-Ok.
void Range::sanity_check() const
{
if(empty())
return;
const PairNode* node = mHead.mNext;
std::vector<const PairNode*> seen_before;
bool stop_it = false;
for(; stop_it == false; node = node->mNext)
{
// have we seen this node before?
assert(std::find(seen_before.begin(), seen_before.end(), node) == seen_before.end());
seen_before.push_back(node);
// is the connection correct?
assert(node->mNext->mPrev == node);
// are the values right?
assert(node->first <= node->second);
if(node != &mHead && node->mPrev != &mHead)
assert(node->mPrev->second < node->first);
if(node == &mHead)
stop_it = true;
}
}
// for debugging
void Range::print(const char *indent_prefix) const
{
print(std::cout, indent_prefix);
}
void Range::print(std::ostream& stream, const char *indent_prefix) const
{
std::string indent_prefix_str;
if (NULL != indent_prefix) indent_prefix_str += indent_prefix;
if (empty()) {
stream << indent_prefix_str << "\tempty" << std::endl;
return;
}
for (const_pair_iterator i = const_pair_begin(); i != const_pair_end(); ++i) {
EntityType t1 = TYPE_FROM_HANDLE( i->first );
EntityType t2 = TYPE_FROM_HANDLE( i->second );
stream << indent_prefix_str << "\t" << CN::EntityTypeName( t1 ) << " "
<< ID_FROM_HANDLE( i->first );
if(i->first != i->second) {
stream << " - ";
if (t1 != t2)
stream << CN::EntityTypeName( t2 ) << " ";
stream << ID_FROM_HANDLE( i->second );
}
stream << std::endl;
}
}
// intersect two ranges, placing the results in the return range
#define MAX(a,b) (a < b ? b : a)
#define MIN(a,b) (a > b ? b : a)
Range intersect(const Range &range1, const Range &range2)
{
Range::const_pair_iterator r_it[2] = { range1.const_pair_begin(),
range2.const_pair_begin() };
EntityHandle low_it, high_it;
Range lhs;
Range::iterator hint = lhs.begin();
// terminate the while loop when at least one "start" iterator is at the
// end of the list
while (r_it[0] != range1.end() && r_it[1] != range2.end()) {
if (r_it[0]->second < r_it[1]->first)
// 1st subrange completely below 2nd subrange
++r_it[0];
else if (r_it[1]->second < r_it[0]->first)
// 2nd subrange completely below 1st subrange
++r_it[1];
else {
// else ranges overlap; first find greater start and lesser end
low_it = MAX(r_it[0]->first, r_it[1]->first);
high_it = MIN(r_it[0]->second, r_it[1]->second);
// insert into result
hint = lhs.insert(hint, low_it, high_it);
// now find bounds of this insertion and increment corresponding iterator
if (high_it == r_it[0]->second) ++r_it[0];
if (high_it == r_it[1]->second) ++r_it[1];
}
}
return lhs;
}
Range subtract(const Range &range1, const Range &range2)
{
const bool braindead = false;
if (braindead) {
// brain-dead implementation right now
Range res( range1 );
for (Range::const_iterator rit = range2.begin(); rit != range2.end(); ++rit)
res.erase(*rit);
return res;
}
else {
Range lhs( range1 );
Range::pair_iterator r_it0 = lhs.pair_begin();
Range::const_pair_iterator r_it1 = range2.const_pair_begin();
// terminate the while loop when at least one "start" iterator is at the
// end of the list
while (r_it0 != lhs.end() && r_it1 != range2.end()) {
// case a: pair wholly within subtracted pair
if (r_it0->first >= r_it1->first && r_it0->second <= r_it1->second) {
Range::PairNode *rtmp = r_it0.node();
++r_it0;
lhs.delete_pair_node(rtmp);
}
// case b: pair overlaps upper part of subtracted pair
else if (r_it0->first <= r_it1->second &&
r_it0->first >= r_it1->first) {
r_it0->first = r_it1->second + 1;
++r_it1;
}
// case c: pair overlaps lower part of subtracted pair
else if (r_it0->second >= r_it1->first &&
r_it0->second <= r_it1->second) {
r_it0->second = r_it1->first - 1;
++r_it0;
}
// case d: pair completely surrounds subtracted pair
else if (r_it0->first < r_it1->first &&
r_it0->second > r_it1->second) {
Range::PairNode* new_node = alloc_pair(r_it0.node(), r_it0.node()->mPrev,
r_it0->first, r_it1->first - 1);
new_node->mPrev->mNext = new_node->mNext->mPrev = new_node;
r_it0.node()->first = r_it1->second+1;
++r_it1;
}
else {
while (r_it0->second < r_it1->first && r_it0 != lhs.end()) ++r_it0;
if (r_it0 == lhs.end()) break;
while (r_it1->second < r_it0->first && r_it1 != range2.end()) ++r_it1;
}
}
return lhs;
}
}
Range &Range::operator-=(const Range &range2)
{
const bool braindead = false;
if (braindead) {
// brain-dead implementation right now
Range res( *this );
for (Range::const_iterator rit = range2.begin(); rit != range2.end(); ++rit)
res.erase(*rit);
return *this;
}
else {
Range::pair_iterator r_it0 = this->pair_begin();
Range::const_pair_iterator r_it1 = range2.const_pair_begin();
// terminate the while loop when at least one "start" iterator is at the
// end of the list
while (r_it0 != this->end() && r_it1 != range2.end()) {
// case a: pair wholly within subtracted pair
if (r_it0->first >= r_it1->first && r_it0->second <= r_it1->second) {
Range::PairNode *rtmp = r_it0.node();
++r_it0;
this->delete_pair_node(rtmp);
}
// case b: pair overlaps upper part of subtracted pair
else if (r_it0->first <= r_it1->second &&
r_it0->first >= r_it1->first) {
r_it0->first = r_it1->second + 1;
++r_it1;
}
// case c: pair overlaps lower part of subtracted pair
else if (r_it0->second >= r_it1->first &&
r_it0->second <= r_it1->second) {
r_it0->second = r_it1->first - 1;
++r_it0;
}
// case d: pair completely surrounds subtracted pair
else if (r_it0->first < r_it1->first &&
r_it0->second > r_it1->second) {
Range::PairNode* new_node = alloc_pair(r_it0.node(), r_it0.node()->mPrev,
r_it0->first, r_it1->first - 1);
new_node->mPrev->mNext = new_node->mNext->mPrev = new_node;
r_it0.node()->first = r_it1->second+1;
++r_it1;
}
else {
while (r_it0->second < r_it1->first && r_it0 != this->end()) ++r_it0;
if (r_it0 == this->end()) break;
while (r_it1->second < r_it0->first && r_it1 != range2.end()) ++r_it1;
}
}
return *this;
}
}
EntityID
operator-( const Range::const_iterator& it2, const Range::const_iterator& it1 )
{
assert( !it2.mValue || *it2 >= *it1 );
if (it2.mNode == it1.mNode) {
return *it2 - *it1;
}
EntityID result = it1.mNode->second - it1.mValue + 1;
for (Range::PairNode* n = it1.mNode->mNext; n != it2.mNode; n = n->mNext)
result += n->second - n->first + 1;
if (it2.mValue) // (it2.mNode != &mHead)
result += it2.mValue - it2.mNode->first;
return result;
}
Range::const_iterator Range::lower_bound(Range::const_iterator first,
Range::const_iterator last,
EntityHandle val)
{
// Find the first pair whose end is >= val
PairNode* iter;
for (iter = first.mNode; iter != last.mNode; iter = iter->mNext)
{
if (iter->second >= val)
{
// This is the correct pair. Either 'val' is in the range, or
// the range starts before 'val' and iter->first IS the lower_bound.
if (iter->first > val)
return const_iterator(iter, iter->first);
return const_iterator(iter, val);
}
}
if (iter->first >= val)
return const_iterator( iter, iter->first );
else if(*last > val)
return const_iterator( iter, val );
else
return last;
}
Range::const_iterator Range::upper_bound(Range::const_iterator first,
Range::const_iterator last,
EntityHandle val)
{
Range::const_iterator result = lower_bound( first, last, val );
if (result != last && *result == val)
++result;
return result;
}
Range::const_iterator Range::lower_bound( EntityType type ) const
{
int err;
EntityHandle handle = CREATE_HANDLE( type, 0, err );
return err ? end() : lower_bound( begin(), end(), handle );
}
Range::const_iterator Range::lower_bound( EntityType type,
const_iterator first ) const
{
int err;
EntityHandle handle = CREATE_HANDLE( type, 0, err );
return err ? end() : lower_bound( first, end(), handle );
}
Range::const_iterator Range::upper_bound( EntityType type ) const
{
// if (type+1) overflows, err will be true and we return end().
int err;
EntityHandle handle = CREATE_HANDLE( type + 1, 0, err );
return err ? end() : lower_bound( begin(), end(), handle );
}
Range::const_iterator Range::upper_bound( EntityType type,
const_iterator first ) const
{
// if (type+1) overflows, err will be true and we return end().
int err;
EntityHandle handle = CREATE_HANDLE( type + 1, 0, err );
return err ? end() : lower_bound( first, end(), handle );
}
std::pair<Range::const_iterator, Range::const_iterator>
Range::equal_range( EntityType type ) const
{
std::pair<Range::const_iterator, Range::const_iterator> result;
int err;
EntityHandle handle = CREATE_HANDLE( type, 0, err );
result.first = err ? end() : lower_bound( begin(), end(), handle );
// if (type+1) overflows, err will be true and we return end().
handle = CREATE_HANDLE( type+1, 0, err );
result.second = err ? end() : lower_bound( result.first, end(), handle );
return result;
}
bool Range::all_of_type( EntityType type ) const
{
return empty()
|| (TYPE_FROM_HANDLE(front()) == type
&& TYPE_FROM_HANDLE(back()) == type);
}
bool Range::all_of_dimension( int dimension ) const
{
return empty()
|| (CN::Dimension(TYPE_FROM_HANDLE(front())) == dimension
&& CN::Dimension(TYPE_FROM_HANDLE(back())) == dimension);
}
unsigned Range::num_of_type( EntityType type ) const
{
const_pair_iterator iter = const_pair_begin();
while(iter != const_pair_end() && TYPE_FROM_HANDLE((*iter).second) < type)
++iter;
unsigned count = 0;
for ( ; iter != const_pair_end(); ++iter)
{
EntityType start_type = TYPE_FROM_HANDLE((*iter).first);
EntityType end_type = TYPE_FROM_HANDLE((*iter).second);
if (start_type > type)
break;
EntityID sid = start_type < type ? 1 : ID_FROM_HANDLE((*iter).first);
EntityID eid = end_type > type ? MB_END_ID : ID_FROM_HANDLE((*iter).second);
count += eid - sid + 1;
}
return count;
}
unsigned Range::num_of_dimension( int dim ) const
{
const_pair_iterator iter = const_pair_begin();
while(iter != const_pair_end() && CN::Dimension(TYPE_FROM_HANDLE((*iter).second)) < dim)
++iter;
int junk;
unsigned count = 0;
for ( ; iter != const_pair_end(); ++iter)
{
int start_dim = CN::Dimension(TYPE_FROM_HANDLE((*iter).first));
int end_dim = CN::Dimension(TYPE_FROM_HANDLE((*iter).second));
if (start_dim > dim)
break;
EntityHandle sh = start_dim < dim ?
CREATE_HANDLE( CN::TypeDimensionMap[dim].first, 1, junk ) :
(*iter).first;
EntityHandle eh = end_dim > dim ?
CREATE_HANDLE( CN::TypeDimensionMap[dim].second, MB_END_ID, junk ) :
(*iter).second;
count += eh - sh + 1;
}
return count;
}
//! swap the contents of this range with another one
//! THIS FUNCTION MUST NOT BE INLINED, THAT WILL ELIMINATE RANGE_EMPTY AND THIS_EMPTY
//! BY SUBSTITUTION AND THE FUNCTION WON'T WORK RIGHT!
void Range::swap( Range &range )
{
// update next/prev nodes of head of both ranges
bool range_empty = (range.mHead.mNext == &(range.mHead));
bool this_empty = (mHead.mNext == &mHead);
range.mHead.mNext->mPrev = (range_empty ? &(range.mHead) : &mHead);
range.mHead.mPrev->mNext = (range_empty ? &(range.mHead) : &mHead);
mHead.mNext->mPrev = (this_empty ? &mHead : &(range.mHead));
mHead.mPrev->mNext = (this_empty ? &mHead : &(range.mHead));
// switch data in head nodes of both ranges
PairNode *range_next = range.mHead.mNext, *range_prev = range.mHead.mPrev;
range.mHead.mNext = (this_empty ? &(range.mHead) : mHead.mNext);
range.mHead.mPrev = (this_empty ? &(range.mHead) : mHead.mPrev);
mHead.mNext = (range_empty ? &mHead : range_next);
mHead.mPrev = (range_empty ? &mHead : range_prev);
}
//! return a subset of this range, by type
Range Range::subset_by_type(EntityType t) const
{
Range result;
std::pair<const_iterator, const_iterator> iters = equal_range(t);
result.insert( iters.first, iters.second );
return result;
}
//! return a subset of this range, by type
Range Range::subset_by_dimension( int d ) const
{
EntityHandle handle1 = CREATE_HANDLE( CN::TypeDimensionMap[d].first, 0 );
iterator st = lower_bound( begin(), end(), handle1 );
iterator en;
if (d < 4) { // dimension 4 is MBENTITYSET
EntityHandle handle2 = CREATE_HANDLE( CN::TypeDimensionMap[d+1].first, 0 );
en = lower_bound( st, end(), handle2 );
}
else {
en = end();
}
Range result;
result.insert( st, en );
return result;
}
bool operator==( const Range& r1, const Range& r2 )
{
Range::const_pair_iterator i1, i2;
i1 = r1.const_pair_begin();
i2 = r2.const_pair_begin();
for ( ; i1 != r1.const_pair_end(); ++i1, ++i2)
if (i2 == r2.const_pair_end() ||
i1->first != i2->first ||
i1->second != i2->second)
return false;
return i2 == r2.const_pair_end();
}
unsigned long Range::get_memory_use() const
{
unsigned long result = 0;
for (const PairNode* n = mHead.mNext; n != &mHead; n = n->mNext)
result += sizeof(PairNode);
return result;
}
bool Range::contains( const Range& othr ) const
{
if (othr.empty())
return true;
if (empty())
return false;
// neither range is empty, so both have valid pair nodes
// other than dummy mHead
const PairNode* this_node = mHead.mNext;
const PairNode* othr_node = othr.mHead.mNext;
for(;;) {
// Loop while the node in this list is entirely before
// the node in the other list.
while (this_node->second < othr_node->first) {
this_node = this_node->mNext;
if (this_node == &mHead)
return false;
}
// If other node is not entirely contained in this node
// then other list is not contained in this list
if (this_node->first > othr_node->first)
break;
// Loop while other node is entirely contained in this node.
while (othr_node->second <= this_node->second) {
othr_node = othr_node->mNext;
if (othr_node == &othr.mHead)
return true;
}
// If other node overlapped end of this node
if (othr_node->first <= this_node->second)
break;
}
// should be unreachable
return false;
}
} // namespace moab
| 28.947818 | 146 | 0.611255 | [
"mesh",
"vector"
] |
4ef163367f6b5197a80b70818c9a37283f2c8785 | 109,071 | cpp | C++ | source/utils/dx12/backend/rg_dx12_frontend.cpp | clayne/RGA | 7ed370e00b635c5b558d4af4eb050e2a38f77e53 | [
"MIT"
] | 97 | 2020-03-12T01:47:49.000Z | 2022-03-16T02:29:04.000Z | source/utils/dx12/backend/rg_dx12_frontend.cpp | clayne/RGA | 7ed370e00b635c5b558d4af4eb050e2a38f77e53 | [
"MIT"
] | 34 | 2020-03-10T16:38:48.000Z | 2022-03-19T04:05:04.000Z | source/utils/dx12/backend/rg_dx12_frontend.cpp | clayne/RGA | 7ed370e00b635c5b558d4af4eb050e2a38f77e53 | [
"MIT"
] | 14 | 2020-03-13T00:50:23.000Z | 2022-01-31T09:06:54.000Z | // D3D12.
#include <d3d12.h>
#include <d3dcompiler.h>
#include <d3dcommon.h>
#include <wrl.h>
#include "../backend/d3dx12.h"
// C++.
#include <cassert>
#include <iostream>
#include <sstream>
#include <locale>
#include <codecvt>
#include <vector>
#include <iomanip>
#include <algorithm>
// Local.
#include "rg_dx12_frontend.h"
#include "rg_dx12_utils.h"
#include "rg_dx12_factory.h"
#include "rg_dxr_state_desc_reader.h"
#include "rg_dxr_output_metadata.h"
// Backend.
#include "be_d3d_include_manager.h"
namespace rga
{
// *** CONSTANTS - START ***
// Errors.
static const char* kStrErrorRootSignatureExtractionFailure = "Error: failed to extract root signature from DXCB binary.";
static const char* kStrErrorLocalRootSignatureCreateFromFileFailure = "Error: failed to create local root signature from file: ";
static const char* kStrErrorGlobalRootSignatureCreateFromFileFailure = "Error: failed to create global root signature from file: ";
static const char* kStrErrorShaderCompilationFailure = "Error: failed to compile shader: ";
static const char* kStrErrorComputeShaderDisassemblyExtractionFailure = "Error: failed to extract GCN ISA disassembly for compute shader.";
static const char* kStrErrorGraphicsShaderDisassemblyExtractionFailure1 = "Error: failed to extract GCN ISA disassembly for ";
static const char* kStrErrorGraphicsShaderDisassemblyExtractionFailure2 = " shader.";
static const char* kStrErrorRootSignatureCompileFailure = "Error: failed to compile root signature.";
static const char* kStrErrorDxbcDisassembleFailure = "Error: failed to disassemble compute shader DXBC binary.";
static const char* kStrErrorExtractComputeShaderStatsFailure = "Error: failed to extract compute shader statistics.";
static const char* kStrErrorExtractComputeShaderDisassemblyFailure = "Error: failed to extract compute shader disassembly.";
static const char* kStrErrorExtractComputePipelineBinaryFailure = "Error: failed to extract compute pipeline binary.";
static const char* kStrErrorExtractGraphicsShaderStatsFailure = "Error: failed to extract graphics pipeline binary.";
static const char* kStrErrorExtractGraphicsShaderOutputFailure1 = "Error: failed to extract ";
static const char* kStrErrorExtractGraphicsShaderStatsFailure2 = " shader statistics.";
static const char* kStrErrorExtractGraphicsShaderDisassemblyFailure2 = " shader disassembly.";
static const char* kStrErrorFrontEndCompilationFailure = "Error: front-end compilation of hlsl to DXBC failed.";
static const char* kStrErrorFailedToFindDx12Adapter = "Error: failed to find a DX12 display adapter.";
static const char* kStrErrorGraphicsPipelineCreationFailure = "Error: graphics pipeline creation failed.";
static const char* kStrErrorGpsoFileParseFailed = "Error: failed to parse graphics pipeline description file.";
static const char* kStrErrorRsFileReadFailed = "Error: failed to read binary file for root signature: ";
static const char* kStrErrorRsFileCompileFailed = "Error: failed to compile root signature after reading binary data from file: ";
static const char* kStrErrorDxilFileReadFailed = "Error: failed to read binary DXIL library: ";
static const char* kStrErrorFailedToCreateDxrInterface = "Error: failed to initialize DXR interface.";
static const char* kStrErrorNoPipelineBinaryGeneratedForIndex = "Error: no pipeline binary generated for pipeline #";
static const char* kStrErrorDxrInputFileNotFound = "Error: DXR input file not found: ";
static const char* kStrErrorDxrLocalRootSignatureFileNotFound = "Error: local root signature file not found: ";
static const char* kStrErrorDxrGlobalRootSignatureFileNotFound = "Error: global root signature file not found: ";
static const char* kStrErrorDxrRootSignatureFailureHlsl1 = "Error: no root signature detected in HLSL code. If your root signature is defined in the HLSL code, make sure that "
"the [RootSignature()] attribute is used for";
static const char* kStrErrorDxrRootSignatureFailureHlsl2Graphics = " one of the pipeline's shaders ";
static const char* kStrErrorDxrRootSignatureFailureHlsl2Compute = " the compute shader ";
static const char* kStrErrorDxrRootSignatureFailureHlsl3 = "with the macro name as the argument, or use the --rs-macro option. If your root signature is precompiled into a binary, please use "
"the --rs-bin option with the full path to the binary file as an argument. For more information about root signatures in HLSL, "
"see https://docs.microsoft.com/en-us/windows/win32/direct3d12/specifying-root-signatures-in-hlsl#compiling-an-hlsl-root-signature";
static const char* kStrErrorFailedToWriteOutputFile1 = "Error: failed to write ";
static const char* kStrErrorFailedToWriteOutputFile2 = " file to ";
static const char* kStrErrorFailedToWriteOutputFile3 = "make sure that the path is valid.";
static const char* kStrErrorFailedToExtractRaytracingDisassembly = "Error: failed to extract disassembly.";
static const char* kStrErrorFailedToExtractRaytracingStatistics = "Error: failed to extract hardware resource usage statistics.";
static const char* kStrErrorFailedToExtractRaytracingBinary = "Error: failed to extract pipeline binary.";
static const char* kStrErrorFailedToCreateComputePipeline = "Error: compute pipeline state creation failed. ";
static const char* kStrErrorDxrShaderModeCompilationFailed = "Error: DXR shader mode compilation failed.";
static const char* kStrErrorDxrFailedToReadHlslToDxilMappingFile1 = "Error: failed to read ";
static const char* kStrErrorDxrFailedToParseHlslToDxilMappingFile1 = "Error: failed to parse ";
static const char* kStrErrorDxrdHlslToDxilMappingFile2 = "HLSL->DXIL mapping file.";
static const char* kStrErrorDxrFailedToRetrievePipelineShaderName = "Error: failed to retrieve shader name for shader #";
static const char* kStrErrorAmdDisplayAdapterNotFound = "Error: could not find an AMD display adapter on the system.";
// Warnings.
static const char* kStrWarningBinaryExtractionNotSupportedInIndirectMode = "Warning: pipeline binary extraction (-b option) is not supported when driver performs Indirect compilation.";
static const char* kStrWarningBinaryExtractionNotSupportedMultiplePipelines1 = "Warning: pipeline binary extraction skipped for pipeline #";
static const char* kStrWarningBinaryExtractionNotSupportedMultiplePipelines2 = " - there is currently no support for pipeline binary extraction when multiple pipelines are generated.";
// Info.
static const char* kStrInfoExtractComputeShaderStats = "Extracting compute shader statistics...";
static const char* kStrInfoExtractComputeShaderDisassembly = "Extracting compute shader disassembly...";
static const char* kStrInfoExtractGraphicsShaderDisassembly = " shader disassembly...";
static const char* kStrInfoExtractComputePipelineBinary = "Extracting compute pipeline binary...";
static const char* kStrInfoExtractGraphicsPipelineBinary = "Extracting graphics pipeline binary...";
static const char* kStrInfoExtractGraphicsShaderOutput1 = "Extracting ";
static const char* kStrInfoExtractGraphicsShaderStats2 = " shader statistics...";
static const char* kStrInfoExtractComputeShaderStatsSuccess = "Compute shader statistics extracted successfully.";
static const char* kStrInfoExtractComputeShaderDisassemblySuccess = "Compute shader disassembly extracted successfully.";
static const char* kStrInfoExtractComputePipelineBinarySuccess = "Compute pipeline binary extracted successfully.";
static const char* kStrInfoExtractGraphicsPipelineBinarySuccess = "Graphics pipeline binary extracted successfully.";
static const char* kStrInfoExtractGraphicsShaderStatsSuccess = " shader statistics extracted successfully.";
static const char* kStrInfoExtractGraphicsShaderDisassemblySuccess = " shader disassembly extracted successfully.";
static const char* kStrInfoExtractRayTracingDisassemblySuccess = "Disassembly extracted successfully.";
static const char* kStrInfoExtractRayTracingStatisticsSuccess = "Hardware resource usage statistics extracted successfully.";
static const char* kStrInfoExtractRayTracingBinarySuccess = "Pipeline binary extracted successfully.";
static const char* kStrInfoExtractRayTracingStatsShader = "Extracting statistics for shader ";
static const char* kStrInfoExtractRayTracingPipelineBinaryByRaygen = "Extracting pipeline binary for pipeline associated with raygeneration shader ";
static const char* kStrInfoExtractRayTracingDisassemblyPipelineByRaygen = "Extracting disassembly for pipeline associated with raygeneration shader ";
static const char* kStrInfoExtractRayTracingResourceUsagePipelineByRaygen = "Extracting hardware resource usage for pipeline associated with raygeneration shader ";
static const char* kStrInfoExtractRayTracingPipelineBinaryByIndex1 = "Extracting pipeline binary for pipeline #";
static const char* kStrInfoExtractRayTracingDisassemblyPipelineByIndex1 = "Extracting disassembly for pipeline #";
static const char* kStrInfoExtractRayTracingResourceUsagePipelineByIndex1 = "Extracting hardware resource usage for pipeline #";
static const char* kStrInfoExtractRayTracingResultByIndex2 = " for shader ";
static const char* kStrInfoExtractRayTracingDisassemblyShader = "Extracting disassembly for shader ";
static const char* kStrInfoCompilingRootSignatureFromHlsl1 = "Compiling root signature defined in HLSL file ";
static const char* kStrInfoCompilingRootSignatureFromHlsl2 = " in macro named ";
static const char* kStrHintRootSignatureFailure = "Hint: this failure could be due to a missing or incompatible root signature.\n"
"1. If your root signature is defined in the HLSL code, make sure that the [RootSignature()] attribute is used for one of the pipeline shaders "
"with the macro name, or use the --rs-macro option.\n2. If your root signature is precompiled into a binary, please use the --rs-bin "
"option with the full path to the binary file as an argument.";
static const char* kStrInfoDxrPipelineCompiledUnified = "Pipeline compiled in Unified mode, expect a single uber shader in the output.";
static const char* kStrInfoDxrPipelineCompiledIndirect1 = "Pipeline compiled in Indirect mode, expect ";
static const char* kStrInfoDxrPipelineCompiledIndirect2 = " shaders in the output.";
static const char* kStrInfoDxrPipelineCompilationGenerated1 = "Compilation generated ";
static const char* kStrInfoDxrPipelineCompilationGeneratedMultiplePipelines2 = " pipelines.";
static const char* kStrInfoDxrPipelineCompilationGeneratedSinglePipeline2 = " pipeline.";
static const char* kStrInfoDxrPipelineTypeReport1 = "Pipeline #";
static const char* kStrInfoDxrPipelineTypeReport2 = " associated with raygeneration shader ";
// *** CONSTANTS - END ***
// *** STATICALLY-LINKED UTITILIES - START ***
static void Dx12StatsToString(const RgDx12ShaderResults& stats, std::stringstream& serialized_stats)
{
serialized_stats << "Statistics:" << std::endl;
serialized_stats << " - shaderStageMask = " << stats.shader_mask << std::endl;
serialized_stats << " - resourceUsage.numUsedVgprs = " << stats.vgpr_used << std::endl;
serialized_stats << " - resourceUsage.numUsedSgprs = " << stats.sgpr_used << std::endl;
serialized_stats << " - resourceUsage.ldsSizePerLocalWorkGroup = " << stats.lds_available_bytes << std::endl;
serialized_stats << " - resourceUsage.ldsUsageSizeInBytes = " << stats.lds_used_bytes << std::endl;
serialized_stats << " - resourceUsage.scratchMemUsageInBytes = " << stats.scratch_used_bytes << std::endl;
serialized_stats << " - numPhysicalVgprs = " << stats.vgpr_physical << std::endl;
serialized_stats << " - numPhysicalSgprs = " << stats.sgpr_physical << std::endl;
serialized_stats << " - numAvailableVgprs = " << stats.vgpr_available << std::endl;
serialized_stats << " - numAvailableSgprs = " << stats.sgpr_available << std::endl;
}
static void Dx12StatsToStringRayTracing(const RgDx12ShaderResultsRayTracing& stats, std::stringstream& serialized_stats)
{
// Serialize the common part.
Dx12StatsToString(stats, serialized_stats);
#ifdef _DXR_STATS_ENABLED
// These are currently not supported by the driver.
// Add DXR-specific part.
serialized_stats << " - stackSizeBytes = " << stats.stack_size_bytes << std::endl;
serialized_stats << " - isInlined = " << (stats.is_inlined ? "yes" : "no") << std::endl;
#endif
}
// Serialize a graphics shader's statistics.
static bool SerializeDx12StatsGraphics(const RgDx12ShaderResults& stats, const std::string& output_filename)
{
// Convert the statistics to string.
std::stringstream serialized_stats;
Dx12StatsToString(stats, serialized_stats);
// Write the results to the output file.
bool ret = RgDx12Utils::WriteTextFile(output_filename, serialized_stats.str());
assert(ret);
return ret;
}
// Serialize a compute shader's statistics including the thread group dimensions.
static bool SerializeDx12StatsCompute(const RgDx12ShaderResults& stats, const RgDx12ThreadGroupSize& thread_group_size,
const std::string& output_filename)
{
// Serialize the common shader stats.
std::stringstream serialized_stats;
Dx12StatsToString(stats, serialized_stats);
// Serialize and append the compute thread group size.
serialized_stats << " - computeWorkGroupSizeX" << " = " << thread_group_size.x << std::endl;
serialized_stats << " - computeWorkGroupSizeY" << " = " << thread_group_size.y << std::endl;
serialized_stats << " - computeWorkGroupSizeZ" << " = " << thread_group_size.z << std::endl;
// Write the results to the output file.
bool ret = RgDx12Utils::WriteTextFile(output_filename, serialized_stats.str());
assert(ret);
return ret;
}
// Serialize a raytracing pipeline statistics.
static bool SerializeDx12StatsRayTracing(const RgDx12ShaderResultsRayTracing& stats,
const std::string& output_filename)
{
// Serialize.
std::stringstream serialized_stats;
Dx12StatsToStringRayTracing(stats, serialized_stats);
// Write the results to the output file.
bool ret = RgDx12Utils::WriteTextFile(output_filename, serialized_stats.str());
assert(ret);
return ret;
}
static bool CreateDefaultRootSignature(ID3D12Device* d3d12_device, ID3D12RootSignature*& d3d_root_signature)
{
bool ret = false;
assert(d3d12_device != nullptr);
if (d3d12_device != nullptr)
{
D3D12_ROOT_SIGNATURE_DESC root_signature_desc;
memset(&root_signature_desc, 0, sizeof(root_signature_desc));
root_signature_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
ComPtr<ID3DBlob> signature;
ComPtr<ID3DBlob> error;
D3D12SerializeRootSignature(&root_signature_desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error);
d3d12_device->CreateRootSignature(0, signature->GetBufferPointer(),
signature->GetBufferSize(), IID_PPV_ARGS(&d3d_root_signature));
assert(d3d_root_signature != nullptr);
ret = (d3d_root_signature != nullptr);
}
return ret;
}
static std::string ExtractFileDirectory(const std::string& full_path)
{
std::string ret;
size_t pos = full_path.rfind('\\');
if (pos != std::string::npos)
{
ret = full_path.substr(0, pos);
}
return ret;
}
static bool CompileHlslShader(const RgDx12Config& config, const std::string& hlsl_full_path,
const std::string& entry_point, const std::string& shader_model,
D3D12_SHADER_BYTECODE& bytecode, std::string& error_msg)
{
bool ret = false;
// Convert the shader file name to wide characters.
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring hlsl_full_path_wide = converter.from_bytes(hlsl_full_path);
// Extract the hlsl file's folder and instantiate the include manager.
std::string hlsl_file_folder = ExtractFileDirectory(hlsl_full_path);
D3dIncludeManager include_manager(hlsl_file_folder.c_str(), config.include_dirs);
// Preprocessor definitions.
D3D_SHADER_MACRO* macros = new D3D_SHADER_MACRO[config.defines.size() + 1]{};
// Handle the defines.
if (!config.defines.empty())
{
int i = 0;
for (const auto& preprocessor_define : config.defines)
{
std::vector<std::string> macro_parts;
RgDx12Utils::SplitString(preprocessor_define, '=', macro_parts);
assert(macro_parts.size() > 0 && macro_parts.size() < 3);
if (macro_parts.size() > 0 && macro_parts.size() < 3)
{
macros[i].Name = new char[macro_parts[0].size() + 1]{};
memcpy((void*)macros[i].Name, macro_parts[0].data(), macro_parts[0].size());
if (macro_parts.size() > 1)
{
// This is a X=Y macro.
macros[i].Definition = new char[macro_parts[1].size() + 1]{};
memcpy((void*)macros[i].Definition, macro_parts[1].data(), macro_parts[1].size());
}
else
{
// This is just a definition.
macros[i].Definition = "";
}
i++;
}
}
}
// Front-end compilation.
ComPtr<ID3DBlob> compiled_blob;
ComPtr<ID3DBlob> error_messages;
UINT compile_flags = 0;
HRESULT hr = D3DCompileFromFile(hlsl_full_path_wide.c_str(), macros, &include_manager,
entry_point.c_str(), shader_model.c_str(),
compile_flags, 0, &compiled_blob, &error_messages);
assert(hr == S_OK);
if (hr == S_OK)
{
// Extract the byte code.
bytecode.BytecodeLength = compiled_blob->GetBufferSize();
char* buffer = new char[bytecode.BytecodeLength]();
memcpy(buffer, compiled_blob->GetBufferPointer(), bytecode.BytecodeLength);
bytecode.pShaderBytecode = buffer;
ret = true;
}
else
{
if (error_messages != nullptr && error_messages->GetBufferSize() > 0)
{
std::cerr << (char*)error_messages->GetBufferPointer() << std::endl;;
}
std::cerr << kStrErrorFrontEndCompilationFailure << std::endl;
}
// Clean up.
for (size_t i = 1; i < config.defines.size(); i++)
{
delete[] macros[i].Name;
macros[i].Name = nullptr;
delete[] macros[i].Definition;
macros[i].Definition = nullptr;
}
delete[] macros;
macros = nullptr;
return ret;
}
static bool ReadDxbcBinary(const std::string& dxbc_full_path, D3D12_SHADER_BYTECODE& bytecode)
{
bool ret = false;
// Read the compiled DXBC from a file.
std::vector<char> compiled_shader;
bool is_dxbc_binary_read = RgDx12Utils::ReadBinaryFile(dxbc_full_path, compiled_shader);
assert(is_dxbc_binary_read);
if (is_dxbc_binary_read)
{
char* buffer = new char[compiled_shader.size()]();
memcpy(buffer, compiled_shader.data(), compiled_shader.size());
bytecode.pShaderBytecode = buffer;
bytecode.BytecodeLength = compiled_shader.size();
ret = true;
}
else
{
static const char* kStrErrorDxbcReadFailure = "Error: failed to read input DXBC binary: ";
std::cerr << kStrErrorDxbcReadFailure << dxbc_full_path << std::endl;
}
return ret;
}
static bool WriteDxbcFile(const D3D12_SHADER_BYTECODE& bytecode, const std::string& output_file)
{
char* buffer = (char*)bytecode.pShaderBytecode;
std::vector<char> comp_bytecode(buffer, buffer + bytecode.BytecodeLength);
bool is_file_written = RgDx12Utils::WriteBinaryFile(output_file, comp_bytecode);
assert(is_file_written);
return is_file_written;
}
static bool DisassembleDxbc(const D3D12_SHADER_BYTECODE& bytecode, const std::string& output_file)
{
bool ret = false;
ID3DBlob* disassembly = nullptr;
HRESULT hr = D3DDisassemble(bytecode.pShaderBytecode, bytecode.BytecodeLength, 0, "", &disassembly);
assert(hr == S_OK);
assert(disassembly != nullptr);
assert(disassembly->GetBufferSize() > 0);
if (SUCCEEDED(hr) && disassembly != nullptr && disassembly->GetBufferSize() > 0)
{
std::string dxbc_disassembly((char*)disassembly->GetBufferPointer(),
(char*)disassembly->GetBufferPointer() + disassembly->GetBufferSize());
ret = RgDx12Utils::WriteTextFile(output_file, dxbc_disassembly);
assert(ret);
}
else
{
std::cerr << kStrErrorDxbcDisassembleFailure << std::endl;
}
return ret;
}
static bool CompileRootSignature(const RgDx12Config& config, ComPtr<ID3DBlob>& compiled_rs)
{
bool ret = false;
if (!config.rs_macro_file.empty() && !config.rs_macro.empty())
{
std::cout << kStrInfoCompilingRootSignatureFromHlsl1 <<
config.rs_macro_file << kStrInfoCompilingRootSignatureFromHlsl2 <<
config.rs_macro << "..." << std::endl;
// Read the content of the HLSL file.
std::string hlsl_text;
bool is_file_read = RgDx12Utils::ReadTextFile(config.rs_macro_file, hlsl_text);
assert(is_file_read);
assert(!hlsl_text.empty());
if (is_file_read)
{
// Extract the HLSL file's folder and instantiate the include manager.
std::string hlslFileFolder = ExtractFileDirectory(config.rs_macro_file);
D3dIncludeManager includeManager(hlslFileFolder.c_str(), config.include_dirs);
// Root signature compilation.
ComPtr<ID3DBlob> error_messages;
HRESULT hr = D3DCompile(hlsl_text.c_str(), hlsl_text.size(), nullptr,
nullptr, &includeManager,
config.rs_macro.c_str(), config.rs_version.c_str(), 0, 0, &compiled_rs, &error_messages);
if (error_messages != nullptr)
{
std::cerr << (char*)error_messages->GetBufferPointer() << std::endl;
}
assert(hr == S_OK);
assert(compiled_rs != nullptr);
ret = SUCCEEDED(hr) && compiled_rs != nullptr;
if (!ret)
{
std::cerr << kStrErrorRootSignatureCompileFailure << std::endl;
}
}
}
return ret;
}
static bool CreateRootSignatureFromBinary(ID3D12Device* device, const std::string& full_path, ID3D12RootSignature*& root_signature)
{
// Read the root signature from the file and recreate it.
std::vector<char> rs_data;
std::vector<char> root_signature_buffer;
bool ret = RgDx12Utils::ReadBinaryFile(full_path, root_signature_buffer);
assert(ret);
if (ret)
{
device->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&root_signature));
assert(root_signature != nullptr);
ret = (root_signature != nullptr);
}
return ret;
}
// Generates a new name by replacing the token with the given specific name.
static std::string GenerateSpecificFileName(const std::string& basic_filename, const std::string& specific_filename)
{
const char kFilenameToken = '*';
std::string fixed_str;
std::vector<std::string> split_string;
RgDx12Utils::SplitString(basic_filename, kFilenameToken, split_string);
assert(split_string.size() == 2);
if (split_string.size() == 2)
{
std::stringstream fixed_stream;
fixed_stream << split_string[0].c_str() << specific_filename.c_str() << split_string[1].c_str();
fixed_str = fixed_stream.str();
}
return fixed_str;
}
static bool IsDxrInputValid(const RgDxrStateDesc& state_desc)
{
bool ret = true;
// Input files.
for (const std::shared_ptr<RgDxrDxilLibrary>& local_rs : state_desc.input_files)
{
if (!RgDx12Utils::IsFileExists(local_rs->full_path))
{
std::cout << kStrErrorDxrInputFileNotFound << local_rs->full_path << std::endl;
ret = false;
break;
}
}
if (ret)
{
// Local root signatures.
for (const std::shared_ptr<RgDxrRootSignature>& local_rs : state_desc.local_root_signature)
{
if (!RgDx12Utils::IsFileExists(local_rs->full_path))
{
std::cout << kStrErrorDxrLocalRootSignatureFileNotFound << local_rs->full_path << std::endl;
ret = false;
break;
}
}
if (ret)
{
// Global root signatures.
for (const std::shared_ptr<RgDxrRootSignature>& global_rs : state_desc.global_root_signature)
{
if (!RgDx12Utils::IsFileExists(global_rs->full_path))
{
std::cout << kStrErrorDxrGlobalRootSignatureFileNotFound << global_rs->full_path << std::endl;
ret = false;
break;
}
else
{
std::cout << "Root signature compiled successfully." << std::endl;
}
}
}
}
return ret;
}
static void ReadHlslMappingFile(const std::string& dxr_hlsl_mapping, std::map<std::string, std::string>& hlsl_dxil_mapping)
{
std::string mapping_content;
bool is_hlsl_mapping_file_read = RgDx12Utils::ReadTextFile(dxr_hlsl_mapping, mapping_content);
assert(is_hlsl_mapping_file_read);
if (is_hlsl_mapping_file_read)
{
try
{
// Filter out newlines.
mapping_content.erase(std::remove(mapping_content.begin(), mapping_content.end(), '\n'), mapping_content.end());
// Extract the HLSL->DXIL mapping.
std::vector <std::string> mapping_components;
RgDx12Utils::SplitString(mapping_content, '$', mapping_components);
assert(!mapping_components.empty());
assert(mapping_components.size() % 2 == 0);
for (uint32_t i = 0; i < mapping_components.size() - 1; i += 2)
{
hlsl_dxil_mapping[mapping_components[i]] = mapping_components[i + 1];
}
}
catch (const std::exception&)
{
std::cerr << kStrErrorDxrFailedToParseHlslToDxilMappingFile1 <<
kStrErrorDxrdHlslToDxilMappingFile2 << std::endl;
}
}
else
{
std::cerr << kStrErrorDxrFailedToReadHlslToDxilMappingFile1 <<
kStrErrorDxrdHlslToDxilMappingFile2 << std::endl;
}
}
// *** STATICALLY-LINKED UTITILIES - END ***
bool rgDx12Frontend::CreateComputePipeline(const RgDx12Config& config,
D3D12_COMPUTE_PIPELINE_STATE_DESC*& compute_pso,
std::string& error_msg) const
{
bool ret = false;
compute_pso = new D3D12_COMPUTE_PIPELINE_STATE_DESC();
// If the input is DXBC binary, we do not need front-end compilation.
bool is_front_end_compilation_required = !config.comp.hlsl.empty();
// If the root signature was already created, use it. Otherwise,
// try to extract it from the DXBC binary after compiling the HLSL code.
bool should_extract_root_signature = !config.rs_macro.empty();
// Check if the user provided a serialized root signature file.
bool is_serialized_root_signature = !config.rs_serialized.empty();
// Buffer to hold DXBC compiled shader.
D3D12_SHADER_BYTECODE bytecode;
HRESULT hr = E_FAIL;
if (is_front_end_compilation_required)
{
// Compile the HLSL file.
ret = CompileHlslShader(config, config.comp.hlsl, config.comp.entry_point,
config.comp.shader_model, bytecode, error_msg);
assert(ret);
if (ret)
{
compute_pso->CS = bytecode;
}
else
{
error_msg = kStrErrorShaderCompilationFailure;
error_msg.append("compute\n");
}
}
else
{
// Read the compiled HLSL binary.
ret = ReadDxbcBinary(config.comp.dxbc, bytecode);
assert(ret);
if (ret)
{
compute_pso->CS = bytecode;
}
}
if (!config.comp.dxbcOut.empty())
{
// If the user wants to dump the bytecode as a binary, do it here.
bool is_dxbc_written = WriteDxbcFile(bytecode, config.comp.dxbcOut);
assert(is_dxbc_written);
}
if (ret)
{
if (!config.comp.dxbc_disassembly.empty())
{
// If the user wants to dump the bytecode disassembly, do it here.
bool is_dxbc_disassembly_generated = DisassembleDxbc(bytecode, config.comp.dxbc_disassembly);
assert(is_dxbc_disassembly_generated);
}
if (should_extract_root_signature)
{
// If the input is HLSL, we need to compile the root signature out of the HLSL file.
// Otherwise, if the input is a DXBC binary and it has a root signature baked into it,
// then the root signature would be automatically fetched from the binary, there is no
// need to set it into the PSO's root signature field.
ComPtr<ID3DBlob> compiled_rs;
ret = CompileRootSignature(config, compiled_rs);
if (ret)
{
// Create the root signature through the device and assign it to our PSO.
std::vector<uint8_t> root_signature_buffer;
root_signature_buffer.resize(compiled_rs->GetBufferSize());
memcpy(root_signature_buffer.data(), compiled_rs->GetBufferPointer(),
compiled_rs->GetBufferSize());
device_.Get()->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&compute_pso->pRootSignature));
assert(compute_pso->pRootSignature != nullptr);
ret = compute_pso->pRootSignature != nullptr;
}
}
else if (is_serialized_root_signature)
{
// Read the root signature from the file and recreate it.
std::vector<char> root_signature_buffer;
ret = RgDx12Utils::ReadBinaryFile(config.rs_serialized, root_signature_buffer);
assert(ret);
if (ret)
{
device_.Get()->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&compute_pso->pRootSignature));
assert(compute_pso->pRootSignature != nullptr);
ret = compute_pso->pRootSignature != nullptr;
}
}
else
{
// If we got here, it means that the user did not explicitly provide a root
// signature (using --rs-bin or --rs-macro). Therefore, the assumption is that
// the root signature was defined in HLSL code. By trying to explicitly create the
// root signature from the blob, we effectively check if a root signature was
// properly defined in the HLSL code.
device_.Get()->CreateRootSignature(0, bytecode.pShaderBytecode,
bytecode.BytecodeLength, IID_PPV_ARGS(&compute_pso->pRootSignature));
assert(compute_pso->pRootSignature != nullptr);
ret = compute_pso->pRootSignature != nullptr;
if (!ret)
{
std::cout << kStrErrorDxrRootSignatureFailureHlsl1 <<
kStrErrorDxrRootSignatureFailureHlsl2Compute << kStrErrorDxrRootSignatureFailureHlsl3 << std::endl;
}
}
}
return ret;
}
static bool CompileGraphicsShaders(const RgDx12Config& config,
RgDx12PipelineByteCode& bytecode, D3D12_GRAPHICS_PIPELINE_STATE_DESC*& pso,
std::string& error_msg)
{
bool ret = false;
// If the input is DXBC binary, we do not need front-end compilation.
RgPipelineBool is_front_end_compilation_required;
is_front_end_compilation_required.vert = !config.vert.hlsl.empty();
is_front_end_compilation_required.hull = !config.hull.hlsl.empty();
is_front_end_compilation_required.domain = !config.domain.hlsl.empty();
is_front_end_compilation_required.geom = !config.geom.hlsl.empty();
is_front_end_compilation_required.pixel = !config.pixel.hlsl.empty();
// Vertex.
if (is_front_end_compilation_required.vert)
{
// Compile the vertex shader.
ret = CompileHlslShader(config, config.vert.hlsl, config.vert.entry_point,
config.vert.shader_model, bytecode.vert, error_msg);
assert(ret);
if (ret)
{
pso->VS = bytecode.vert;
}
else
{
error_msg = kStrErrorShaderCompilationFailure;
error_msg.append("vertex\n");
}
}
else if (!config.vert.dxbc.empty())
{
// Read the compiled vertex shader.
ret = ReadDxbcBinary(config.vert.dxbc, bytecode.vert);
assert(ret);
if (ret)
{
pso->VS = bytecode.vert;
}
}
// Hull.
if (is_front_end_compilation_required.hull)
{
// Compile the hull shader.
ret = CompileHlslShader(config, config.hull.hlsl, config.hull.entry_point,
config.hull.shader_model, bytecode.vert, error_msg);
assert(ret);
if (ret)
{
pso->HS = bytecode.hull;
}
else
{
error_msg = kStrErrorShaderCompilationFailure;
error_msg.append("hull\n");
}
}
else if (!config.hull.dxbc.empty())
{
// Read the compiled hull shader.
ret = ReadDxbcBinary(config.hull.dxbc, bytecode.hull);
assert(ret);
if (ret)
{
pso->HS = bytecode.hull;
}
}
// Domain.
if (is_front_end_compilation_required.domain)
{
// Compile the domain shader.
ret = CompileHlslShader(config, config.domain.hlsl, config.domain.entry_point,
config.domain.shader_model, bytecode.domain, error_msg);
assert(ret);
if (ret)
{
pso->DS = bytecode.domain;
}
else
{
error_msg = kStrErrorShaderCompilationFailure;
error_msg.append("domain\n");
}
}
else if (!config.domain.dxbc.empty())
{
// Read the compiled domain shader.
ret = ReadDxbcBinary(config.domain.dxbc, bytecode.domain);
assert(ret);
if (ret)
{
pso->DS = bytecode.domain;
}
}
// Geometry.
if (is_front_end_compilation_required.geom)
{
// Compile the geometry shader.
ret = CompileHlslShader(config, config.geom.hlsl, config.geom.entry_point,
config.geom.shader_model, bytecode.geom, error_msg);
assert(ret);
if (ret)
{
pso->GS = bytecode.geom;
}
else
{
error_msg = kStrErrorShaderCompilationFailure;
error_msg.append("geometry\n");
}
}
else if (!config.geom.dxbc.empty())
{
// Read the compiled geometry shader.
ret = ReadDxbcBinary(config.geom.dxbc, bytecode.geom);
assert(ret);
if (ret)
{
pso->GS = bytecode.geom;
}
}
// Pixel.
if (is_front_end_compilation_required.pixel)
{
// Compile the pixel shader.
ret = CompileHlslShader(config, config.pixel.hlsl, config.pixel.entry_point,
config.pixel.shader_model, bytecode.pixel, error_msg);
assert(ret);
if (ret)
{
pso->PS = bytecode.pixel;
}
else
{
error_msg = kStrErrorShaderCompilationFailure;
error_msg.append("pixel\n");
}
}
else if (!config.pixel.dxbc.empty())
{
// Read the compiled pixel shader.
ret = ReadDxbcBinary(config.pixel.dxbc, bytecode.pixel);
assert(ret);
if (ret)
{
pso->PS = bytecode.pixel;
}
}
return ret;
}
static void DumpDxbcBinaries(const RgDx12Config& config, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pso)
{
if (!config.vert.dxbcOut.empty())
{
bool is_dxbc_written = WriteDxbcFile(pso.VS, config.vert.dxbcOut);
assert(is_dxbc_written);
}
if (!config.hull.dxbcOut.empty())
{
bool is_dxbc_written = WriteDxbcFile(pso.HS, config.hull.dxbcOut);
assert(is_dxbc_written);
}
if (!config.domain.dxbcOut.empty())
{
bool is_dxbc_written = WriteDxbcFile(pso.DS, config.domain.dxbcOut);
assert(is_dxbc_written);
}
if (!config.geom.dxbcOut.empty())
{
bool is_dxbc_written = WriteDxbcFile(pso.GS, config.geom.dxbcOut);
assert(is_dxbc_written);
}
if (!config.pixel.dxbcOut.empty())
{
bool is_dxbc_written = WriteDxbcFile(pso.PS, config.pixel.dxbcOut);
assert(is_dxbc_written);
}
}
static void DumpDxbcDisassembly(const RgDx12Config& config, const RgDx12PipelineByteCode& bytecode)
{
if (!config.vert.dxbc_disassembly.empty())
{
bool isDxbcDisassemblyGenerated = DisassembleDxbc(bytecode.vert, config.vert.dxbc_disassembly);
assert(isDxbcDisassemblyGenerated);
}
if (!config.hull.dxbc_disassembly.empty())
{
bool isDxbcDisassemblyGenerated = DisassembleDxbc(bytecode.hull, config.hull.dxbc_disassembly);
assert(isDxbcDisassemblyGenerated);
}
if (!config.domain.dxbc_disassembly.empty())
{
bool isDxbcDisassemblyGenerated = DisassembleDxbc(bytecode.domain, config.domain.dxbc_disassembly);
assert(isDxbcDisassemblyGenerated);
}
if (!config.geom.dxbc_disassembly.empty())
{
bool isDxbcDisassemblyGenerated = DisassembleDxbc(bytecode.geom, config.geom.dxbc_disassembly);
assert(isDxbcDisassemblyGenerated);
}
if (!config.pixel.dxbc_disassembly.empty())
{
bool isDxbcDisassemblyGenerated = DisassembleDxbc(bytecode.pixel, config.pixel.dxbc_disassembly);
assert(isDxbcDisassemblyGenerated);
}
}
bool rgDx12Frontend::CreateGraphicsPipeline(const RgDx12Config& config,
D3D12_GRAPHICS_PIPELINE_STATE_DESC*& pso, std::string& error_msg) const
{
bool ret = false;
// Create and initialize graphics pipeline state descriptor.
pso = new D3D12_GRAPHICS_PIPELINE_STATE_DESC();
RgDx12Utils::InitGraphicsPipelineStateDesc(*pso);
// If the root signature was already created, use it. Otherwise,
// try to extract it from the DXBC binary after compiling the HLSL code.
bool should_extract_root_signature = !config.rs_macro.empty();
// Check if the user provided a serialized root signature file.
bool is_serialized_root_signature = !config.rs_serialized.empty();
RgDx12PipelineByteCode bytecode = {};
HRESULT hr = E_FAIL;
// Compile the graphics pipeline shaders.
ret = CompileGraphicsShaders(config, bytecode, pso, error_msg);
// If the user wants to dump the bytecode as a binary, do it here.
DumpDxbcBinaries(config, *pso);
assert(ret);
if (ret)
{
// If the user wants to dump the bytecode disassembly, do it here.
DumpDxbcDisassembly(config, bytecode);
if (should_extract_root_signature)
{
ComPtr<ID3DBlob> compiled_rs;
ret = CompileRootSignature(config, compiled_rs);
if (ret)
{
// Create the root signature through the device and assign it to our PSO.
std::vector<uint8_t> root_signature_buffer;
root_signature_buffer.resize(compiled_rs->GetBufferSize());
memcpy(root_signature_buffer.data(), compiled_rs->GetBufferPointer(),
compiled_rs->GetBufferSize());
device_.Get()->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&pso->pRootSignature));
assert(pso->pRootSignature != nullptr);
ret = pso->pRootSignature != nullptr;
}
}
else if (is_serialized_root_signature)
{
// Read the root signature from the file and recreate it.
std::vector<char> root_signature_buffer;
ret = RgDx12Utils::ReadBinaryFile(config.rs_serialized, root_signature_buffer);
assert(ret);
if (ret)
{
device_.Get()->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&pso->pRootSignature));
assert(pso->pRootSignature != nullptr);
ret = pso->pRootSignature != nullptr;
if (pso->pRootSignature == nullptr)
{
std::cerr << kStrErrorRsFileCompileFailed << config.rs_serialized << std::endl;
}
}
else
{
std::cerr << kStrErrorRsFileReadFailed << config.rs_serialized << std::endl;
}
}
else
{
// Make sure that the root signature exists in one of the blobs.
bool does_rs_exists = false;
// Go through each of the existing blobs, and try to create the root signature
// from it. If the root signature was defined together with the [RootSignature()]
// attribute in HLSL code, the root signature creation from the blob should succeed.
// Vert blob.
if (bytecode.vert.pShaderBytecode != nullptr && bytecode.vert.BytecodeLength > 0)
{
device_.Get()->CreateRootSignature(0, bytecode.vert.pShaderBytecode,
bytecode.vert.BytecodeLength, IID_PPV_ARGS(&pso->pRootSignature));
ret = pso->pRootSignature != nullptr;
does_rs_exists = (pso->pRootSignature != nullptr);
}
// Hull blob.
if (!does_rs_exists && bytecode.hull.pShaderBytecode != nullptr && bytecode.hull.BytecodeLength > 0)
{
device_.Get()->CreateRootSignature(0, bytecode.hull.pShaderBytecode,
bytecode.hull.BytecodeLength, IID_PPV_ARGS(&pso->pRootSignature));
ret = pso->pRootSignature != nullptr;
does_rs_exists = (pso->pRootSignature != nullptr);
}
// Domain blob.
if (!does_rs_exists && bytecode.domain.pShaderBytecode != nullptr && bytecode.domain.BytecodeLength > 0)
{
device_.Get()->CreateRootSignature(0, bytecode.domain.pShaderBytecode,
bytecode.domain.BytecodeLength, IID_PPV_ARGS(&pso->pRootSignature));
ret = pso->pRootSignature != nullptr;
does_rs_exists = (pso->pRootSignature != nullptr);
}
// Geometry blob.
if (!does_rs_exists && bytecode.geom.pShaderBytecode != nullptr && bytecode.geom.BytecodeLength > 0)
{
device_.Get()->CreateRootSignature(0, bytecode.geom.pShaderBytecode,
bytecode.geom.BytecodeLength, IID_PPV_ARGS(&pso->pRootSignature));
ret = pso->pRootSignature != nullptr;
does_rs_exists = (pso->pRootSignature != nullptr);
}
// Pixel blob.
if (!does_rs_exists && bytecode.pixel.pShaderBytecode != nullptr && bytecode.pixel.BytecodeLength > 0)
{
device_.Get()->CreateRootSignature(0, bytecode.pixel.pShaderBytecode,
bytecode.pixel.BytecodeLength, IID_PPV_ARGS(&pso->pRootSignature));
ret = pso->pRootSignature != nullptr;
does_rs_exists = (pso->pRootSignature != nullptr);
}
assert(does_rs_exists);
if (!does_rs_exists)
{
std::cout << kStrErrorDxrRootSignatureFailureHlsl1 <<
kStrErrorDxrRootSignatureFailureHlsl2Graphics << kStrErrorDxrRootSignatureFailureHlsl3 << std::endl;
}
}
}
return ret;
}
bool rgDx12Frontend::ExtractRootSignature(const D3D12_SHADER_BYTECODE& bytecode,
ID3D12RootSignature*& root_signature, std::string& error_msg) const
{
bool ret = false;
// Try to extract the root signature.
ComPtr<ID3DBlob> bytecode_root_signature;
HRESULT hr = D3DGetBlobPart(bytecode.pShaderBytecode, bytecode.BytecodeLength,
D3D_BLOB_ROOT_SIGNATURE, 0, &bytecode_root_signature);
if (SUCCEEDED(hr))
{
std::vector<uint8_t> root_signature_data;
root_signature_data.resize(bytecode_root_signature->GetBufferSize());
memcpy(root_signature_data.data(), bytecode_root_signature->GetBufferPointer(),
bytecode_root_signature->GetBufferSize());
device_.Get()->CreateRootSignature(0, root_signature_data.data(),
root_signature_data.size(), IID_PPV_ARGS(&root_signature));
assert(root_signature != nullptr);
ret = (root_signature != nullptr);
}
else
{
error_msg = kStrErrorRootSignatureExtractionFailure;
}
return ret;
}
bool rga::rgDx12Frontend::GetHardwareAdapter(IDXGIAdapter1** dxgi_adapter)
{
bool ret = false;
// Create the factory.
UINT dxgi_factory_flags = 0;
ComPtr<IDXGIFactory4> factory;
HRESULT hr = CreateDXGIFactory2(dxgi_factory_flags, IID_PPV_ARGS(&factory));
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
// Find the adapter.
ComPtr<IDXGIAdapter1> adapter;
*dxgi_adapter = nullptr;
for (UINT adapter_index = 0; DXGI_ERROR_NOT_FOUND !=
factory->EnumAdapters1(adapter_index, &adapter); ++adapter_index)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
// Look for a physical AMD display adapter.
const UINT kAmdVendorId = 0x1002;
if (desc.VendorId != kAmdVendorId || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE))
{
// Don't select the Basic Render Driver adapter.
continue;
}
if (SUCCEEDED(D3D12CreateDevice(adapter.Get(),
feature_level_, _uuidof(ID3D12Device), nullptr)))
{
ret = true;
break;
}
}
if (!ret)
{
std::cout << kStrErrorAmdDisplayAdapterNotFound << std::endl;
}
*dxgi_adapter = adapter.Detach();
}
return ret;
}
bool rgDx12Frontend::Init(bool is_dxr_session)
{
bool ret = false;
// Create the DXGI adapter.
ComPtr<IDXGIAdapter1> hw_adapter;
ret = GetHardwareAdapter(&hw_adapter);
assert(ret);
assert(hw_adapter != nullptr);
if (ret && hw_adapter != nullptr)
{
// Create the D3D12 device.
HRESULT hr = D3D12CreateDevice(hw_adapter.Get(),
feature_level_,
IID_PPV_ARGS(&device_));
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
// Initialize the backend with the D3D12 device.
ret = backend_.Init(device_.Get());
assert(ret);
if (ret && is_dxr_session)
{
// Create the DXR interface.
hr = device_->QueryInterface(IID_PPV_ARGS(&dxr_device_));
assert(SUCCEEDED(hr));
if (!SUCCEEDED(hr))
{
std::cout << kStrErrorFailedToCreateDxrInterface << std::endl;
}
}
}
}
else
{
std::cerr << kStrErrorFailedToFindDx12Adapter << std::endl;
}
return ret;
}
bool rgDx12Frontend::GetSupportedTargets(std::vector<std::string>& supported_targets,
std::map<std::string, unsigned>& target_to_id) const
{
return backend_.GetSupportedTargets(supported_targets, target_to_id);
}
bool rgDx12Frontend::CompileComputePipeline(const RgDx12Config& config, std::string& error_msg) const
{
D3D12_COMPUTE_PIPELINE_STATE_DESC* pso = nullptr;
bool ret = CreateComputePipeline(config, pso, error_msg);
assert(ret);
if (ret)
{
// Create the compute pipeline state.
ID3D12PipelineState* compute_pso = nullptr;
HRESULT hr = device_->CreateComputePipelineState(pso, IID_PPV_ARGS(&compute_pso));
assert(SUCCEEDED(hr));
ret = SUCCEEDED(hr);
if (ret)
{
RgDx12ShaderResults results;
RgDx12ThreadGroupSize thread_group_size;
std::vector<char> pipeline_binary;
ret = backend_.CompileComputePipeline(pso, results, thread_group_size, pipeline_binary, error_msg);
assert(ret);
if (ret)
{
if (!config.comp.isa.empty())
{
// Save results to file: GCN ISA disassembly.
assert(results.disassembly != nullptr);
if (results.disassembly != nullptr)
{
// GCN ISA Disassembly.
std::cout << kStrInfoExtractComputeShaderDisassembly << std::endl;
ret = RgDx12Utils::WriteTextFile(config.comp.isa, results.disassembly);
// Report the result to the user.
std::cout << (ret ? kStrInfoExtractComputeShaderDisassemblySuccess :
kStrErrorExtractComputeShaderDisassemblyFailure) << std::endl;
}
else
{
std::cerr << kStrErrorComputeShaderDisassemblyExtractionFailure << std::endl;
}
assert(ret);
}
if (!config.comp.stats.empty())
{
// Save results to file: statistics.
std::cout << kStrInfoExtractComputeShaderStats << std::endl;
bool isStatsSaved = SerializeDx12StatsCompute(results, thread_group_size, config.comp.stats);
assert(isStatsSaved);
ret = ret && isStatsSaved;
// Report the result to the user.
std::cout << (isStatsSaved ? kStrInfoExtractComputeShaderStatsSuccess :
kStrErrorExtractComputeShaderStatsFailure) << std::endl;
assert(ret);
}
if (!config.pipeline_binary.empty())
{
// Pipeline binary.
std::cout << kStrInfoExtractComputePipelineBinary << std::endl;
ret = !pipeline_binary.empty() && RgDx12Utils::WriteBinaryFile(config.pipeline_binary, pipeline_binary);
// Report the result to the user.
std::cout << (ret ? kStrInfoExtractComputePipelineBinarySuccess :
kStrErrorExtractComputePipelineBinaryFailure) << std::endl;
}
}
else if (!error_msg.empty())
{
// Print the error messages to the user.
std::cerr << error_msg << std::endl;
}
}
else
{
std::cerr << kStrErrorFailedToCreateComputePipeline << std::endl;
std::cerr << kStrHintRootSignatureFailure << std::endl;
}
}
return ret;
}
static bool WriteGraphicsShaderOutputFiles(const RgDx12ShaderConfig& shader_config,
const RgDx12ShaderResults& shader_results, const std::string& stage_name)
{
bool ret = true;
if (!shader_config.isa.empty())
{
// Save results to file: GCN ISA disassembly.
assert(shader_results.disassembly != nullptr);
if (shader_results.disassembly != nullptr)
{
// GCN ISA Disassembly.
std::cout << kStrInfoExtractGraphicsShaderOutput1 << stage_name <<
kStrInfoExtractGraphicsShaderDisassembly << std::endl;
ret = RgDx12Utils::WriteTextFile(shader_config.isa, shader_results.disassembly);
assert(ret);
// Report the result to the user.
if (ret)
{
std::cout << stage_name << kStrInfoExtractGraphicsShaderDisassemblySuccess << std::endl;
}
else
{
std::cerr << kStrErrorExtractGraphicsShaderOutputFailure1 << stage_name <<
kStrErrorExtractGraphicsShaderDisassemblyFailure2 << std::endl;
}
}
else
{
std::cerr << kStrErrorGraphicsShaderDisassemblyExtractionFailure1 << stage_name <<
kStrErrorGraphicsShaderDisassemblyExtractionFailure2 << std::endl;
}
}
if (!shader_config.stats.empty())
{
// Save results to file: statistics.
std::cout << kStrInfoExtractGraphicsShaderOutput1 << stage_name <<
kStrInfoExtractGraphicsShaderStats2 << std::endl;
bool isStatsSaved = SerializeDx12StatsGraphics(shader_results, shader_config.stats);
assert(isStatsSaved);
ret = ret && isStatsSaved;
// Report the result to the user.
if (isStatsSaved)
{
std::cout << stage_name << kStrInfoExtractGraphicsShaderStatsSuccess << std::endl;
}
else
{
std::cout << kStrErrorExtractGraphicsShaderOutputFailure1 << stage_name <<
kStrErrorExtractGraphicsShaderStatsFailure2 << std::endl;
}
}
return ret;
}
bool rgDx12Frontend::CompileGraphicsPipeline(const RgDx12Config& config, std::string& error_msg) const
{
D3D12_GRAPHICS_PIPELINE_STATE_DESC* pso = nullptr;
RgDx12PipelineResults results = {};
std::vector<char> pipeline_binary;
bool ret = CreateGraphicsPipeline(config, pso, error_msg);
assert(ret);
if (ret)
{
// Create the graphics pipeline state.
ID3D12PipelineState* graphics_pso = nullptr;
// For graphics, we must use a .gpso file.
bool is_pso_file_parsed = false;
if (!config.rs_pso.empty())
{
// Load the .gpso file that the user provided, and extract the
// relevant pipeline state.
is_pso_file_parsed = RgDx12Utils::ParseGpsoFile(config.rs_pso, *pso);
assert(is_pso_file_parsed);
}
else
{
// Use a default pso.
assert(false);
std::cout << "Warning: no pipeline state file received. Use the --gpso switch to provide a graphics pipeline description." << std::endl;
}
if (is_pso_file_parsed)
{
// Check if the user provided a serialized root signature file.
bool is_serialized_root_signature = !config.rs_serialized.empty();
// Read the root signature from the file and recreate it.
if (is_serialized_root_signature)
{
std::vector<char> root_signature_buffer;
ret = RgDx12Utils::ReadBinaryFile(config.rs_serialized, root_signature_buffer);
assert(ret);
if (ret)
{
device_.Get()->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&pso->pRootSignature));
assert(pso->pRootSignature != nullptr);
ret = pso->pRootSignature != nullptr;
}
}
else
{
// If the root signature was already created, use it. Otherwise,
// try to extract it from the DXBC binary after compiling the HLSL code.
bool should_extract_root_signature = !config.rs_macro.empty();
// If the input is HLSL, we need to compile the root signature out of the HLSL file.
// Otherwise, if the input is a DXBC binary and it has a root signature baked into it,
// then the root signature would be automatically fetched from the binary, there is no
// need to set it into the PSO's root signature field.
ComPtr<ID3DBlob> compiled_rs;
ret = CompileRootSignature(config, compiled_rs);
if (ret)
{
// Create the root signature through the device and assign it to our PSO.
std::vector<uint8_t> root_signature_buffer;
root_signature_buffer.resize(compiled_rs->GetBufferSize());
memcpy(root_signature_buffer.data(), compiled_rs->GetBufferPointer(),
compiled_rs->GetBufferSize());
device_.Get()->CreateRootSignature(0, root_signature_buffer.data(),
root_signature_buffer.size(), IID_PPV_ARGS(&pso->pRootSignature));
assert(pso->pRootSignature != nullptr);
ret = pso->pRootSignature != nullptr;
}
}
// Create the graphics pipeline.
HRESULT hr = device_->CreateGraphicsPipelineState(pso, IID_PPV_ARGS(&graphics_pso));
assert(SUCCEEDED(hr));
ret = SUCCEEDED(hr);
if (ret)
{
ret = backend_.CompileGraphicsPipeline(pso, results, pipeline_binary, error_msg);
assert(ret);
if (ret)
{
// Write the output files (for applicable stages).
ret = WriteGraphicsShaderOutputFiles(config.vert, results.vertex, "vertex");
assert(ret);
ret = WriteGraphicsShaderOutputFiles(config.hull, results.hull, "hull");
assert(ret);
ret = WriteGraphicsShaderOutputFiles(config.domain, results.domain, "domain");
assert(ret);
ret = WriteGraphicsShaderOutputFiles(config.geom, results.geometry, "geometry");
assert(ret);
ret = WriteGraphicsShaderOutputFiles(config.pixel, results.pixel, "pixel");
assert(ret);
// Write the pipeline binary file.
if (!config.pipeline_binary.empty())
{
std::cout << kStrInfoExtractGraphicsPipelineBinary << std::endl;
ret = !pipeline_binary.empty() && RgDx12Utils::WriteBinaryFile(config.pipeline_binary, pipeline_binary);
// Report the result to the user.
std::cout << (ret ? kStrInfoExtractGraphicsPipelineBinarySuccess :
kStrErrorExtractGraphicsShaderStatsFailure) << std::endl;
}
}
}
else
{
std::stringstream msg;
if (!error_msg.empty())
{
msg << std::endl;
}
msg << kStrErrorGraphicsPipelineCreationFailure << std::endl;
msg << kStrHintRootSignatureFailure << std::endl;
error_msg.append(msg.str());
}
}
else
{
std::cerr << kStrErrorGpsoFileParseFailed << std::endl;
}
}
return ret;
}
#ifdef RGA_DXR_ENABLED
bool rgDx12Frontend::CompileRayTracingPipeline(const RgDx12Config& config, std::string& error_msg) const
{
bool ret = false;
bool should_abort = false;
RgDxrStateDesc state_desc;
if (!config.dxr_hlsl_input.empty())
{
// If an HLSL input was given, we will only use the HLSL as an input, without
// reading the state data.
std::shared_ptr<RgDxrDxilLibrary> dxil_lib = std::make_shared<RgDxrDxilLibrary>();
dxil_lib->input_type = DxrSourceType::kHlsl;
dxil_lib->full_path = config.dxr_hlsl_input;
state_desc.input_files.push_back(dxil_lib);
}
else
{
// Read the input metadata file.
const char* kJsonInputFileName = config.dxr_state_file.c_str();
bool is_state_desc_read = RgDxrStateDescReader::ReadDxrStateDesc(kJsonInputFileName, state_desc, error_msg);
assert(is_state_desc_read);
should_abort = !is_state_desc_read;
if (!error_msg.empty())
{
std::cerr << error_msg << std::endl;
error_msg.clear();
}
}
if (!should_abort)
{
// Validate DXR input.
should_abort = !IsDxrInputValid(state_desc);
assert(!should_abort);
if (!should_abort)
{
// A map to hold the HLSL->DXIL mapping if needed.
std::map<std::string, std::string> hlsl_dxil_mapping;
// Read the binary data for DXIL libraries.
for (std::shared_ptr<RgDxrDxilLibrary> dxil_lib : state_desc.input_files)
{
assert(dxil_lib != nullptr);
if (dxil_lib != nullptr)
{
std::string dxil_file_to_read;
if (dxil_lib->input_type == DxrSourceType::kBinary)
{
dxil_file_to_read = dxil_lib->full_path;
}
else
{
// Read the HLSL mapping file if we haven't done it already.
if (hlsl_dxil_mapping.empty())
{
ReadHlslMappingFile(config.dxr_hlsl_mapping, hlsl_dxil_mapping);
}
// Retrieve the DXIL binary which corresponds to the current HLSL file.
dxil_file_to_read = hlsl_dxil_mapping[dxil_lib->full_path];
}
// Read the binary DXIL file.
bool is_file_read = RgDx12Utils::ReadBinaryFile(dxil_file_to_read, dxil_lib->binary_data);
assert(is_file_read);
if (!is_file_read)
{
should_abort = true;
std::stringstream msg;
msg << kStrErrorDxilFileReadFailed << dxil_lib->full_path;
error_msg = msg.str();
}
}
}
if (!should_abort)
{
// Assume pipeline mode by default, unless user specified shader mode explicitly.
D3D12_STATE_OBJECT_TYPE stateObjectType = D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE;
std::string modeLower = RgDx12Utils::ToLower(config.dxr_mode);
if (modeLower.compare("shader") == 0)
{
stateObjectType = D3D12_STATE_OBJECT_TYPE_COLLECTION;
}
// Create the State Object descriptor, based upon which the state object would be created.
CD3DX12_STATE_OBJECT_DESC dxr_state_desc(stateObjectType);
// Create the DXIL library subobjects.
for (std::shared_ptr<RgDxrDxilLibrary> dxil_lib : state_desc.input_files)
{
// Treat Binary and HLSL the same, since HLSL if applicable has already
// been converted to binary DXIL and read from disk.
if (dxil_lib->input_type == DxrSourceType::kBinary ||
(dxil_lib->input_type == DxrSourceType::kHlsl))
{
RgDx12Factory::CreateDxilLibrarySubobject(&dxr_state_desc, *dxil_lib, error_msg);
}
else
{
should_abort = true;
}
}
if (!should_abort)
{
// Create the hit groups and push a copy to our subobject container.
for (const RgDxrHitGroup& hitGroup : state_desc.hit_groups)
{
RgDx12Factory::CreateHitGroupSubobject(&dxr_state_desc, hitGroup);
}
// Create the shader config and push a copy to our subobject container.
for (const RgDxrShaderConfig& sc : state_desc.shader_config)
{
RgDx12Factory::CreateShaderConfigSubobject(&dxr_state_desc, sc.max_payload_size_in_bytes, sc.max_attribute_size_in_bytes);
}
// Local root signatures.
ID3D12RootSignature* local_root_signature = nullptr;
for (std::shared_ptr<RgDxrRootSignature> pLocalRs : state_desc.local_root_signature)
{
bool is_root_signature_created = CreateRootSignatureFromBinary(device_.Get(), pLocalRs->full_path, local_root_signature);
assert(is_root_signature_created);
assert(local_root_signature != nullptr);
if (!is_root_signature_created || local_root_signature == nullptr)
{
std::cout << kStrErrorLocalRootSignatureCreateFromFileFailure << pLocalRs->full_path << std::endl;
should_abort = true;
break;
}
RgDx12Factory::CreateLocalRootSignatureSubobject(&dxr_state_desc, local_root_signature, pLocalRs->exports);
}
if (!should_abort)
{
// Global root signatures.
ID3D12RootSignature* global_root_signature = nullptr;
for (std::shared_ptr<RgDxrRootSignature> pGlobalRs : state_desc.global_root_signature)
{
bool is_root_signature_created = CreateRootSignatureFromBinary(device_.Get(), pGlobalRs->full_path, global_root_signature);
assert(is_root_signature_created);
assert(global_root_signature != nullptr);
if (!is_root_signature_created || global_root_signature == nullptr)
{
std::cout << kStrErrorGlobalRootSignatureCreateFromFileFailure << pGlobalRs->full_path << std::endl;
should_abort = true;
break;
}
RgDx12Factory::CreateGlobalRootSignatureSubobject(&dxr_state_desc, global_root_signature);
}
if (!should_abort)
{
// Pipeline config.
RgDx12Factory::CreatePipelineConfigSubobject(&dxr_state_desc, state_desc.pipeline_config.max_trace_recursion_depth);
ComPtr<ID3D12StateObject> dxrStateObject;
#ifdef _DXRTEST
PrintStateObjectDesc(dxr_state_desc);
HRESULT rc = dxr_device_->CreateStateObject(dxr_state_desc, IID_PPV_ARGS(&dxrStateObject));
assert(SUCCEEDED(rc));
#endif // _DXRTEST
// Containers to track the output files that we created.
// Since the compiler may generate an arbitrary number of shaders with names that are
// not known to us in advance, we would have to communicate this list to the calling process.
// Track the results.
std::vector<RgDxrPipelineResults> results_pipeline_mode;
const wchar_t* kStrExportNameAll = L"all";
const char* kStrModeNameShader = "shader";
const char* kOutputFilenameSuffixUnified = "unified";
std::wstring dxr_export_wide = RgDx12Utils::strToWstr(config.dxrExport);
std::string export_lower = RgDx12Utils::ToLower(config.dxrExport);
std::wstring dxr_export_wide_lower = RgDx12Utils::strToWstr(config.dxrExport);
bool is_shader_mode = modeLower.compare(kStrModeNameShader) == 0;
if (is_shader_mode)
{
std::vector<std::shared_ptr<RgDx12ShaderResultsRayTracing>> rs;
std::vector<unsigned char> pipeline_binary;
bool is_unified_mode = true;
std::vector<std::string> indirect_shader_names;
// Compile and extract the results for a single shader.
std::shared_ptr<RgDx12ShaderResultsRayTracing> raytracing_shader_stats = std::make_shared<RgDx12ShaderResultsRayTracing>();
ret = backend_.CreateStateObjectShader(dxr_state_desc, dxr_export_wide, *raytracing_shader_stats, pipeline_binary, error_msg);
assert(ret);
if (ret)
{
rs.push_back(raytracing_shader_stats);
}
else
{
if (error_msg.empty())
{
std::cerr << kStrErrorDxrShaderModeCompilationFailed << std::endl;
}
}
if (ret)
{
RgDxrPipelineResults pipeline_results;
pipeline_results.isUnified = is_unified_mode;
// If we are in Pipeline (non All) mode, we would use the export name as the name of the pipeline.
pipeline_results.pipeline_name = "null";
uint32_t i = 0;
for (const auto& curr_results : rs)
{
// If we are in Unified mode, pipeline name is identical to export name (raygeneration shader name).
RgDxrShaderResults shader_results_tracking;
if (is_unified_mode || is_shader_mode)
{
shader_results_tracking.export_name = config.dxrExport;
}
else
{
assert(i < indirect_shader_names.size());
if (i < indirect_shader_names.size())
{
shader_results_tracking.export_name = indirect_shader_names[i];
}
}
assert(is_unified_mode || i < indirect_shader_names.size());
if (!config.dxr_isa_output.empty() && curr_results->disassembly != nullptr)
{
// Save output files and report to user: disassembly.
if (is_shader_mode || is_unified_mode)
{
std::cout << (!is_shader_mode ? kStrInfoExtractRayTracingDisassemblyPipelineByRaygen : kStrInfoExtractRayTracingDisassemblyShader)
<< config.dxrExport << "..." << std::endl;
}
else
{
std::cout << kStrInfoExtractRayTracingDisassemblyShader << "#" << (i + 1) << ": " << indirect_shader_names[i] << "..." << std::endl;
}
std::string output_filename_fixed = config.dxr_isa_output;
if (!is_shader_mode)
{
output_filename_fixed = GenerateSpecificFileName(output_filename_fixed, (is_unified_mode ? kOutputFilenameSuffixUnified : indirect_shader_names[i]));
}
bool is_disassembly_saved = RgDx12Utils::WriteTextFile(output_filename_fixed, curr_results->disassembly);
std::cout << (is_disassembly_saved ? kStrInfoExtractRayTracingDisassemblySuccess :
kStrErrorFailedToExtractRaytracingDisassembly) << std::endl;
assert(is_disassembly_saved);
ret = ret && is_disassembly_saved;
if (is_disassembly_saved)
{
shader_results_tracking.isa_disassembly = output_filename_fixed;
}
}
if (!config.dxr_statistics_output.empty())
{
// Save output files and report to user: statistics.
if (is_shader_mode)
{
std::cout << kStrInfoExtractRayTracingStatsShader << config.dxrExport << "..." << std::endl;
}
else
{
std::cout << kStrInfoExtractRayTracingStatsShader << "#" << (i + 1) << ": " <<
indirect_shader_names[i] << "..." << std::endl;
}
std::string output_filename_fixed = config.dxr_statistics_output;
if (!is_shader_mode)
{
output_filename_fixed = GenerateSpecificFileName(output_filename_fixed, (is_unified_mode ? kOutputFilenameSuffixUnified : indirect_shader_names[i]));
}
bool is_statistics_saved = SerializeDx12StatsRayTracing(*curr_results, output_filename_fixed);
std::cout << (is_statistics_saved ? kStrInfoExtractRayTracingStatisticsSuccess :
kStrErrorFailedToExtractRaytracingStatistics) << std::endl;
assert(is_statistics_saved);
ret = ret && is_statistics_saved;
if (is_statistics_saved)
{
shader_results_tracking.stats = output_filename_fixed;
}
}
// Track the current results.
pipeline_results.results.push_back(shader_results_tracking);
// Increment the index for the current result.
++i;
}
// Pipeline binaries extraction is not supported in shader mode.
if (!is_shader_mode && is_unified_mode && !config.dxr_binary_output.empty())
{
// Save output files and report to user: binaries.
std::cout << kStrInfoExtractRayTracingPipelineBinaryByRaygen << config.dxrExport << "..." << std::endl;
std::string output_filename_fixed = config.dxr_binary_output;
output_filename_fixed = GenerateSpecificFileName(output_filename_fixed, (is_unified_mode ? kOutputFilenameSuffixUnified : ""));
bool is_binary_saved = RgDx12Utils::WriteBinaryFile(output_filename_fixed, pipeline_binary);
std::cout << (is_binary_saved ? kStrInfoExtractRayTracingBinarySuccess :
kStrErrorFailedToExtractRaytracingBinary) << std::endl;
assert(is_binary_saved);
ret = ret && is_binary_saved;
if (is_binary_saved)
{
pipeline_results.pipeline_binary = output_filename_fixed;
}
}
// Track the pipeline results.
results_pipeline_mode.push_back(pipeline_results);
}
}
else
{
// Pipeline mode: compile and extract the results for all generated pipelines.
// Per-pipeline results.
std::vector<std::shared_ptr<std::vector<std::shared_ptr<RgDx12ShaderResultsRayTracing>>>> rs;
// Per-pipeline binary.
std::vector<std::shared_ptr<std::vector<unsigned char>>> pipeline_binaries;
// Per-pipeline flag that specifies whether the pipeline was compiled in Unified mode.
std::vector<bool> is_unified;
// Container for the raygeneration shader name for each generated pipeline.
std::vector<std::shared_ptr<std::vector<std::string>>> raygeneration_shader_names;
// Compile.
ret = backend_.CreateStateObject(dxr_state_desc, rs, pipeline_binaries,
is_unified, raygeneration_shader_names, error_msg);
assert(ret);
assert(!rs.empty());
if (ret && !rs.empty())
{
// Notify the user about the number of pipelines that were generated.
std::cout << kStrInfoDxrPipelineCompilationGenerated1 << rs.size() <<
(rs.size() == 1 ? kStrInfoDxrPipelineCompilationGeneratedSinglePipeline2 :
kStrInfoDxrPipelineCompilationGeneratedMultiplePipelines2) << std::endl;
// For each pipeline, let's extract the results.
for (uint32_t pipeline_index = 0; pipeline_index < rs.size(); pipeline_index++)
{
// Running number to identify the current pipeline in Indirect mode.
const std::string pipeline_index_display_name = std::to_string(pipeline_index + 1);
// The shader names for the current pipeline. In case we are in Unified mode, there will
// be only a single shader name (the raygeneration shader).
std::shared_ptr<std::vector<std::string>> pipeline_shader_names = raygeneration_shader_names[pipeline_index];
const auto& curr_raygeneration_shader_names = *pipeline_shader_names;
// The raygeneration shader name for this pipeline (essentially, the pipeline identifier).
// We already have in hand the vector that holds the raygeneration shader name for the current pipeline
// so we will take the first (and only) element.
const char* curr_raygeneration_shader_name = curr_raygeneration_shader_names[0].data();
// The results for the current pipeline.
const auto& curr_results = rs[pipeline_index];
// Report the type of compilation (Unified/Indirect) to the user for the current pipeline.
std::cout << kStrInfoDxrPipelineTypeReport1 << (pipeline_index + 1);
if (is_unified[pipeline_index])
{
std::cout << kStrInfoDxrPipelineTypeReport2 <<
curr_raygeneration_shader_name;
}
std::cout << ": " << std::endl;
if (is_unified[pipeline_index])
{
// Unified mode - expect a single shader in output.
assert(curr_results->size() == 1);
std::cout << kStrInfoDxrPipelineCompiledUnified << std::endl;
}
else
{
// Indirect mode - expect N shaders in output.
assert(curr_results->size() >= 1);
std::cout << kStrInfoDxrPipelineCompiledIndirect1 << curr_results->size() <<
kStrInfoDxrPipelineCompiledIndirect2 << std::endl;
}
// Output metadata.
RgDxrPipelineResults curr_pipeline_results_metadata;
if (is_unified[pipeline_index])
{
// Since this pipeline was compiled in Unified mode, shader name is pipeline name.
curr_pipeline_results_metadata.pipeline_name = curr_raygeneration_shader_name;
curr_pipeline_results_metadata.isUnified = true;
}
else
{
// In Indirect mode we don't have the name of the raygeneration shader, just an index.
curr_pipeline_results_metadata.pipeline_name = pipeline_index_display_name;
curr_pipeline_results_metadata.isUnified = false;
}
// Go through pipeline's shaders.
for (uint32_t shader_index = 0; shader_index < rs[pipeline_index]->size(); shader_index++)
{
// Metadata to track the output files for this shader.
RgDxrShaderResults curr_shader_results_metadata;
// Track the export name.
if (is_unified[pipeline_index])
{
// In unified mode, this is the raygeneration shader name.
curr_shader_results_metadata.export_name = curr_raygeneration_shader_name;
}
else
{
// In indirect mode, this is the name of the current shader.
assert(shader_index < curr_raygeneration_shader_names.size());
if (shader_index < curr_raygeneration_shader_names.size())
{
curr_shader_results_metadata.export_name = curr_raygeneration_shader_names[shader_index].data();
}
else
{
std::cout << kStrErrorDxrFailedToRetrievePipelineShaderName <<
(shader_index + 1) << "." << std::endl;
}
}
// Build a suffix for this shader's output files.
std::stringstream shader_output_file_suffix_stream;
if (is_unified[pipeline_index])
{
shader_output_file_suffix_stream << curr_shader_results_metadata.export_name.c_str() << "_";
shader_output_file_suffix_stream << kOutputFilenameSuffixUnified;
}
else
{
shader_output_file_suffix_stream << pipeline_index_display_name << "_" <<
curr_shader_results_metadata.export_name.c_str();
}
const std::string shader_output_file_suffix = shader_output_file_suffix_stream.str().c_str();
// ISA files.
if (!config.dxr_isa_output.empty())
{
// Generate an index-specific file name.
std::string isa_output_filename = GenerateSpecificFileName(config.dxr_isa_output, shader_output_file_suffix);
assert(!isa_output_filename.empty());
if (!isa_output_filename.empty())
{
// Save per-pipeline disassembly.
if (is_unified[pipeline_index])
{
std::cout << kStrInfoExtractRayTracingDisassemblyPipelineByRaygen << curr_shader_results_metadata.export_name;
}
else
{
std::cout << kStrInfoExtractRayTracingDisassemblyPipelineByIndex1 << pipeline_index_display_name <<
kStrInfoExtractRayTracingResultByIndex2 << curr_shader_results_metadata.export_name;
}
std::cout << "..." << std::endl;
bool is_disassembly_saved = RgDx12Utils::WriteTextFile(isa_output_filename, (*curr_results)[shader_index]->disassembly);
ret = ret && is_disassembly_saved;
assert(is_disassembly_saved);
if (is_disassembly_saved)
{
curr_shader_results_metadata.isa_disassembly = isa_output_filename;
std::cout << kStrInfoExtractRayTracingDisassemblySuccess << std::endl;
}
else
{
std::cerr << kStrErrorFailedToWriteOutputFile1 << "disassembly" <<
kStrErrorFailedToWriteOutputFile2 << isa_output_filename <<
kStrErrorFailedToWriteOutputFile3 << std::endl;
}
}
}
// Statistics files.
if (!config.dxr_statistics_output.empty())
{
// Generate an index-specific file name.
std::string stats_output_filename = GenerateSpecificFileName(config.dxr_statistics_output,
shader_output_file_suffix);
assert(!stats_output_filename.empty());
if (!stats_output_filename.empty())
{
// Save per-pipeline statistics.
if (is_unified[pipeline_index])
{
std::cout << kStrInfoExtractRayTracingResourceUsagePipelineByRaygen <<
curr_shader_results_metadata.export_name;
}
else
{
std::cout << kStrInfoExtractRayTracingResourceUsagePipelineByIndex1 << pipeline_index_display_name <<
kStrInfoExtractRayTracingResultByIndex2 << curr_shader_results_metadata.export_name;
}
std::cout << "..." << std::endl;
bool is_statistics_saved = SerializeDx12StatsRayTracing((*(*curr_results)[shader_index]), stats_output_filename);
assert(is_statistics_saved);
ret = ret && is_statistics_saved;
if (is_statistics_saved)
{
curr_shader_results_metadata.stats = stats_output_filename;
std::cout << kStrInfoExtractRayTracingStatisticsSuccess << std::endl;
}
else
{
std::cerr << kStrErrorFailedToWriteOutputFile1 << "statistics" <<
kStrErrorFailedToWriteOutputFile2 << stats_output_filename <<
kStrErrorFailedToWriteOutputFile3 << std::endl;
}
}
}
// Binary files: only if required by user and only once per pipeline.
if (!config.dxr_binary_output.empty() && (shader_index == 0))
{
assert(pipeline_index < pipeline_binaries.size());
if (pipeline_index < pipeline_binaries.size())
{
// Generate an index-specific file name.
std::string bin_output_filename = GenerateSpecificFileName(config.dxr_binary_output,
(is_unified[pipeline_index] ? curr_raygeneration_shader_name : pipeline_index_display_name));
assert(!bin_output_filename.empty());
if (!bin_output_filename.empty())
{
// Save per-pipeline binary.
if (is_unified[pipeline_index])
{
std::cout << kStrInfoExtractRayTracingPipelineBinaryByRaygen <<
curr_raygeneration_shader_name;
}
else
{
std::cout << kStrInfoExtractRayTracingPipelineBinaryByIndex1 << pipeline_index_display_name;
}
std::cout << "..." << std::endl;
bool is_binary_saved = RgDx12Utils::WriteBinaryFile(bin_output_filename, *pipeline_binaries[pipeline_index]);
ret = ret && is_binary_saved;
assert(is_binary_saved);
if (is_binary_saved)
{
curr_pipeline_results_metadata.pipeline_binary = bin_output_filename;
std::cout << kStrInfoExtractRayTracingBinarySuccess << std::endl;
}
else
{
std::cout << kStrErrorFailedToWriteOutputFile1 << "binary" <<
kStrErrorFailedToWriteOutputFile2 << bin_output_filename <<
kStrErrorFailedToWriteOutputFile3 << std::endl;
}
}
}
else
{
bool is_multi_pipeline = (rs.size() > 1);
if(!is_multi_pipeline)
{
// Pipeline generation is supported for a single pipeline.
std::cerr << kStrErrorNoPipelineBinaryGeneratedForIndex << pipeline_index_display_name << std::endl;
}
else
{
// Pipeline generation is currently not supported by the driver for multiple pipelines.
std::cerr << kStrWarningBinaryExtractionNotSupportedMultiplePipelines1 <<
pipeline_index_display_name << kStrWarningBinaryExtractionNotSupportedMultiplePipelines2 << std::endl;
}
}
}
// Track current shader's results in the pipeline output metadata container.
curr_pipeline_results_metadata.results.push_back(curr_shader_results_metadata);
}
// Track the current pipeline's results.
results_pipeline_mode.push_back(curr_pipeline_results_metadata);
}
}
}
// Output metadata file.
if (!config.output_metadata.empty())
{
// Write the output metadata file.
RgDxrOutputMetadata::WriteOutputMetadata(config.output_metadata, results_pipeline_mode, error_msg);
#ifdef _DXR_TEST
std::vector<RgDxrPipelineResults> test;
RgDxrOutputMetadata::ReadOutputMetadata(config.output_metadata, test, error_msg);
#endif
}
}
}
}
}
}
}
else
{
should_abort = true;
}
return ret;
}
bool rgDx12Frontend::CompileRayTracingShader(const RgDx12Config& config, std::string& error_msg) const
{
bool ret = false;
return ret;
}
#endif
} | 53.729557 | 202 | 0.498969 | [
"geometry",
"render",
"object",
"vector"
] |
f60196ab93fcb5c778a8c056e9da1b561a12ee55 | 461 | cpp | C++ | coursera/algorithms/week2/main.cpp | clpsz/algorithms | c537c65eea5176f64cb37af674c3f07bc7d47821 | [
"Apache-2.0"
] | 2 | 2019-08-14T09:32:07.000Z | 2019-12-22T10:54:35.000Z | coursera/algorithms/week2/main.cpp | clpsz/algorithms | c537c65eea5176f64cb37af674c3f07bc7d47821 | [
"Apache-2.0"
] | null | null | null | coursera/algorithms/week2/main.cpp | clpsz/algorithms | c537c65eea5176f64cb37af674c3f07bc7d47821 | [
"Apache-2.0"
] | null | null | null | #include "common.h"
#include "QuickSort.h"
#include <assert.h>
#include <stdio.h>
vector<int> datas;
void read_data()
{
int num;
while (cin >> num)
{
datas.push_back(num);
}
}
void print_data()
{
cout << "length: " << datas.size() << endl;
for (auto d : datas)
{
cout << d << endl;
}
}
int main()
{
Sort *s = new QuickSort();
LLONG res = s->sort();
s->show();
cout << res;
return 0;
}
| 12.131579 | 47 | 0.507592 | [
"vector"
] |
f60aca291f47a694af0eecfa76d8f2228cd49b86 | 2,047 | cpp | C++ | input-output_example_gen/bench/mvt.cpp | dongchen-coder/symRIByInputOuputExamples | e7434699f44ceb01f153ac8623b5bafac57f8abf | [
"MIT"
] | null | null | null | input-output_example_gen/bench/mvt.cpp | dongchen-coder/symRIByInputOuputExamples | e7434699f44ceb01f153ac8623b5bafac57f8abf | [
"MIT"
] | null | null | null | input-output_example_gen/bench/mvt.cpp | dongchen-coder/symRIByInputOuputExamples | e7434699f44ceb01f153ac8623b5bafac57f8abf | [
"MIT"
] | null | null | null | #include "./utility/rt.h"
int N;
#define A_OFFSET 0
#define X1_OFFSET N * N
#define X2_OFFSET N * N + N
#define Y1_OFFSET N * N + N + N
#define Y2_OFFSET N * N + N + N + N
void runMvt_trace( double* a, double* x1, double* x2, double* y1, double* y2)
{
int i, j;
vector<int> idx;
for (i=0; i< N; i++)
{
for (j=0; j < N; j++)
{
idx.clear(); idx.push_back(i); idx.push_back(j);
//x1[i] = x1[i] + a[i][j] * y1[j];
x1[i] = x1[i] + a[i * N + j] * y1[j];
rtTmpAccess(X1_OFFSET + i, 0, 0, idx);
rtTmpAccess(A_OFFSET + i * N + j, 1, 1, idx);
rtTmpAccess(Y1_OFFSET + j, 2, 2, idx);
rtTmpAccess(X1_OFFSET + i, 3, 0, idx);
}
}
for (i=0; i < N; i++)
{
for (j=0; j< N; j++)
{
idx.clear(); idx.push_back(i); idx.push_back(j);
//x2[i] = x2[i] + a[j][i] * y2[j];
x2[i] = x2[i] + a[j * N + i] * y2[j];
rtTmpAccess(X2_OFFSET + i, 4, 3, idx);
rtTmpAccess(A_OFFSET + j * N + i, 5, 1, idx);
rtTmpAccess(Y2_OFFSET + j, 6, 4, idx);
rtTmpAccess(X2_OFFSET + i, 7, 3, idx);
}
}
return;
}
int main(int argc, char const *argv[])
{
if (argc != 2) {
cout << "This benchmark needs 1 loop bounds" << endl;
return 0;
}
for (int i = 1; i < argc; i++) {
if (!isdigit(argv[i][0])) {
cout << "arguments must be integer" << endl;
return 0;
}
}
N = stoi(argv[1]);
double* a = (double*)malloc( (N*N) * sizeof(double));
double* y1 = (double*)malloc( N * sizeof(double));
double* x1 = (double*)malloc( N * sizeof(double));
double* y2 = (double*)malloc( N * sizeof(double));
double* x2 = (double*)malloc( N * sizeof(double));
for (int i = 0; i < N; ++i)
{
y1[i] = i % 256;
y2[i] = i / 100;
}
for (int i = 0; i < N*N; ++i)
{
a[i] = i / 10;
}
runMvt_trace( a, x1, x2, y1, y2);
dumpRIHistogram();
return 0;
}
| 23 | 77 | 0.465071 | [
"vector"
] |
f60b09f2c9b2f0eeec9384f0dd17d28f7408ba2c | 5,109 | hpp | C++ | hpx/runtime/agas/stubs/symbol_namespace.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/runtime/agas/stubs/symbol_namespace.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/runtime/agas/stubs/symbol_namespace.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Bryce Adelstein-Lelbach
// Copyright (c) 2012-2013 Hartmut Kaiser
//
// 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)
////////////////////////////////////////////////////////////////////////////////
#if !defined(HPX_28443929_CB68_43ED_B134_F60602A344DD)
#define HPX_28443929_CB68_43ED_B134_F60602A344DD
#include <hpx/hpx_fwd.hpp>
#include <hpx/include/async.hpp>
#include <hpx/runtime/agas/server/symbol_namespace.hpp>
#include <hpx/util/jenkins_hash.hpp>
namespace hpx { namespace agas { namespace stubs
{
struct HPX_EXPORT symbol_namespace
{
typedef server::symbol_namespace server_type;
typedef server::symbol_namespace server_component_type;
typedef server_type::iterate_names_function_type
iterate_names_function_type;
///////////////////////////////////////////////////////////////////////////
template <typename Result>
static lcos::future<Result> service_async(
naming::id_type const& gid
, request const& req
, threads::thread_priority priority = threads::thread_priority_default
);
template <typename Result>
static lcos::future<Result> service_async(
std::string const& key
, request const& req
, threads::thread_priority priority = threads::thread_priority_default
)
{
return service_async<Result>(symbol_namespace_locality(key), req, priority);
}
/// Fire-and-forget semantics.
///
/// \note This is placed out of line to avoid including applier headers.
static void service_non_blocking(
naming::id_type const& gid
, request const& req
, threads::thread_priority priority = threads::thread_priority_default
);
static response service(
naming::id_type const& gid
, request const& req
, threads::thread_priority priority = threads::thread_priority_default
, error_code& ec = throws
)
{
return service_async<response>(gid, req, priority).get(ec);
}
static response service(
std::string const& key
, request const& req
, threads::thread_priority priority = threads::thread_priority_default
, error_code& ec = throws
)
{
return service_async<response>(key, req, priority).get(ec);
}
///////////////////////////////////////////////////////////////////////////
static lcos::future<std::vector<response> > bulk_service_async(
naming::id_type const& gid
, std::vector<request> const& reqs
, threads::thread_priority priority = threads::thread_priority_default
);
/// Fire-and-forget semantics.
///
/// \note This is placed out of line to avoid including applier headers.
static void bulk_service_non_blocking(
naming::id_type const& gid
, std::vector<request> const& reqs
, threads::thread_priority priority = threads::thread_priority_default
);
static std::vector<response> bulk_service(
naming::id_type const& gid
, std::vector<request> const& reqs
, threads::thread_priority priority = threads::thread_priority_default
, error_code& ec = throws
)
{
return bulk_service_async(gid, reqs, priority).get(ec);
}
static naming::gid_type get_service_instance(boost::uint32_t service_locality_id)
{
naming::gid_type service(HPX_AGAS_SYMBOL_NS_MSB, HPX_AGAS_SYMBOL_NS_LSB);
return naming::replace_locality_id(service, service_locality_id);
}
static naming::gid_type get_service_instance(naming::gid_type const& dest,
error_code& ec = throws)
{
boost::uint32_t service_locality_id = naming::get_locality_id_from_gid(dest);
if (service_locality_id == naming::invalid_locality_id)
{
HPX_THROWS_IF(ec, bad_parameter,
"symbol_namespace::get_service_instance",
boost::str(boost::format(
"can't retrieve a valid locality id from global address: "
) % dest));
return naming::gid_type();
}
return get_service_instance(service_locality_id);
}
static bool is_service_instance(naming::gid_type const& gid)
{
return gid.get_lsb() == HPX_AGAS_SYMBOL_NS_LSB &&
(gid.get_msb() & ~naming::gid_type::locality_id_mask) == HPX_AGAS_NS_MSB;
}
static naming::id_type symbol_namespace_locality(std::string const& key)
{
boost::uint32_t hash_value = 0;
if (key.size() < 2 || key[1] != '0' || key[0] != '/')
{
// keys starting with '/0' have to go to node 0
util::jenkins_hash hash;
hash_value = hash(key) % get_initial_num_localities();
}
return naming::id_type(get_service_instance(hash_value),
naming::id_type::unmanaged);
}
};
}}}
#endif // HPX_28443929_CB68_43ED_B134_F60602A344DD
| 34.755102 | 85 | 0.622431 | [
"vector"
] |
f60d388a69e05231ffd63f5f5148fb3816b291af | 18,953 | cpp | C++ | src/gfx/Shader/ShaderProgram.cpp | Robograde/Robograde | 2c9a7d0b8250ec240102d504127f5c54532cb2b0 | [
"Zlib"
] | 5 | 2015-10-11T10:22:39.000Z | 2019-07-24T10:09:13.000Z | src/gfx/Shader/ShaderProgram.cpp | Robograde/Robograde | 2c9a7d0b8250ec240102d504127f5c54532cb2b0 | [
"Zlib"
] | null | null | null | src/gfx/Shader/ShaderProgram.cpp | Robograde/Robograde | 2c9a7d0b8250ec240102d504127f5c54532cb2b0 | [
"Zlib"
] | null | null | null | /**************************************************
Zlib Copyright 2015 Henrik Johansson
***************************************************/
#include "ShaderProgram.h"
#include <utility/Logger.h>
gfx::ShaderProgram::ShaderProgram ( void )
{
m_LoadedShaders = false;
m_TextureCount = 0;
}
gfx::ShaderProgram::ShaderProgram ( rVector<Shader*> Shaders )
{
this->m_Shaders = Shaders;
Init ( m_Shaders,true );
}
gfx::ShaderProgram::~ShaderProgram ( void )
{
if ( m_LoadedShaders )
{
for ( rVector<Shader*>::iterator it = m_Shaders.begin(); it != m_Shaders.end(); ++it )
{
tDelete( *it );
}
m_Shaders.clear();
}
glDeleteProgram ( m_Handle );
}
bool gfx::ShaderProgram::Init ( rVector<Shader*> Shaders, bool print )
{
if ( m_Shaders.size() > 0 )
{
m_Shaders.clear();
}
//save shaders
for ( auto it : Shaders )
{
m_Shaders.push_back ( it );
}
m_Handle = glCreateProgram();
if ( m_Handle == 0 )
{
throw "Failed to create shader program";
return false;
}
//attach shaders to program
for ( int i = 0; i < static_cast<int> ( Shaders.size() ); i++ )
{
glAttachShader ( m_Handle,Shaders[i]->GetHandle() );
}
//link shaders
glLinkProgram ( m_Handle );
//error checking
GLint status;
glGetProgramiv ( m_Handle,GL_LINK_STATUS,&status );
if ( status == GL_FALSE )
{
char log[1024];
int len = 0;
Logger::Log( "Can't link shaders", "ShaderProgram", LogSeverity::ERROR_MSG );
glGetProgramInfoLog ( m_Handle, sizeof ( log ), &len, log );
Logger::Log( "Errorlog: " + rString( log ), "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
if ( print )
{
Logger::Log( "Linked Shaderprogram", "ShaderProgram", LogSeverity::DEBUG_MSG );
}
// Not using "return Validate();" because stuff might get added after
if ( !Validate() )
{
return false;
}
return true;
}
GLuint gfx::ShaderProgram::GetHandle()
{
return m_Handle;
}
void gfx::ShaderProgram::Apply()
{
// Lazy validation because of AMD driver behaviour.
if ( !m_Validated )
{
if ( !Validate() )
{
GLint status;
glGetProgramiv ( m_Handle, GL_VALIDATE_STATUS, &status );
if ( status == GL_FALSE )
{
char log[1024];
int len = 0;
glGetProgramInfoLog ( m_Handle, sizeof ( log ), &len, log );
if (len > 0)
{
Logger::Log("Validation of shader program: \"" + m_Filename + "\" failed: " + rString(log, len - 1), "ShaderProgram", LogSeverity::ERROR_MSG);
}
// TODO assert or fancy recovery when recompiling in run-time? assert for now.
assert ( false );
}
}
}
m_TextureCount = 0;
glUseProgram ( m_Handle );
}
bool gfx::ShaderProgram::Validate()
{
glValidateProgram ( m_Handle );
GLint status;
glGetProgramiv ( m_Handle, GL_VALIDATE_STATUS, &status );
m_Validated = ( status == GL_TRUE );
return m_Validated;
}
GLuint gfx::ShaderProgram::GetUniformLocationByName ( const rString& name )
{
return glGetUniformLocation ( m_Handle,name.c_str() );
}
//Create shaderprogram
bool gfx::ShaderProgram::LoadCompleteShaderProgramFromFile ( const rString& filename, bool print )
{
//this function is used to load a set of shaders from a single file
//seperate each shader with a #new_shader ******* and a #end_shader
//where **** can be a vertex, geometry, control, evaluation or fragment
//extra code can be loaded into the current shader by the #include filename macro
m_Filename = rString ( filename.c_str() );
m_LoadedShaders = true;
ifstream fin;
fin.open ( filename.c_str() );
if ( !fin.is_open() )
{
if ( print )
{
Logger::Log( "Could not open file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
return false;
}
rString line;
size_t found;
while ( !fin.eof() )
{
getline ( fin, line );
if ( (found = line.find( "#new_shader" )) != rString::npos )
{
if ( (found = line.find( "vertex" )) != rString::npos )
{
CreateShader ( &fin, GL_VERTEX_SHADER, filename,print );
}
if ( (found = line.find( "geometry" )) != rString::npos )
{
CreateShader ( &fin, GL_GEOMETRY_SHADER, filename, print );
}
if ( (found = line.find( "control" )) != rString::npos )
{
CreateShader ( &fin, GL_TESS_CONTROL_SHADER, filename, print );
}
if ( (found = line.find( "evaluation" )) != rString::npos )
{
CreateShader ( &fin, GL_TESS_EVALUATION_SHADER, filename, print );
}
if ( (found = line.find( "fragment" )) != rString::npos )
{
CreateShader ( &fin, GL_FRAGMENT_SHADER, filename, print );
}
if ( (found = line.find( "compute" )) != rString::npos )
{
CreateShader ( &fin, GL_COMPUTE_SHADER, filename, print );
}
}
}
m_Handle = glCreateProgram();
if ( m_Handle == 0 )
{
if ( print )
{
Logger::Log( "Could not create shader program", "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
return false;
}
//attach shaders to program
for ( int i = 0; i < static_cast<int> ( m_Shaders.size() ); i++ )
{
glAttachShader ( m_Handle, m_Shaders[i]->GetHandle() );
}
//link shaders
glLinkProgram ( m_Handle );
//error checking
GLint status;
glGetProgramiv ( m_Handle, GL_LINK_STATUS, &status );
if ( status == GL_FALSE )
{
char log[1024];
int len = 0;
Logger::Log( "Could not link shaders to program", "ShaderProgram", LogSeverity::ERROR_MSG );
glGetProgramInfoLog ( m_Handle, sizeof ( log ), &len, log );
Logger::Log( "Error log: " + rString( log ), "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
if ( print )
{
Logger::Log( "Linked Shaders to program", "ShaderProgram", LogSeverity::DEBUG_MSG );
}
Validate();
return true;
}
// Create shaderprogram with a define container
bool gfx::ShaderProgram::LoadCompleteShaderProgramFromFile ( const rString& filename, bool print, ShaderDefineContainer& container )
{
//this function is used to load a set of shaders from a single file
//seperate each shader with a #new_shader ******* and a #end_shader
//where **** can be a vertex, geometry, control, evaluation or fragment
//extra code can be loaded into the current shader by the #include filename macro
m_Filename = rString ( filename.c_str() );
m_LoadedShaders = true;
m_Defines = container;
ifstream fin;
fin.open ( filename.c_str() );
if ( !fin.is_open() )
{
if ( print )
{
Logger::Log( "Could not open file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
return false;
}
rString line;
size_t found;
while ( !fin.eof() )
{
getline ( fin, line );
if ( (found = line.find( "#new_shader" )) != rString::npos )
{
if ( (found = line.find( "vertex" )) != rString::npos )
{
CreateShader ( &fin, GL_VERTEX_SHADER, filename,print,container );
}
if ( (found = line.find( "geometry" )) != rString::npos )
{
CreateShader ( &fin, GL_GEOMETRY_SHADER, filename, print,container );
}
if ( (found = line.find( "control" )) != rString::npos )
{
CreateShader ( &fin, GL_TESS_CONTROL_SHADER, filename, print,container );
}
if ( (found = line.find( "evaluation" )) != rString::npos )
{
CreateShader ( &fin, GL_TESS_EVALUATION_SHADER, filename, print,container );
}
if ( (found = line.find( "fragment" )) != rString::npos )
{
CreateShader ( &fin, GL_FRAGMENT_SHADER, filename, print,container );
}
if ( (found = line.find( "compute" )) != rString::npos )
{
CreateShader ( &fin, GL_COMPUTE_SHADER, filename, print,container );
}
}
}
m_Handle = glCreateProgram();
if ( m_Handle == 0 )
{
if ( print )
{
Logger::Log( "Could not create shader program", "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
return false;
}
//attach shaders to program
for ( int i = 0; i < static_cast<int> ( m_Shaders.size() ); i++ )
{
glAttachShader ( m_Handle, m_Shaders[i]->GetHandle() );
}
//link shaders
glLinkProgram ( m_Handle );
//error checking
GLint status;
glGetProgramiv ( m_Handle, GL_LINK_STATUS, &status );
if ( status == GL_FALSE )
{
char log[1024];
int len = 0;
Logger::Log( "Could not link shaders to program", "ShaderProgram", LogSeverity::ERROR_MSG );
glGetProgramInfoLog ( m_Handle, sizeof ( log ), &len, log );
Logger::Log( "Error log: " + rString( log ), "ShaderProgram", LogSeverity::ERROR_MSG );
return false;
}
if ( print )
{
Logger::Log( "Linked Shaders to program", "ShaderProgram", LogSeverity::DEBUG_MSG );
}
Validate();
return true;
}
//Creates a shader
void gfx::ShaderProgram::CreateShader ( ifstream* FileStream, GLenum shaderType, const rString& filename,bool print )
{
rString line;
size_t found;
rString shaderText;
bool end = false;
while ( !end )
{
getline ( *FileStream, line );
//search for the end of the shader
found = line.find ( "#include " );
if ( found != rString::npos )
{
int i = static_cast<int> ( found ) + 9; //found + "#include "
rString s;
while ( i < static_cast<int> ( line.length() ) )
{
s += line[i];
i++;
}
rString str = GetDir ( rString ( filename ) ) + s;
shaderText += LoadText ( str.c_str() );
shaderText += "\n";
}
else
{
found = line.find ( "#end_shader" );
if ( found != rString::npos )
{
//break loop
end = true;
break;
}
else if ( FileStream->eof() )
{
Logger::Log( "Could not find end of file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG );
return;
}
else
{
shaderText += line;
shaderText += '\n';
}
}
}
if ( shaderText.length() > 0 )
{
Shader* shader = tNew( Shader );
shader->CreateFromString ( shaderText, shaderType, filename,print );
m_Shaders.push_back ( shader );
shaderText.clear();
}
}
//Creates a shader with defines
void gfx::ShaderProgram::CreateShader ( ifstream* FileStream, GLenum shaderType, const rString& filename,bool print, ShaderDefineContainer& container )
{
rString line;
size_t found;
rString shaderText;
getline(*FileStream, line);
shaderText += line;
shaderText += "\n";
shaderText += container.GetAllDefineLines();
shaderText += container.GetDefinesShaderStage ( shaderType );
bool end = false;
while ( !end )
{
getline ( *FileStream, line );
//search for the end of the shader
found = line.find ( "#include " );
if ( found != rString::npos )
{
int i = static_cast<int> ( found ) + 9; //found + "#include "
rString s;
while ( i < static_cast<int> ( line.length() ) )
{
s += line[i];
i++;
}
rString str = GetDir ( rString ( filename.c_str() ) ) + s;
shaderText += LoadText ( str.c_str() );
shaderText += "\n";
}
else
{
found = line.find ( "#end_shader" );
if ( found != rString::npos )
{
//break loop
end = true;
break;
}
else if ( FileStream->eof() )
{
Logger::Log( "Could not find end of file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG );
return;
}
else
{
shaderText += line;
shaderText += '\n';
}
}
}
if ( shaderText.length() > 0 )
{
Shader* shader = tNew( Shader );
shader->CreateFromString ( shaderText, shaderType, filename,print );
m_Shaders.push_back ( shader );
shaderText.clear();
}
}
rString gfx::ShaderProgram::GetDir ( rString filename )
{
bool found = false;
for ( int i = static_cast<int> ( filename.size() ); i > 0; i-- )
{
if ( filename.c_str() [i] == '/' )
{
found = true;
}
if ( !found )
{
filename.erase ( i );
}
}
return filename;
}
rString gfx::ShaderProgram::LoadText ( const char* filename )
{
ifstream fin;
fin.open ( filename );
if ( !fin.is_open() )
{
return "";
}
rString text;
rString line;
while ( !fin.eof() )
{
getline ( fin, line );
text += line;
text += "\n";
}
return text;
}
void gfx::ShaderProgram::SetUniformFloat ( const rString& name, const float value )
{
glUniform1f ( FetchUniform ( name ), value );
}
void gfx::ShaderProgram::SetUniformInt( const rString& name, const int value )
{
glUniform1i ( FetchUniform ( name ), value );
}
void gfx::ShaderProgram::SetUniformUInt ( const rString& name, const unsigned int value )
{
glUniform1ui ( FetchUniform ( name ), value );
}
void gfx::ShaderProgram::SetUniformBool ( const rString& name, const bool value )
{
glUniform1i ( FetchUniform ( name ), value );
}
void gfx::ShaderProgram::SetUniformVec3 ( const rString& name, const glm::vec3& value )
{
glUniform3f ( FetchUniform ( name ), value.x,value.y,value.z );
}
void gfx::ShaderProgram::SetUniformVec2 ( const rString& name, const glm::vec2& value )
{
glUniform2f ( FetchUniform ( name ), value.x, value.y );
}
void gfx::ShaderProgram::SetUniformVec4 ( const rString& name, const glm::vec4& value )
{
glUniform4f ( FetchUniform ( name ), value.x, value.y, value.z,value.w );
}
void gfx::ShaderProgram::SetUniformMat4 ( const rString& name, const glm::mat4x4& value )
{
glUniformMatrix4fv ( FetchUniform ( name ), 1, GL_FALSE, &value[0][0] );
}
void gfx::ShaderProgram::SetUniformTexture(const rString& name, Texture& tex){
tex.Apply(FetchUniform(name), m_TextureCount++);
}
void gfx::ShaderProgram::SetUniformTextureHandle(const rString& name, GLuint tex, int index){
glUniform1i(FetchUniform(name), index);
glActiveTexture(GL_TEXTURE0 + index);
glBindTexture(GL_TEXTURE_2D, tex);
}
GLint gfx::ShaderProgram::FetchUniform ( const rString& name )
{
rMap<rString, GLint>::const_iterator it = m_UniformMap.find ( name );
// Uniform wasn't found in cache
if ( it == m_UniformMap.end() )
{
GLint loc = GetUniformLocationByName ( name );
// Don't emplace in cache if uniform was invalid
if ( loc != -1 )
{
m_UniformMap.emplace ( name, loc );
}
else
{
//printf("Failed to fetch unifrom : %s\n",name.c_str());
//assert(false); //makes it annoying to debug shaders
}
return loc;// Uniform was found in cache
}
else
{
return it->second;
}
}
bool gfx::ShaderProgram::Recompile()
{
if ( !m_LoadedShaders )
{
for ( auto it : m_Shaders )
{
it->Recompile();
}
glDeleteProgram ( m_Handle );
m_Validated = false;
return Init ( m_Shaders, false );;
}
else
{
//clear up old shader
for ( rVector<Shader*>::iterator i = m_Shaders.begin(); i != m_Shaders.end(); i++ )
{
tDelete( *i );
}
m_Shaders.clear();
glDeleteProgram ( m_Handle );
//reinit the program
if(m_Defines.IsEmpty())
{
LoadCompleteShaderProgramFromFile ( m_Filename, false );
}
else
{
LoadCompleteShaderProgramFromFile ( m_Filename, false, m_Defines );
}
m_Validated = false;
return true;
}
}
rString& gfx::ShaderProgram::GetFilename()
{
return m_Filename;
}
void gfx::ShaderProgram::SaveProgramBinary(){
if(m_Handle <= 0){
return;
}
GLint formatCount;
glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS,&formatCount);
GLint* formats = new GLint[formatCount];
glGetIntegerv(GL_PROGRAM_BINARY_FORMATS, formats);
GLint length;
glGetProgramiv(m_Handle,GL_PROGRAM_BINARY_LENGTH, &length);
GLenum* binaryFormats = new GLenum();
GLbyte* programBinary = new GLbyte[length];
glGetProgramBinary(m_Handle,length,nullptr, binaryFormats,programBinary);
ShaderProgramBinary header;
header.Size = length;
strcpy(header.Version,(char*)glGetString(GL_VERSION));
std::stringstream ss;
ss << m_Filename;
ss << ".bin";
FILE* file = fopen(ss.str().c_str(),"wb");
fwrite(&header,sizeof(ShaderProgramBinary),1,file);
fwrite(programBinary,length,1,file);
fclose(file);
Logger::Log("Saved program binary", "ShaderProgram", LogSeverity::INFO_MSG);
delete [] programBinary;
delete binaryFormats;
delete formats;
}
void gfx::ShaderProgram::LoadProgramBinary(const rString& filename)
{
std::stringstream ss;
ss << filename;
ss << ".bin";
FILE* fp = fopen(ss.str().c_str(), "rb");
//header
ShaderProgramBinary header;
fseek(fp, 0, SEEK_SET);
fread(&header, sizeof(ShaderProgramBinary),1,fp);
//shader prog
GLbyte* binary = new GLbyte[header.Size];
fseek(fp, sizeof(ShaderProgramBinary), SEEK_SET);
fread(binary, header.Size, 1, fp);
fclose(fp);
GLint formats = 0;
glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats);
GLint *binaryFormats = new GLint[formats];
glGetIntegerv(GL_PROGRAM_BINARY_FORMATS, binaryFormats);
m_Handle = glCreateProgram();
glProgramBinary(m_Handle,(GLenum)(*binaryFormats),binary,header.Size);
GLint succes;
glGetProgramiv(m_Handle, GL_LINK_STATUS, &succes);
if(!succes)
{
Logger::Log("Failed to load shader program binary", "ShaderProgram", LogSeverity::ERROR_MSG);
}
delete [] binary;
delete [] binaryFormats;
}
bool gfx::ShaderProgram::LoadProgramBinaryHeader(const rString& filename, ShaderProgramBinary& outHeader)
{
std::stringstream ss;
ss << filename;
ss << ".bin";
FILE* fp = fopen(ss.str().c_str(), "rb");
if(fp == nullptr)
return false;
//header
fseek(fp, 0, SEEK_SET);
fread(&outHeader, sizeof(ShaderProgramBinary),1,fp);
fclose(fp);
return true;
}
| 28.457958 | 151 | 0.580858 | [
"geometry"
] |
f6187204b12bf63ece9b847b00ab12cf68ad51e4 | 7,874 | cpp | C++ | Proj/XCOM Ai Behaviours Unknown/AI/Actions/MoveAction.cpp | PLockhart/XCOM-AI--Behaviours-Unknown | 73e82ae75ef09ba9463799f09ff999371927ef1e | [
"MIT"
] | null | null | null | Proj/XCOM Ai Behaviours Unknown/AI/Actions/MoveAction.cpp | PLockhart/XCOM-AI--Behaviours-Unknown | 73e82ae75ef09ba9463799f09ff999371927ef1e | [
"MIT"
] | null | null | null | Proj/XCOM Ai Behaviours Unknown/AI/Actions/MoveAction.cpp | PLockhart/XCOM-AI--Behaviours-Unknown | 73e82ae75ef09ba9463799f09ff999371927ef1e | [
"MIT"
] | null | null | null | #include "MoveAction.h"
#include "../AICharacter.h"
#include "../PathFinding.h"
MoveAction::MoveAction(int priority)
:Action(priority) {}
//Creates a new movement action with;
//the character that will be performing the action,
//the tile that the character must move to
MoveAction::MoveAction(AICharacter * character, Tile * destination, int priority)
: Action(priority) {
ActingCharacter = character;
_originalDestination = destination;
}
void MoveAction::setup() {
_isSetupFin = true;
//the character is moving from their current tile, so don't mark it as occupied
ActingCharacter->CurrentTile->IsOccupied = false;
//try and work out a path to the destination
bool _pathCalculated;
_pathCalculated = getPathwayData(_moveTiles, ActingCharacter->CurrentTile, _originalDestination);
//if we coulld plot a path, set the characters destination to the first index
if (_pathCalculated == true) {
Destination = _originalDestination->Position;
ActingCharacter->DestinationTile = _moveTiles[0];
}
//otherwise cancel the movement
else {
cancel();
}
}
//Gets the pathway data from a start to a finish point.
//Returns the outcome of the procedure, true if a path was found
bool MoveAction::getPathwayData(vector<Tile*> &pathway, Tile * start, Tile * destination) {
//normal movement, so nothing special
return PathFinding::getPathway(pathway, start, destination);
}
//Moves the player's vector along the move positions
void MoveAction::act(float dt, AICharacter * sender) {
Action::act(dt, sender);
//validation check
if (abs(ActingCharacter->DestinationTile->X - ActingCharacter->CurrentTile->X) > 1 ||
abs(ActingCharacter->DestinationTile->Y - ActingCharacter->CurrentTile->Y) > 1) {
cancel();
return;
}
//if we have tiles to move to keep cycling through them moving to each one in turn
if (_moveTiles.size() != 0) {
//if the overall destination is occupied by another character then cancel the action
if (_moveTiles.back()->IsOccupied == true) {
cancel();
return;
}
//work out the move vector to the next point
Vector3 nextPoint = (_moveTiles.front())->Position;
//work out the direction we have to face
Vector3 moveVector = nextPoint - ActingCharacter->Position;
//resolve vector into an angle, where 0 is facing up n degrees
float targetRot = ((atan2(moveVector.y, moveVector.x) * 180) / 3.1415926) + 90;
Rotations::clampDegreeRotation(targetRot);
//Only allow the movement along the direction vector if they are facing the general direction
if (Rotations::rotationsSimilair(ActingCharacter->Rotation, targetRot, ActingCharacter->RotSpeed) == false) {
ActingCharacter->rotateBy(Rotations::RotDir(ActingCharacter->Rotation, targetRot) * ActingCharacter->RotSpeed);
}
//else the player is facing in the right direction and ready to move
else {
moveVector.normalise();
//move the player along its move vector
ActingCharacter->moveBy((moveVector * ActingCharacter->Speed * ActingCharacter->MoveModifier));
//check to see if the character has moved on to the destination tile
if (ActingCharacter->CurrentTile == _moveTiles.front()) {
//remove that point from the movePositions list
_moveTiles.erase(_moveTiles.begin());
//move on to the next tile in the list while we stil have a series of tiles to move through
if (_moveTiles.size() != 0)
ActingCharacter->DestinationTile = _moveTiles[0];
}
}
}
//if the character has no destination other than the tile they are on, then move them to the center of that tile
else if (ActingCharacter->CurrentTile == ActingCharacter->DestinationTile) {
//if the destination has been taken then cancel the move
if (ActingCharacter->DestinationTile->IsOccupied == true) {
cancel();
return;
}
//work out the move vector to the next point
Vector3 nextPoint = ActingCharacter->CurrentTile->Position;
Vector3 moveVector = nextPoint - ActingCharacter->Position;
moveVector.normalise();
//if the character is basically on top of the tile's center position, make it so
if (ActingCharacter->Position.distance(nextPoint) < ActingCharacter->Speed * ActingCharacter->MoveModifier)
ActingCharacter->moveBy(ActingCharacter->CurrentTile->Position - ActingCharacter->Position);
//move the character along its move vector
else
ActingCharacter->moveBy(moveVector * ActingCharacter->Speed * ActingCharacter->MoveModifier);
}
//if the cahracter has no more tiles ot move though and they are in the center of their current tile, then finish the action
if (ActingCharacter->Position == ActingCharacter->CurrentTile->Position &&
_moveTiles.size() == 0)
finished();
}
//Cancels the movement and moves the character to the nearest valid tile
void MoveAction::cancel() {
//don't bother redoing the cancel if we are already cancelled or have already finished
if (State == kCancelling || Action::isActionComplete() == true)
return;
State = kCancelling;
_moveTiles.clear();
//with this uncommented, the charcter must always move to the center position before the action can finish
//just move the character to the centre of the tile they were on, if not occupied
//if (ActingCharacter->CurrentTile->IsOccupied == false)
// ActingCharacter->DestinationTile = ActingCharacter->CurrentTile;
//with this uncommented, the character can end in an odd position in the tile
if (ActingCharacter->CurrentTile->IsOccupied == false) {
ActingCharacter->DestinationTile = ActingCharacter->CurrentTile;
finished();
}
//if we can't immediately find a fallback, search out to the neighbouring tiles
else {
Tile *closest = getIdealFallback();
//path find to the worked out nearest tile
getPathwayData(_moveTiles, ActingCharacter->CurrentTile, closest);
ActingCharacter->DestinationTile = _moveTiles[0];
}
}
//Gets the closest valid tile we can move to, to stop moving
Tile* MoveAction::getIdealFallback() {
bool foundDestination = false;
int depth = 1;
Tile *closest;
while (foundDestination == false) {
//flood map and find a random neighbour to go to
vector<Tile*> neighbours;
PathFinding::floodMap(neighbours, ActingCharacter->CurrentTile, depth);
for (int i = 0; i < (int)neighbours.size(); i++) {
//remove any neighbours that are occupied
if (neighbours[i]->IsOccupied == true) {
neighbours.erase(neighbours.begin() + i);
i--;
}
}
//if there are possible tiles to move to, work out the nearest
if ((int)neighbours.size() > 1) {
//pick the closest valid neighbour
closest = neighbours[0];
for (int i = 0; i < (int)neighbours.size(); i++) {
//if we found a closer tile set it as the next closest
if (ActingCharacter->Position.distance(closest->Position) > ActingCharacter->Position.distance(neighbours[i]->Position))
closest = neighbours[i];
}
foundDestination = true;
break;
}
//increase the depth in case we couldn't find neighbours at the current depth
depth++;
}
return closest;
}
//cancels moving to the target
bool MoveAction::canInterrupt() {
return true;
}
//Cant do anything while moving
bool MoveAction::canDoBoth(Action * other) {
return false;
}
//Set the tile to be occupied then call the super finished method
void MoveAction::finished() {
ActingCharacter->CurrentTile->IsOccupied = true;
Action::finished();
}
bool MoveAction::isSameKind(Action * other) {
if (MoveAction * derived = dynamic_cast<MoveAction*>(other))
return true;
return false;
}
bool MoveAction::shouldGiveWayTo(Action * other) {
//if they are of the same type..
if (isSameKind(other) == true) {
if (other->Priority >= Priority)
return true;
return false;
}
//if not the same type, prioritise the action with the bigger priority
else if (other->Priority >= Priority)
return true;
return false;
}
std::string MoveAction::toString() {
return "Moving";
} | 29.601504 | 125 | 0.729997 | [
"vector"
] |
f61f27d5bcbb7c34e3a07c47c849d167760528a1 | 5,425 | hpp | C++ | benchmarks/BenchmarkApp.hpp | irfanhamid/khyber | b6decef55ea199f884f2d77e049e979f1c7ba8bf | [
"Apache-2.0"
] | 1 | 2018-01-06T20:44:24.000Z | 2018-01-06T20:44:24.000Z | benchmarks/BenchmarkApp.hpp | irfanhamid/khyber | b6decef55ea199f884f2d77e049e979f1c7ba8bf | [
"Apache-2.0"
] | null | null | null | benchmarks/BenchmarkApp.hpp | irfanhamid/khyber | b6decef55ea199f884f2d77e049e979f1c7ba8bf | [
"Apache-2.0"
] | null | null | null | // Copyright 2014 Irfan Hamid
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <chrono>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
enum AccelerationType { Serial, AVX, AVX2, Optimum };
namespace po = boost::program_options;
class BenchmarkApp
{
public:
virtual bool InitApplication(int argc, char* argv[])
{
_name.assign(argv[0], strlen(argv[0]));
std::string acceleration;
po::options_description desc("Allowed options");
desc.add_options()
("length,l", po::value<size_t>(&_length)->default_value(512), "Length of vector")
("iterations,it", po::value<size_t>(&_iterations)->default_value(5000000), "Number of iterations")
("fma", po::value<bool>(&_useFma)->default_value(false), "Use the FMA instruction")
("acceleration,a", po::value<std::string>(&acceleration)->default_value("best"), "Acceleration type to use, AVX, AVX2, Serial etc.");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if ( !AccelerationFromString(acceleration, _acceleration) ) {
std::cout << "Invalid acceleration type" << std::endl;
return false;
}
return true;
}
virtual bool RunBenchmarks()
{
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point end;
start = std::chrono::high_resolution_clock::now();
for ( auto i = 0; i < _iterations; ++i ) {
RunSimd();
}
end = std::chrono::high_resolution_clock::now();
_simdDuration = (end - start);
start = std::chrono::high_resolution_clock::now();
for ( auto i = 0; i < _iterations; ++i ) {
RunSerial();
}
end = std::chrono::high_resolution_clock::now();
_serialDuration = (end - start);
return true;
}
virtual bool RunSimd()
{
return false;
}
virtual bool RunSerial()
{
return false;
}
///
/// \brief Produces a concise report of the execution of both benchmarks
/// \return std::string containing the report
///
std::string Report()
{
std::ostringstream reportStream;
reportStream << "Benchmarks report for " << _name << std::endl;
reportStream << "Vector size: " << _length << std::endl;
reportStream << "Iterations: " << _iterations << std::endl;
reportStream << "FMA: " << _useFma << std::endl;
reportStream << "Acceleration type: " << StringFromAcceleration(_acceleration) << std::endl;
reportStream << "Serial ticks: " << _serialDuration.count() << std::endl;
reportStream << "Simd ticks: " << _simdDuration.count() << std::endl;
// reportStream << "Speedup percentage: " << ((double)(_serialDuration - _simdDuration) * 100.0 / (double)_serialDuration) << std::endl;
return reportStream.str();
}
protected:
///
/// \brief Length of the arrays to run the benchmark on, modifiable by the -l cmdline param, defaults to 512
///
size_t _length;
///
/// \brief The number of iterations of the benchmark's basic operation to carry out, modifiable by the -it cmdline param, defaults to 5M
///
size_t _iterations;
///
/// \brief Which hardware level to use (serial, AVX, AVX2), modifiable by the -a cmdline param, defaults to the best available on the processor
///
enum AccelerationType _acceleration;
///
/// \brief Whether to use the FMA instruction, modifiable by the -fma cmdline param, defaults to false
///
bool _useFma;
std::chrono::high_resolution_clock::duration _serialDuration;
std::chrono::high_resolution_clock::duration _simdDuration;
std::string _name;
std::string StringFromAcceleration(AccelerationType acceleration)
{
switch (acceleration) {
case Serial: return "Serial";
case AVX: return "AVX";
case AVX2: return "AVX2";
case Optimum: return "Optimum";
}
}
bool AccelerationFromString(std::string& acceleration, AccelerationType& accelerationType)
{
if ( boost::iequals(acceleration, "best") || boost::iequals(acceleration, "optimum") ) {
_acceleration = Optimum;
} else if ( boost::iequals(acceleration, "avx2") ) {
_acceleration = AVX2;
} else if ( boost::iequals(acceleration, "avx") ) {
_acceleration = AVX;
} else if ( boost::iequals(acceleration, "serial") ) {
_acceleration = Serial;
} else {
return false;
}
return true;
}
};
extern BenchmarkApp* app;
int main(int argc, char* argv[])
{
if ( !app->InitApplication(argc, argv) ) {
return 1;
}
if ( !app->RunBenchmarks() ) {
return 1;
}
std::cout << std::endl << "--------------------------------------------------------------------------------" << std::endl;
std::cout << std::endl << app->Report();
std::cout << std::endl << "--------------------------------------------------------------------------------" << std::endl;
return 0;
}
| 31.178161 | 145 | 0.641659 | [
"vector"
] |
f62525c9df2211a450a0e9385417ec05c280e10f | 1,690 | cpp | C++ | Unidad-2/Aula13/integerlist.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | Unidad-2/Aula13/integerlist.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | Unidad-2/Aula13/integerlist.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> res;
int i;
void solve(string x, string v){
deque<int> temp;
vector<int> t;
int cont = 0;
for (i = 0; i < v.length(); ++i){
if(v[i] == '[' || v[i] == ']' || v[i] == ','){continue;}
else{temp.push_back((int)v[i]-'0');++cont;}
}
if(x.length() > cont){
//t.push_back(-9999);
res.push_back(t);
return;
}else{
bool flag = true;
for (i = 0; i < x.length(); ++i){
if(x[i] == 'R'){
if(flag == true){flag = false;}
else{flag = true;}
}
if(x[i] == 'D'){
if(flag == true){temp.pop_front();continue;}
if(flag == false) {temp.pop_back();}
}
}
if(flag == true){
while (!temp.empty()){
t.push_back(temp.front());
temp.pop_front();
}
res.push_back(t);
return;
}else if (flag == false){
while (!temp.empty()){
t.push_back(temp.back());
temp.pop_back();
}
res.push_back(t);
return;
}
}
}
int main(){
int n, t;
cin >> n;
string x, v;
while (n--){
cin >> x;
cin >> t;
cin >> v;
solve(x, v);
}
for (i = 0; i < res.size(); ++i){
if(res[i].empty() == true){cout << "error" << '\n'; continue;}
else{
cout << '[';
for (auto x : res[i]){cout << x << ',';}
cout << ']';
cout << '\n';
}
}
return EXIT_SUCCESS;
} | 22.236842 | 70 | 0.376923 | [
"vector"
] |
f626511b339af6b37373ad81f97337e8002e55d5 | 3,801 | hpp | C++ | include/touca/devkit/platform.hpp | cthulhu-irl/touca-cpp | 97392a1f84c7a92211ee86bcb527637a6c9a5cba | [
"Apache-2.0"
] | null | null | null | include/touca/devkit/platform.hpp | cthulhu-irl/touca-cpp | 97392a1f84c7a92211ee86bcb527637a6c9a5cba | [
"Apache-2.0"
] | null | null | null | include/touca/devkit/platform.hpp | cthulhu-irl/touca-cpp | 97392a1f84c7a92211ee86bcb527637a6c9a5cba | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "touca/lib_api.hpp"
namespace touca {
struct Response {
Response(const int status, const std::string& body)
: status(status), body(body) {}
const int status = -1;
const std::string body;
};
class TOUCA_CLIENT_API Transport {
public:
virtual void set_token(const std::string& token) = 0;
virtual Response get(const std::string& route) const = 0;
virtual Response patch(const std::string& route,
const std::string& body = "") const = 0;
virtual Response post(const std::string& route,
const std::string& body = "") const = 0;
virtual Response binary(const std::string& route,
const std::string& content) const = 0;
virtual ~Transport() = default;
};
class TOUCA_CLIENT_API ApiUrl {
public:
ApiUrl(const std::string& url);
bool confirm(const std::string& team, const std::string& suite,
const std::string& revision);
std::string root() const;
std::string route(const std::string& path) const;
std::string _team;
std::string _suite;
std::string _revision;
std::string _error;
private:
struct {
std::string scheme;
std::string host;
std::string port;
} _root;
std::string _prefix;
};
class TOUCA_CLIENT_API Platform {
public:
explicit Platform(const ApiUrl& api_url);
bool set_params(const std::string& team, const std::string& suite,
const std::string& revision);
/**
* Checks server status.
*
* @return true if server is ready to serve incoming requests.
*/
bool handshake() const;
/**
* Authenticates with the server using the provided API Key.
*
* @param api_key API Key to be used for authentication.
* Can be retrieved from server and is unique for
* each user account.
* @return true if authentication was successful.
*/
bool auth(const std::string& api_key);
/**
* Submits test results in binary format for one or multiple testcases
* to the server. Expects a valid API Token.
*
* @param content test results in binary format.
* @param max_retries maximum number of retries.
* @return a list of error messages useful for logging or printing
*/
std::vector<std::string> submit(const std::string& content,
const unsigned max_retries) const;
/**
* Informs the server that no more testcases will be submitted for
* the specified revision.
*
* @return true if we managed to seal the specified revision.
*/
bool seal() const;
/**
* Queries the server for the list of testcases that are submitted
* to the baseline version of this suite. Expects a valid API Token.
*
* @return list of test cases of the baseline version of this suite.
*/
std::vector<std::string> elements() const;
/**
* Checks if we are already authenticated with the server.
*
* @return true if object has a valid authentication token.
*/
inline bool has_token() const { return _is_auth; }
/**
* Provides a description of any error encountered during the
* execution of the most recently called member function.
* Intended to be used for logging purposes.
*
* @return any error encountered during the last function call.
*/
inline std::string get_error() const { return _error; }
bool cmp_submit(const std::string& url, const std::string& content) const;
bool cmp_jobs(std::string& content) const;
bool cmp_stats(const std::string& content) const;
private:
ApiUrl _api;
std::unique_ptr<Transport> _http;
bool _is_auth = false;
mutable std::string _error;
};
} // namespace touca
| 27.543478 | 76 | 0.661668 | [
"object",
"vector"
] |
f62a7c98528b03f941acf5279a7943ac1f9799af | 6,532 | hpp | C++ | source/framework/algorithm/include/lue/framework/algorithm/array_like.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/framework/algorithm/include/lue/framework/algorithm/array_like.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/framework/algorithm/include/lue/framework/algorithm/array_like.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include "lue/framework/algorithm/policy/all_values_within_domain.hpp"
#include "lue/framework/algorithm/policy/default_policies.hpp"
#include "lue/framework/algorithm/policy/default_value_policies.hpp"
#include "lue/framework/partitioned_array.hpp"
#include "lue/framework/core/annotate.hpp"
namespace lue {
namespace detail {
template<
typename Policies,
typename InputElement,
typename OutputElement,
Rank rank>
ArrayPartition<OutputElement, rank> array_like_partition(
Policies const& policies,
ArrayPartition<InputElement, rank> const& input_partition,
OutputElement const fill_value)
{
using InputPartition = ArrayPartition<InputElement, rank>;
using Offset = OffsetT<InputPartition>;
using Shape = ShapeT<InputPartition>;
using OutputPartition = ArrayPartition<OutputElement, rank>;
using OutputData = DataT<OutputPartition>;
lue_hpx_assert(input_partition.is_ready());
return hpx::dataflow(
hpx::launch::async,
hpx::unwrapping(
[policies, input_partition, fill_value](
Offset const& offset,
Shape const& shape)
{
AnnotateFunction annotation{"array_like_partition"};
HPX_UNUSED(input_partition);
OutputData output_partition_data{shape};
auto const& indp = std::get<0>(policies.inputs_policies()).input_no_data_policy();
auto const& ondp = std::get<0>(policies.outputs_policies()).output_no_data_policy();
Count const nr_elements{lue::nr_elements(output_partition_data)};
if(indp.is_no_data(fill_value))
{
for(Index i = 0; i < nr_elements; ++i)
{
ondp.mark_no_data(output_partition_data, i);
}
}
else
{
for(Index i = 0; i < nr_elements; ++i)
{
output_partition_data[i] = fill_value;
}
}
return OutputPartition{hpx::find_here(), offset, std::move(output_partition_data)};
}
),
input_partition.offset(),
input_partition.shape());
}
} // namespace detail
namespace policy::array_like {
template<
typename OutputElement,
typename InputElement>
using DefaultPolicies = policy::DefaultPolicies<
AllValuesWithinDomain<InputElement>,
OutputElements<OutputElement>,
InputElements<InputElement>>;
template<
typename OutputElement,
typename InputElement>
using DefaultValuePolicies = policy::DefaultValuePolicies<
AllValuesWithinDomain<InputElement>,
OutputElements<OutputElement>,
InputElements<InputElement>>;
} // namespace policy::array_like
template<
typename Policies,
typename InputElement,
typename OutputElement,
Rank rank>
struct ArrayLikePartitionAction:
hpx::actions::make_action<
decltype(&detail::array_like_partition<Policies, InputElement, OutputElement, rank>),
&detail::array_like_partition<Policies, InputElement, OutputElement, rank>,
ArrayLikePartitionAction<Policies, InputElement, OutputElement, rank>>::type
{};
template<
typename OutputElement,
typename Policies,
typename InputElement,
Rank rank>
PartitionedArray<OutputElement, rank> array_like(
Policies const& policies,
PartitionedArray<InputElement, rank> const& input_array,
hpx::shared_future<OutputElement> const& fill_value)
{
using InputArray = PartitionedArray<InputElement, rank>;
using InputPartitions = PartitionsT<InputArray>;
using InputPartition = PartitionT<InputArray>;
using OutputArray = PartitionedArray<OutputElement, rank>;
using OutputPartitions = PartitionsT<OutputArray>;
ArrayLikePartitionAction<Policies, InputElement, OutputElement, rank> action;
Localities<rank> const& localities{input_array.localities()};
InputPartitions const& input_partitions{input_array.partitions()};
OutputPartitions output_partitions{shape_in_partitions(input_array)};
for(Index p = 0; p < nr_partitions(input_array); ++p)
{
output_partitions[p] = hpx::dataflow(
hpx::launch::async,
[locality_id=localities[p], action, policies](
InputPartition const& input_partition,
hpx::shared_future<OutputElement> const& fill_value)
{
AnnotateFunction annotation{"array_like"};
return action(locality_id, policies, input_partition, fill_value.get());
},
input_partitions[p],
fill_value);
}
return OutputArray{shape(input_array), localities, std::move(output_partitions)};
}
template<
typename OutputElement,
typename Policies,
typename InputElement,
Rank rank>
PartitionedArray<OutputElement, rank> array_like(
Policies const& policies,
PartitionedArray<InputElement, rank> const& input_array,
OutputElement const fill_value)
{
return array_like(policies, input_array, hpx::make_ready_future<OutputElement>(fill_value).share());
}
template<
typename OutputElement,
typename InputElement,
Rank rank>
PartitionedArray<OutputElement, rank> array_like(
PartitionedArray<InputElement, rank> const& input_array,
OutputElement const fill_value)
{
using Policies = policy::array_like::DefaultPolicies<OutputElement, InputElement>;
return array_like(Policies{}, input_array, fill_value);
}
} // namespace lue
| 35.693989 | 112 | 0.582823 | [
"shape"
] |
f62bdf33e0db716b446d0b9115e7e767a758c2eb | 181,515 | cpp | C++ | BigDataGeneratorSuite/Graph_datagen/snap-exp/wikinet.cpp | felidsche/BigDataBench_V5.0_BigData_ComponentBenchmark | c65c3df033b84dfb6d229f74e564d69cfe624556 | [
"Apache-2.0"
] | 1,805 | 2015-01-06T20:01:35.000Z | 2022-03-29T16:12:51.000Z | snap-exp/wikinet.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 168 | 2015-01-07T22:57:29.000Z | 2022-03-15T01:20:24.000Z | snap-exp/wikinet.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 768 | 2015-01-09T02:28:45.000Z | 2022-03-30T00:53:46.000Z | #include "stdafx.h"
#include "wikinet.h"
#include "trawling.h"
/////////////////////////////////////////////////
// Wikipedia Talk Network
TWikiUsr::TWikiUsr() : Usr(), Admin(false), ElecTm(), BarnStars(), MnEdCnt(), MnEdWrds(), MnTkEdCnt(), MnTkEdWrds(),
WkEdCnt(), WkEdWrds(), WkTkEdCnt(), WkTkEdWrds(), MnRevCnt(), MnRevWrds() {
}
TWikiUsr::TWikiUsr(const TChA& UsrStr) : Usr(UsrStr), Admin(false), ElecTm(), BarnStars(), MnEdCnt(), MnEdWrds(),
MnTkEdCnt(), MnTkEdWrds(), WkEdCnt(), WkEdWrds(), WkTkEdCnt(), WkTkEdWrds(), MnRevCnt(), MnRevWrds() {
}
TWikiUsr::TWikiUsr(const TWikiUsr& WikiUsr) : Usr(WikiUsr.Usr), Admin(WikiUsr.Admin), ElecTm(WikiUsr.ElecTm),
BarnStars(WikiUsr.BarnStars), MnEdCnt(WikiUsr.MnEdCnt), MnEdWrds(WikiUsr.MnEdWrds),
MnTkEdCnt(WikiUsr.MnTkEdCnt), MnTkEdWrds(WikiUsr.MnTkEdWrds), WkEdCnt(WikiUsr.WkEdCnt),
WkEdWrds(WikiUsr.WkEdWrds), WkTkEdCnt(WikiUsr.WkTkEdCnt), WkTkEdWrds(WikiUsr.WkTkEdWrds),
MnRevCnt(WikiUsr.MnRevCnt), MnRevWrds(WikiUsr.MnRevCnt) {
}
TWikiUsr::TWikiUsr(TSIn& SIn) : Usr(SIn), Admin(SIn), ElecTm(SIn), BarnStars(SIn), MnEdCnt(SIn),
MnEdWrds(SIn), MnTkEdCnt(SIn), MnTkEdWrds(SIn), WkEdCnt(SIn), WkEdWrds(SIn), WkTkEdCnt(SIn), WkTkEdWrds(SIn)
, MnRevCnt(SIn), MnRevWrds(SIn)
{
}
void TWikiUsr::Save(TSOut& SOut) const {
Usr.Save(SOut); Admin.Save(SOut); ElecTm.Save(SOut);
BarnStars.Save(SOut); MnEdCnt.Save(SOut); MnEdWrds.Save(SOut);
MnTkEdCnt.Save(SOut); MnTkEdWrds.Save(SOut); WkEdCnt.Save(SOut); WkEdWrds.Save(SOut);
WkTkEdCnt.Save(SOut); WkTkEdWrds.Save(SOut);
MnRevCnt.Save(SOut); MnRevWrds.Save(SOut);
}
TWikiTalkEdge::TWikiTalkEdge() : TotTalks(), TotWords(), TalksBE(), WordsBE(), TalksAE(), WordsAE(), VoteSign(0), FirstTalk(), LastTalk(), VoteTm() {
}
TWikiTalkEdge::TWikiTalkEdge(const int& _VoteSign) : TotTalks(), TotWords(), TalksBE(), WordsBE(), TalksAE(), WordsAE(),
VoteSign(_VoteSign), FirstTalk(), LastTalk(), VoteTm() {
}
TWikiTalkEdge::TWikiTalkEdge(const TSecTm& FTalk, const TSecTm& LTalk, const int& NTalks, const int& NWords) :
TotTalks(NTalks), TotWords(NWords), TalksBE(), WordsBE(), TalksAE(), WordsAE(), VoteSign(0), FirstTalk(FTalk), LastTalk(LTalk), VoteTm() {
}
TWikiTalkEdge::TWikiTalkEdge(const TWikiTalkEdge& Talk) : TotTalks(Talk.TotTalks), TotWords(Talk.TotWords),
TalksBE(Talk.TalksBE), WordsBE(Talk.WordsBE), TalksAE(Talk.TalksAE), WordsAE(Talk.WordsAE),
VoteSign(Talk.VoteSign), FirstTalk(Talk.FirstTalk), LastTalk(Talk.LastTalk), VoteTm(Talk.VoteTm) {
}
TWikiTalkEdge::TWikiTalkEdge(TSIn& SIn) : TotTalks(SIn), TotWords(SIn), TalksBE(SIn), WordsBE(SIn),
TalksAE(SIn), WordsAE(SIn), VoteSign(SIn), FirstTalk(SIn), LastTalk(SIn), VoteTm(SIn) {
}
void TWikiTalkEdge::Save(TSOut& SOut) const {
TotTalks.Save(SOut); TotWords.Save(SOut);
TalksBE.Save(SOut); WordsBE.Save(SOut);
TalksAE.Save(SOut); WordsAE.Save(SOut);
VoteSign.Save(SOut); FirstTalk.Save(SOut);
LastTalk.Save(SOut); VoteTm.Save(SOut);
}
int TWikiTalkNet::GetUsrNId(const TStr& UsrStr) const {
const int KeyId = UsrNIdH.GetKeyId(UsrStr);
if (KeyId==-1) { return -1; }
else { return UsrNIdH[KeyId]; }
}
bool TWikiTalkNet::IsUsr(const TStr& UsrStr) const {
return UsrNIdH.IsKey(UsrStr);
}
void TWikiTalkNet::PermuteAllVoteSigns(const bool& OnlyVotes) {
printf("\nPermuting %s edge signs\n", OnlyVotes?"VOTE":"ALL");
TVec<TWikiTalkEdge> EDatV;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (OnlyVotes && EI().GetVote() != 0) { EDatV.Add(EI()); }
else if (! OnlyVotes){ EDatV.Add(EI()); }
}
EDatV.Shuffle(TInt::Rnd);
int cnt = 0;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (OnlyVotes && EI().GetVote() != 0) { EI() = EDatV[cnt++]; }
else if (! OnlyVotes){ EI() = EDatV[cnt++]; }
}
}
void TWikiTalkNet::PermuteOutVoteSigns(const bool& OnlyVotes) {
TIntV VoteSignV;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (OnlyVotes && NI.GetOutEDat(e).GetVote() != 0) {
VoteSignV.Add(NI.GetOutEDat(e).GetVote()); }
else if (! OnlyVotes) {
VoteSignV.Add(NI.GetOutEDat(e).GetVote()); }
}
}
VoteSignV.Shuffle(TInt::Rnd);
int cnt = 0;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (OnlyVotes && NI.GetOutEDat(e).GetVote() != 0) {
NI.GetOutEDat(e).VoteSign = VoteSignV[cnt++]; }
else if (! OnlyVotes) {
NI.GetOutEDat(e).VoteSign = VoteSignV[cnt++]; }
}
}
}
void TWikiTalkNet::CountStructBalance() const {
TIntSet NbrIdSet;
THash<TIntTr, TInt> TriadCntH;
TIntH SignH;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
SignH.AddDat(EI().VoteSign()) += 1;
}
printf("Structural balance triads:\n background sign distribution:\n");
SignH.SortByKey(false);
for (int i = 0; i < SignH.Len(); i++) {
printf("\t%2d\t%d\n", SignH.GetKey(i), SignH[i]);
}
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
const TNodeI SrcNI = GetNI(EI.GetSrcNId());
const TNodeI DstNI = GetNI(EI.GetDstNId());
const TInt E1Dat = EI().VoteSign();
NbrIdSet.Clr(false);
for (int es = 0; es < SrcNI.GetDeg(); es++) {
NbrIdSet.AddKey(SrcNI.GetNbrNId(es)); }
for (int ed = 0; ed < DstNI.GetDeg(); ed++) {
const int nbr = DstNI.GetNbrNId(ed);
if (! NbrIdSet.IsKey(nbr)) { continue; }
const TInt E2Dat = SrcNI.GetNbrEDat(NbrIdSet.GetKeyId(nbr)).VoteSign();
const TInt E3Dat = DstNI.GetNbrEDat(ed).VoteSign();
TriadCntH.AddDat(TIntTr(TMath::Mx(E1Dat, E2Dat, E3Dat),
TMath::Median(E1Dat, E2Dat, E3Dat), TMath::Mn(E1Dat, E2Dat, E3Dat))) += 1;
}
}
TriadCntH.SortByKey(false);
printf("triad counts (all counts times 3):\n");
int SumTriad = 0, SignTriad=0;
for (int i = 0; i < TriadCntH.Len(); i++) {
SumTriad += TriadCntH[i];
TIntTr SignTr = TriadCntH.GetKey(i);
if (SignTr.Val1!=0 && SignTr.Val2!=0 && SignTr.Val3!=0) {
SignTriad += TriadCntH[i];; }
}
for (int i = 0; i < TriadCntH.Len(); i++) {
TIntTr SignTr = TriadCntH.GetKey(i);
printf("\t%2d %2d %2d\t%8d\t%f", SignTr.Val1, SignTr.Val2, SignTr.Val3,
TriadCntH[i], TriadCntH[i]/double(SumTriad));
if (SignTr.Val1!=0 && SignTr.Val2!=0 && SignTr.Val3!=0) {
printf("\t%f", TriadCntH[i]/double(SignTriad)); }
printf("\n");
}
}
void TWikiTalkNet::FindPartitions(const int& NPart, const bool& OnlyMinus) const {
printf("\nFind %d partitions use %s edges\n", NPart, OnlyMinus?"NEGATIVE":"ALL");
TIntV NIdV(GetNodes(), 0);
TIntH NIdPartH;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
NIdPartH.AddDat(NI.GetId(), TInt::Rnd.GetUniDevInt(NPart));
NIdV.Add(NI.GetId());
}
int Flips = 0;
TIntPrV CntPartV;
for (int p = 0; p < NPart; p++) {
CntPartV.Add(TIntPr(0, p)); }
for (int iter = 0; iter < 100; iter++) {
NIdV.Shuffle(TInt::Rnd);
Flips = 0;
for (int n = 0; n < NIdV.Len(); n++) {
TNodeI NI = GetNI(NIdV[n]);
for (int p = 0; p < NPart; p++) {
CntPartV[p].Val1=0; CntPartV[p].Val2=p; }
for (int e = 0; e < NI.GetOutDeg(); e++) {
const int DstPart = NIdPartH.GetDat(NI.GetOutNId(e));
const int Vote = NI.GetOutEDat(e).GetVote();
if (OnlyMinus && Vote==-1) { CntPartV[DstPart].Val1 += -1; }
else if (! OnlyMinus) { CntPartV[DstPart].Val1 += Vote; }
}
CntPartV.Sort(false); // take group with highest score (little - edges, lots + edges)
const int NewPart = CntPartV[0].Val2;
if (NIdPartH.GetDat(NI.GetId()) != NewPart) {
NIdPartH.AddDat(NI.GetId(), NewPart);
Flips++;
}
}
//printf(" %d", Flips);
}
// calculate overall energy
int OkMns=0, OkPls=0, AllMns=0, AllPls=0;
TIntH OkPlsH, AllPlsH, OkMnsH, AllMnsH;
for (int p = 0; p < NPart; p++) {
OkPlsH.AddDat(p,0); AllPlsH.AddDat(p,0);
OkMnsH.AddDat(p,0); AllMnsH.AddDat(p,0);
}
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
const int SrcPart = NIdPartH.GetDat(NI.GetId());
for (int e = 0; e < NI.GetOutDeg(); e++) {
const int DstPart = NIdPartH.GetDat(NI.GetOutNId(e));
const int Vote = NI.GetOutEDat(e).GetVote();
if (Vote == -1) {
if (DstPart != SrcPart) { OkMnsH.AddDat(SrcPart) += 1; OkMns++; }
AllMnsH.AddDat(SrcPart) += 1; AllMns++; }
if (Vote == +1) {
if (DstPart == SrcPart) { OkPlsH.AddDat(SrcPart) += 1; OkPls++; }
AllPlsH.AddDat(SrcPart) += 1; AllPls++;
}
}
}
printf("\nSatisfied edges: + : %5d / %5d = %f\n", OkPls, AllPls, double(OkPls)/double(AllPls));
printf( " - : %5d / %5d = %f\n", OkMns, AllMns, double(OkMns)/double(AllMns));
TIntH PartCntH;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
PartCntH.AddDat(NIdPartH.GetDat(NI.GetId())) += 1; }
PartCntH.SortByKey();
for (int p = 0; p < PartCntH.Len(); p++) {
printf(" part %2d : %5d (%.4f) nodes: +: %25s -: %25s\n", p, PartCntH[p], PartCntH[p]/double(NIdPartH.Len()),
TStr::Fmt("%5d/%d=%.4f", OkPlsH.GetDat(PartCntH.GetKey(p)), AllPlsH.GetDat(PartCntH.GetKey(p)), OkPlsH.GetDat(PartCntH.GetKey(p))/double(AllPlsH.GetDat(PartCntH.GetKey(p)))).CStr(),
TStr::Fmt("%5d/%d=%.4f", OkMnsH.GetDat(PartCntH.GetKey(p)), AllMnsH.GetDat(PartCntH.GetKey(p)), OkMnsH.GetDat(PartCntH.GetKey(p))/double(AllMnsH.GetDat(PartCntH.GetKey(p)))).CStr() );
}
}
void TWikiTalkNet::GetPartStat(const TVec<TIntV>& PartNIdV) const {
THash<TIntPr, TIntPr> PartEdgeH;
TIntH NIdPartH;
for (int p = 0; p < PartNIdV.Len(); p++) {
for (int n = 0; n < PartNIdV[p].Len(); n++) {
NIdPartH.AddDat(PartNIdV[p][n], p);
}
}
TInt DstPart;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
if (! NIdPartH.IsKey(NI.GetId())) { continue; }
const int p = NIdPartH.GetDat(NI.GetId());
for (int e = 0; e < NI.GetOutDeg(); e++) {
const int Vote = NI.GetOutEDat(e).GetVote();
TIntPr& IOCnt = PartEdgeH.AddDat(TIntPr(p, Vote));
if (NIdPartH.IsKeyGetDat(NI.GetOutNId(e), DstPart) && DstPart==p) {
if (Vote==1) { IOCnt.Val1++; } else { IOCnt.Val2++; } }
else {
if (Vote==-1) { IOCnt.Val1++; } else { IOCnt.Val2++; } }
}
}
PartEdgeH.SortByKey();
printf("Partition statistics (satisfied edges):\n");
for (int p = 0; p < PartEdgeH.Len(); p++) {
printf(" %2d %2d : %6d : %6d = %f\n", PartEdgeH.GetKey(p).Val1, PartEdgeH.GetKey(p).Val2,
PartEdgeH[p].Val1(), PartEdgeH[p].Val2(), PartEdgeH[p].Val1/double(PartEdgeH[p].Val1+PartEdgeH[p].Val2));
}
}
// get subnetwork on votes
// VoteSign=11 : take +1 and -1 votes
PWikiTalkNet TWikiTalkNet::GetVoteSubNet(const int& VoteSign, const bool& VoteOnly, const bool& TalkOnly) const {
PWikiTalkNet Net = TWikiTalkNet::New();
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (! (EI().GetVote()==VoteSign || (VoteSign==11 && EI().GetVote()!=0))) { continue; }
if (VoteOnly && ! EI().IsVoteE()) { continue; }
if (TalkOnly && ! EI().IsTalkE()) { continue; }
if (! Net->IsNode(EI.GetSrcNId())) {
Net->UsrNIdH.AddDat(EI.GetSrcNDat().Usr, EI.GetSrcNId());
Net->AddNode(EI.GetSrcNId(), EI.GetSrcNDat());
}
if (! Net->IsNode(EI.GetDstNId())) {
Net->UsrNIdH.AddDat(EI.GetDstNDat().Usr, EI.GetDstNId());
Net->AddNode(EI.GetDstNId(), EI.GetDstNDat());
}
Net->AddEdge(EI);
}
TSnap::PrintInfo(Net, TStr::Fmt("Vote network: sign %d %s %s",
VoteSign, VoteOnly?"OnlyVote":"", TalkOnly?"OnlyTalk":""));
return Net;
}
PSignNet TWikiTalkNet::GetSignNet(const int& VoteSign, const bool& VoteOnly, const bool& TalkOnly) const {
PSignNet Net = TSignNet::New();
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI.GetSrcNId() == EI.GetDstNId()) { continue; }
if (! (EI().GetVote()==VoteSign || (VoteSign==11 && EI().GetVote()!=0))) { continue; }
if (VoteOnly && ! EI().IsVoteE()) { continue; }
if (TalkOnly && ! EI().IsTalkE()) { continue; }
if (! Net->IsNode(EI.GetSrcNId())) {
Net->AddNode(EI.GetSrcNId(), 0); }
if (! Net->IsNode(EI.GetDstNId())) {
Net->AddNode(EI.GetDstNId(), 0); }
Net->AddEdge(EI.GetSrcNId(), EI.GetDstNId(), EI().GetVote());
}
//TSnap::PrintInfo(Net, TStr::Fmt("SIGN-NET %d %s %s", VoteSign, VoteOnly?"OnlyVote":"", TalkOnly?"OnlyTalk":""));
return Net;
}
void TWikiTalkNet::TestPartitions(const TStr& OutFNm) {
{ PSignNet MnsNet = GetSignNet(-1, true, false);
PSignNet AllNet = GetSignNet(11, true, false);
PSignNet CoreNet = TSnap::GetKCore(TSnap::GetMxWcc(MnsNet), 2);
TSnap::PrintInfo(CoreNet, "MINUS K-CORE");
for (int npart = 2; npart < 5; npart++) {
printf("\n**** %d-partitions\n", npart);
THopfield Hopfield(CoreNet);
Hopfield.FindStableSet(npart, 1000);
TVec<TIntV> PartNIdV;
Hopfield.GetStableSet(990, PartNIdV);
Hopfield.PlotPartStab(TStr::Fmt("%s-c2-p%d", OutFNm.CStr(), npart));
CoreNet->GetPartStat(PartNIdV, "NETWORK 2-CORE");
MnsNet->GetPartStat(PartNIdV, "FULL MINUS NET");
AllNet->GetPartStat(PartNIdV, "FULL PLUS-MINUS NET");
} }
PermuteAllVoteSigns(false);
printf("\n*** PERMUTE EDGE SIGNS ************************************************************************************\n");
{ PSignNet MnsNet = GetSignNet(-1, true, false);
PSignNet AllNet = GetSignNet(11, true, false);
PSignNet CoreNet = TSnap::GetKCore(TSnap::GetMxWcc(MnsNet), 2);
TSnap::PrintInfo(CoreNet, "MINUS K-CORE");
for (int npart = 2; npart < 6; npart++) {
printf("\n**** %d-partitions\n", npart);
THopfield Hopfield(CoreNet);
Hopfield.FindStableSet(npart, 1000);
TVec<TIntV> PartNIdV;
Hopfield.GetStableSet(990, PartNIdV);
Hopfield.PlotPartStab(TStr::Fmt("%s-c2-Rp%d", OutFNm.CStr(), npart));
CoreNet->GetPartStat(PartNIdV, "NETWORK 2-CORE");
MnsNet->GetPartStat(PartNIdV, "FULL MINUS NET");
AllNet->GetPartStat(PartNIdV, "FULL PLUS-MINUS NET");
} }
}
void TWikiTalkNet::PlotBarnStarDelta(const TStr& OutFNm) const {
THash<TInt, TMom> DiffMomH;
TIntH DiffCntH;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI().GetVote() == 0) { continue; }
//if (! EI().IsVoteTalkE()) { continue; }
DiffMomH.AddDat(EI.GetSrcNDat().GetStars()-EI.GetDstNDat().GetStars()).Add(EI().GetVote()==1?1:0);
DiffCntH.AddDat(EI.GetSrcNDat().GetStars()-EI.GetDstNDat().GetStars()) += 1;
}
TGnuPlot::PlotValMomH(DiffMomH, "dBarnStars-"+OutFNm, "Number of BarnStars (over ALL VOTES): "+OutFNm, "Barnstars delta (source - destination)",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, true);
TGnuPlot::PlotValCntH(DiffCntH, "dBarnStarts2-"+OutFNm, "Number of BarnSTars (over aLL VOES): "+OutFNm, "Barnstars delta (source - destination)",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
}
int log10Delta(const int& Delta) {
//return 10*(Delta/10);
if (Delta == 0) { return 0; }
else if (Delta > 0) { return (int)log10((double)Delta)+1; }
else if (Delta < 0) { return -(int)log10((double)-Delta)+1; }
Fail; return -1;
}
// For every talk edge
void TWikiTalkNet::PlotFracPosVsWords(const TStr& OutFNm) const {
THash<TInt, TMom> DiffMomH, DiffMomH2, WrdAE, WrdBE, TlkAE, TlkBE;
TIntH DiffCntH, DiffCntH2, CWrdAE, CWrdBE, CTlkAE, CTlkBE;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI().GetVote() == 0) { continue; }
if (! EI().IsVoteTalkE()) { continue; }
if (EI().GetTalks() < 50) {
DiffMomH.AddDat(EI().GetTalks()).Add(EI().GetVote()==1?1:0);
DiffCntH.AddDat(EI().GetTalks()) += 1;
TlkBE.AddDat((EI().GetTalksBE())).Add(EI().GetVote()==1?1:0);
CTlkBE.AddDat((EI().GetTalksBE())) += 1;
TlkAE.AddDat((EI().GetTalksAE())).Add(EI().GetVote()==1?1:0);
CTlkAE.AddDat((EI().GetTalksAE())) += 1;
}
DiffMomH2.AddDat(log10Delta(EI().GetWords())).Add(EI().GetVote()==1?1:0);
DiffCntH2.AddDat(log10Delta(EI().GetWords())) += 1;
WrdBE.AddDat(log10Delta(EI().GetWordsBE())).Add(EI().GetVote()==1?1:0);
CWrdBE.AddDat(log10Delta(EI().GetWordsBE())) += 1;
WrdAE.AddDat(log10Delta(EI().GetWordsAE())).Add(EI().GetVote()==1?1:0);
CWrdAE.AddDat(log10Delta(EI().GetWordsAE())) += 1;
}
TGnuPlot::PlotValMomH(DiffMomH, "talks-"+OutFNm, "Number of talks: "+OutFNm, "Number of times users talked",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValCntH(DiffCntH, "talks2-"+OutFNm, "Number of talks: "+OutFNm, "Number of times users talked",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValMomH(DiffMomH2, "words-"+OutFNm, "Number of words edited: "+OutFNm, "Number of words edited",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValCntH(DiffCntH2, "words2-"+OutFNm, "Number of words edited: "+OutFNm, "Number of words edited",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
// words
TGnuPlot::PlotValMomH(WrdAE, "wordsBE-"+OutFNm, "Number of words edited: "+OutFNm, "Number of words edited BEFORE the election (on talk page between a pair)",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValCntH(CWrdAE, "wordsBE2-"+OutFNm, "Number of words edited: "+OutFNm, "Number of words edited BEFORE the election (on talk page between a pair)",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValMomH(WrdBE, "wordsAE-"+OutFNm, "Number of words edited: "+OutFNm, "Number of words edited AFTER the election (on talk page between a pair)",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValCntH(CWrdBE, "wordsAE2-"+OutFNm, "Number of words edited: "+OutFNm, "Number of words edited AFTER the election (on talk page between a pair)",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
// talks
TGnuPlot::PlotValMomH(TlkAE, "talksBE-"+OutFNm, "Number of talks edited: "+OutFNm, "Number of talks BEFORE the election (on talk page between a pair)",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValCntH(CTlkAE, "talksBE2-"+OutFNm, "Number of talks edited: "+OutFNm, "Number of talks BEFORE the election (on talk page between a pair)",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValMomH(TlkBE, "talksAE-"+OutFNm, "Number of talks edited: "+OutFNm, "Number of talks AFTER the election (on talk page between a pair)",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValCntH(CTlkBE, "talksAE2-"+OutFNm, "Number of talks edited: "+OutFNm, "Number of talks AFTER the election (on talk page between a pair)",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
}
// votes based on the characteristic of the target
void TWikiTalkNet::PlotFracPosVsWords2(const TStr& OutFNm) const {
THash<TInt, TMom> TlkAll, WrdAll, WrdAE, WrdBE, TlkAE, TlkBE, EdtAll, EdtAll2, EdtAll3;
// for every node compute total words and talks before and after the election
TIntH NIdTAE, NIdTBE, NIdTalks, NIdWAE, NIdWBE, NIdWords;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
NIdTAE.AddDat(EI.GetDstNId()) += EI().GetTalksAE();
NIdTBE.AddDat(EI.GetDstNId()) += EI().GetTalksBE();
NIdTalks.AddDat(EI.GetDstNId()) += EI().GetTalks();
NIdWAE.AddDat(EI.GetDstNId()) += EI().GetWordsAE();
NIdWBE.AddDat(EI.GetDstNId()) += EI().GetWordsBE();
NIdWords.AddDat(EI.GetDstNId()) += EI().GetWords();
}
// for every vote get target total talk activity
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI().GetVote() == 0) { continue; }
const int C = EI.GetDstNId(); // candidate
if (NIdTAE.GetDat(C)<1000) TlkAE.AddDat(NIdTAE.GetDat(C)).Add(EI().GetVote()==1?1:0);
if (NIdTBE.GetDat(C)<1000) TlkBE.AddDat(NIdTBE.GetDat(C)).Add(EI().GetVote()==1?1:0);
if (NIdTalks.GetDat(C)<1000) TlkAll.AddDat(NIdTalks.GetDat(C)).Add(EI().GetVote()==1?1:0);
WrdAE.AddDat(log10Delta(NIdWAE.GetDat(C))).Add(EI().GetVote()==1?1:0);
WrdBE.AddDat(log10Delta(NIdWBE.GetDat(C))).Add(EI().GetVote()==1?1:0);
WrdAll.AddDat(log10Delta(NIdWords.GetDat(C))).Add(EI().GetVote()==1?1:0);
EdtAll.AddDat(log10Delta(EI.GetDstNDat().GetEdCnt())).Add(EI().GetVote()==1?1:0);
EdtAll2.AddDat(log10Delta(EI.GetDstNDat().GetAllEdCnt())).Add(EI().GetVote()==1?1:0);
EdtAll3.AddDat(log10Delta(EI.GetDstNDat().GetTkEdCnt())).Add(EI().GetVote()==1?1:0);
}
TGnuPlot::PlotValMomH(EdtAll, "editsTot-"+OutFNm, "Number of edits: "+OutFNm, "Total number of times candidate edited",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(EdtAll2, "editsTot2-"+OutFNm, "Number of edits: "+OutFNm, "Total number of times candidate edited",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(EdtAll3, "editsTot3-"+OutFNm, "Number of edits: "+OutFNm, "Total number of times candidate edited",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
// words
TGnuPlot::PlotValMomH(TlkAll, "talksTot-"+OutFNm, "Number of talks: "+OutFNm, "Total number of times candidate talked",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(WrdAE, "wordsBETot-"+OutFNm, "Number of words edited: "+OutFNm, "1+Log_10 Total number of words edited of candidate BEFORE the election",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(WrdBE, "wordsAETot-"+OutFNm, "Number of words edited: "+OutFNm, "1+Log_10 Total number of words edited of candidate AFTER the election",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
// talks
TGnuPlot::PlotValMomH(WrdAll, "wordsTot-"+OutFNm, "Number of words edited: "+OutFNm, "1+Log_10 Total number of words candidate edited",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(TlkAE, "talksBETot-"+OutFNm, "Number of talks edited: "+OutFNm, "Total number of talks of candidate BEFORE the election",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(TlkBE, "talksAETot-"+OutFNm, "Number of talks edited: "+OutFNm, "Total number of talks of candidate AFTER the election",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
}
void TWikiTalkNet::PlotNodeAttrDistr(const TStr& OutFNm) const {
TIntH BarnStars, AllEdCnt, AllEdWrds, MnEdCnt, MnEdWrds, TkEdCnt, TkEdWrds;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
const TWikiUsr& N = NI();
BarnStars.AddDat(N.GetStars()) += 1;
AllEdCnt.AddDat(N.GetAllEdCnt()) += 1;
AllEdWrds.AddDat(1*(N.GetAllWrdCnt()/1)) += 1;
MnEdCnt.AddDat(N.GetEdCnt()) += 1;
MnEdWrds.AddDat(1*(N.GetWrdCnt()/1)) += 1;
TkEdCnt.AddDat(N.GetTkEdCnt()) += 1;
TkEdWrds.AddDat(1*(N.GetTkWrdCnt()/1)) += 1;
}
TGnuPlot::PlotValCntH(BarnStars, "barnStars-"+OutFNm, OutFNm, "Number of barn stars", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValCntH(AllEdCnt, "allEdCnt-"+OutFNm, OutFNm, "Number of edits", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValCntH(AllEdWrds, "allEdWrds-"+OutFNm, OutFNm, "Number of edited words", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValCntH(MnEdCnt, "MnEdCnt-"+OutFNm, OutFNm, "Number of edits on MAIN pages", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValCntH(MnEdWrds, "MnEdWrds-"+OutFNm, OutFNm, "Number of edited words onmain pages", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValCntH(TkEdCnt, "tkEdCnt-"+OutFNm, OutFNm, "Number of edits on TALK pages", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
TGnuPlot::PlotValCntH(TkEdWrds, "tkEdWrds-"+OutFNm, OutFNm, "Number of edited words onmain pages", "Number of users", gpsLog, false, gpwLinesPoints, false, false);
}
void TWikiTalkNet::PlotFracPosVsEdgeAttr(const TStr& OutFNm) const {
THash<TInt, TMom> EdgeTalksH, EdgeTalksH2, EdgeWordsH;
THash<TInt, TMom> dBarnStars, dAllEdCnt, dAllEdWrds;
TIntH dBarnStarsCnt, dAllEdCntCnt, dAllEdWrdsCnt;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
const int Val = EI().GetVote() ==1 ? 1 : 0;
if (EI().GetTalks() < 100) {
EdgeTalksH.AddDat(int(EI().GetTalks())).Add(Val);
}
EdgeTalksH2.AddDat((int)log10((double)EI().GetTalks())).Add(Val);
EdgeWordsH.AddDat((int)log10((double)EI().GetWords())).Add(Val);
const TWikiUsr& S = EI.GetSrcNDat();
const TWikiUsr& D = EI.GetDstNDat();
if (abs(S.GetStars()-D.GetStars()) < 10) {
dBarnStars.AddDat(S.GetStars()-D.GetStars()).Add(Val);
dBarnStarsCnt.AddDat(S.GetStars()-D.GetStars())++;
}
dAllEdCnt.AddDat(log10Delta(S.GetAllEdCnt()-D.GetAllEdCnt())).Add(Val);
dAllEdCntCnt.AddDat(log10Delta(S.GetAllEdCnt()-D.GetAllEdCnt()))++;
dAllEdWrds.AddDat(log10Delta(S.GetAllWrdCnt()-D.GetAllWrdCnt())).Add(Val);
dAllEdWrdsCnt.AddDat(log10Delta(S.GetAllWrdCnt()-D.GetAllWrdCnt()))++;
}
// plot
const bool SDev = true;
TGnuPlot::PlotValMomH(EdgeTalksH, "edgeTks"+OutFNm, OutFNm, "Number of talks over the edge", "Fraction of positive edges", gpsAuto, gpwLinesPoints, true, false, false, false, false, SDev);
TGnuPlot::PlotValMomH(EdgeTalksH2, "edgeTks2"+OutFNm, OutFNm, "1+Log_{10} Number of talks over the edge", "Fraction of positive edges", gpsAuto, gpwLinesPoints, true, false, false, false, false, SDev);
TGnuPlot::PlotValMomH(EdgeWordsH, "edgeWrds"+OutFNm, OutFNm, "1+Log_{10} Number of words over all talks over the edge", "Fraction of positive edges", gpsAuto, gpwLinesPoints, true, false, false, false, false, SDev);
TGnuPlot::PlotValMomH(dBarnStars, "dBarnStars-"+OutFNm, OutFNm, "delta BarnStars", "Fraction of positive edges", gpsAuto, gpwLinesPoints, true, false, false, false, false, SDev);
TGnuPlot::PlotValMomH(dAllEdCnt, "dAllEdCnt-"+OutFNm, OutFNm, "delta AllEdCnt", "Fraction of positive edges", gpsAuto, gpwLinesPoints, true, false, false, false, false, SDev);
TGnuPlot::PlotValMomH(dAllEdWrds, "dAllEdWrds-"+OutFNm, OutFNm, "delta AllEdWrds", "Fraction of positive edges", gpsAuto, gpwLinesPoints, true, false, false, false, false, SDev);
TGnuPlot::PlotValCntH(dBarnStarsCnt, "dBarnStarsCnt-"+OutFNm, OutFNm, "delta BarnStars", "Count", gpsAuto);
TGnuPlot::PlotValCntH(dAllEdCntCnt, "dAllEdCntCnt-"+OutFNm, OutFNm, "delta AllEdCnt", "Count", gpsAuto);
TGnuPlot::PlotValCntH(dAllEdWrdsCnt, "dAllEdWrdsCnt-"+OutFNm, OutFNm, "delta AllEdWrds", "Count", gpsAuto);
}
// plot the span of a particular edge:
// number of common friends of the endpoints
// path length between the endpoints
void TWikiTalkNet::PlotVoteSignCmnFriends(const TStr& OutFNm) const {
TFltFltH SupRngH, OppRngH; // path length
TFltFltH SupCmnH, OppCmnH; // common friends
THash<TFlt, TMom> RngFracH, CmnFracH; // fraction of supporters
PWikiTalkNet ThisPt = PWikiTalkNet((TWikiTalkNet*) this);
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
const int C = -1; Fail;//TGAlg::GetCmnNbrs(ThisPt, EI.GetSrcNId(), EI.GetDstNId(), false);
const int R = -1; //TGAlg::GetRangeDist(ThisPt, EI.GetSrcNId(), EI.GetDstNId(), false);
if (EI().GetVote() == 1) {
SupRngH.AddDat(R)++; RngFracH.AddDat(R).Add(1);
SupCmnH.AddDat(C)++; CmnFracH.AddDat(C).Add(1);
} else if (EI().GetVote() == -1) {
OppRngH.AddDat(R)++; RngFracH.AddDat(R).Add(0);
OppCmnH.AddDat(C)++; CmnFracH.AddDat(C).Add(0);
}
}
TGnuPlot::PlotValCntH(SupRngH, "rngSup-"+OutFNm, "range of support votes", "range (path length after edge is removed)", "count");
TGnuPlot::PlotValCntH(OppRngH, "rngOpp-"+OutFNm, "range of opposing votes", "range (path length after edge is removed)", "count");
TGnuPlot::PlotValCntH(SupCmnH, "cmnSup-"+OutFNm, "number of common friends of support votes", "number of common friends", "count", gpsLog);
TGnuPlot::PlotValCntH(OppCmnH, "cmnOpp-"+OutFNm, "number of common friends of opposing votes", "number of common friends", "count", gpsLog);
TGnuPlot::PlotValMomH(RngFracH, "fracRng-"+OutFNm, "fraction of support edges spanning range X", "range", "fraction of support edges");
TGnuPlot::PlotValMomH(CmnFracH, "fracCmn-"+OutFNm, "fraction of support edges having X common neighbors", "number of common neighbors", "fraction of support edges", gpsLog);
}
void TWikiTalkNet::SaveAreaUTrailAttr(const TStr& OutFNm, const int& MinUsrVotes, const TWikiElecBs& ElecBs) const {
TIntV UIdV;
TFltV AreaV;
TIntSet AdminSet, ElecUsrV;
{ TIntSet FqVoterSet; ElecBs.GetFqVoters(FqVoterSet, MinUsrVotes, 10, false); FqVoterSet.GetKeyV(UIdV);
TIntV ElecUIdV; ElecBs.GetElecUsrV(ElecUIdV); ElecUsrV=TIntSet(ElecUIdV); }
ElecBs.GetUsrAreaUTrail(UIdV, AreaV);
ElecBs.GetAdminSet(AdminSet);
FILE *F = fopen(OutFNm.CStr(), "wt");
fprintf(F, "Area\tUser\tIsAdmin\tIsElec\tTalkOutDeg\tInDeg\tTalkTriads\tBarnStars\tInAdmins\tOutAdmins\tAllEdCnt\tAllWrdCnt\tRevCnt\tRevWrds\n");
printf("%d users", UIdV.Len());
int skip=0;
for (int u = 0; u < UIdV.Len(); u++) {
TStr Usr = ElecBs.GetUsr(UIdV[u]);
if (! IsUsr(Usr)) { printf("x"); skip++; continue; } else { printf("."); }
fprintf(F, "%f\t%s\t%d\t%d", AreaV[u], Usr.CStr(), AdminSet.IsKey(UIdV[u])?1:0, ElecUsrV.IsKey(UIdV[u])?1:0);
TNodeI U = GetNI(GetUsrNId(Usr));
fprintf(F, "\t%d\t%d\t%d", U.GetOutDeg(), U.GetInDeg(), TSnap::GetNodeTriads<PWikiTalkNet>((TWikiTalkNet*)this, U.GetId()));
int OutAdmins=0, InAdmins=0;
for (int i = 0; i < U.GetOutDeg(); i++) {
if (U.GetOutNDat(i).IsAdmin()) { OutAdmins++; } }
for (int i = 0; i < U.GetInDeg(); i++) {
if (U.GetInNDat(i).IsAdmin()) { InAdmins++; } }
fprintf(F, "\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", U().GetStars(), OutAdmins, InAdmins,
U().GetAllEdCnt(), U().GetAllWrdCnt(), U().GetRevCnt(), U().GetRevWrds());
fflush(F);
}
fclose(F);
printf("\n%d users, %d skip\n", UIdV.Len(), skip);
}
void TWikiTalkNet::DumpEdgeStat() const {
TIntH VoteE, TalkE, AllE, VtTkE;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
const TWikiTalkEdge& E = EI();
const int V = E.GetVote();
AllE.AddDat(V) += 1;
if (E.IsTalkE()) { TalkE.AddDat(V)+=1; }
if (E.IsVoteE()) { VoteE.AddDat(V)+=1; }
if (E.IsVoteTalkE()) { VtTkE.AddDat(V)+=1; }
}
VoteE.SortByKey(); TalkE.SortByKey(); AllE.SortByKey(); VtTkE.SortByKey();
printf("Edge\tAll\tTalk\tVote\tVoteTalk\n");
for (int e = 0; e < AllE.Len(); e++) {
const int v = AllE.GetKey(e);
printf("%4d\t%7d\t%7d\t%7d\t%7d\n", v, AllE[e], TalkE.IsKey(v)?TalkE.GetDat(v):0,
VoteE.IsKey(v)?VoteE.GetDat(v):0, VtTkE.IsKey(v)?VtTkE.GetDat(v):0);
}
printf("\n");
}
void TWikiTalkNet::ClearElecData() {
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
EI().VoteSign = -1;
EI().VoteTm = TSecTm();
}
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
NI().Admin = false;
NI().ElecTm = TSecTm();
}
}
void TWikiTalkNet::ImposeElecNet(const TWikiElecBs& ElecBs, const THash<TChA, TChA>& UsrChageH, const bool& AddVoteOnlyEdges) {
int GoodEl=0, ESet=0, ESkip=0, GoodVotes=0, AllCmts=0, VoteEdge=0;
int DstNf=0, SrcNf=0;
for (int e = 0; e < ElecBs.Len(); e++) {
const TWikiElec& E = ElecBs[e];
TChA DstUsr = ElecBs.GetUsr(E.GetUId()); DstUsr.ToLc();
if (UsrChageH.IsKey(DstUsr)) { DstUsr = UsrChageH.GetDat(DstUsr); }
if (! UsrNIdH.IsKey(DstUsr)) { DstNf++; continue; }
GoodEl++;
TWikiElec Votes;
E.GetOnlyVotes(Votes, false);
AllCmts += E.Len();
GoodVotes += Votes.Len();
for (int v = 0; v < Votes.Len(); v++) {
TChA SrcUsr = ElecBs.GetUsr(E.GetVote(v).GetUId()); SrcUsr.ToLc();
if (UsrChageH.IsKey(SrcUsr)) { SrcUsr = UsrChageH.GetDat(SrcUsr); }
if (! UsrNIdH.IsKey(SrcUsr)) { SrcNf++; continue; }
const int SrcId = UsrNIdH.GetDat(SrcUsr);
const int DstId = UsrNIdH.GetDat(DstUsr);
if (SrcId==DstId) { continue; }
if (IsEdge(SrcId, DstId)) {
//IAssert(! GetEDat(SrcId, DstId).VoteTm.IsDef());
//IAssert(GetEDat(SrcId, DstId).GetTalks() > 0);
GetEDat(SrcId, DstId).VoteSign = E.GetVote(v).GetVote();
GetEDat(SrcId, DstId).VoteTm = E.GetVote(v).GetTm();
ESet++;
}
else if (AddVoteOnlyEdges) {
AddEdge(SrcId, DstId);
TWikiTalkEdge& EdgeDat = GetEDat(SrcId, DstId);
EdgeDat.VoteSign = E[v].GetVote();
EdgeDat.VoteTm = E[v].GetTm();
VoteEdge++;
}
else { ESkip++; }
}
}
printf("admins that talk (good elections): %d / %d\n", GoodEl, ElecBs.Len());
printf("actual votes vs. comments in elections: %d / %d : %f\n", GoodVotes, AllCmts, GoodVotes/double(AllCmts));
printf("votes where both users talk %d (%f of votes where nodes exist)\n", ESet, ESet/double(ESet+ESkip));
printf("fraction of all votes found in the graph: %d/%d : %f\n", ESet, GoodVotes, ESet/double(GoodVotes));
printf("destination not found: %d\n", DstNf);
printf("source not found: %d\n", SrcNf);
printf("talk+vote: %d vote: %d skip: %d\n", ESet, VoteEdge, ESkip);
}
PWikiTalkNet TWikiTalkNet::LoadTalkNet(const TStr& ParsedWikiDir, const TWikiElecBs& ElecBs) {
// data files
const TStr WikiUsrTalk = "enwiki-20080103.user_talk.7z"; // talk network
const TStr WikiMain = "enwiki-20080103.main.7z";
const TStr WikiMainTalk = "enwiki-20080103.talk.7z";
const TStr WikiWiki = "enwiki-20080103.wikipedia.7z";
const TStr WikiWikiTalk = "enwiki-20080103.wikipedia_talk.7z";
// misc files
const TStr BarnStartList = "barnstars.history.unsorted";
const TStr AdminList = "enwiki.admins2009.txt";
const TStr BotList = "enwiki.botlist.2007-03";
const TStr UsrChanges = "enwiki.important-username-changes.2007-08-06.txt";
// load bot list (skip bots) and username change list
THash<TChA, TChA> UsrMapH;
THashSet<TChA> BotSet;
THash<TChA, TInt> UsrElecId; // users that went up for election
TChA Ln;
TExeTm ExeTm;
for (TFIn FIn(ParsedWikiDir+BotList); FIn.GetNextLn(Ln); ) {
BotSet.AddKey(Ln.ToLc()); }
printf("Bots: %d bots\n", BotSet.Len());
for (TSsParser Ss(ParsedWikiDir+UsrChanges, ssfSpaceSep); Ss.Next(); ) {
TChA U1=Ss[0], U2=Ss[1]; if (U1.ToLc()!=U2.ToLc()) { UsrMapH.AddDat(U1,U2); }
}
printf("User changes: %d chages\n", UsrMapH.Len());
for (int e = 0; e < ElecBs.Len(); e++) {
UsrElecId.AddDat(ElecBs.GetUsr(ElecBs[e].GetUId()), e); }
printf("Elections: %d users up for election\n", UsrElecId.Len());
// create network
printf("Load WikiTalk network:");
PWikiTalkNet Net = TWikiTalkNet::New();
printf(" Load %s ", WikiUsrTalk.CStr());
{ TWikiMetaLoader WML(ParsedWikiDir+WikiUsrTalk);
int src, dst, k, elecSet=0;
for (int edges=0; WML.Next(); edges++) {
if (! WML.Title.IsPrefix("User_talk:")) { printf("."); continue; }
const int b = (int) strlen("User_talk:");
int e2 = WML.Title.SearchCh('/', b)-1;
if (e2<0) { e2=TInt::Mx; }
TChA Dst = WML.Title.GetSubStr(b, e2).ToLc();
TChA Src = WML.Usr.ToLc();
if (BotSet.IsKey(Src) || BotSet.IsKey(Dst)) { printf(""); continue; }
if (TWikiMetaLoader::IsIpAddr(Src) || TWikiMetaLoader::IsIpAddr(Dst)) { printf(""); continue; }
if (Src != Dst) { // skip self edges
k = UsrMapH.GetKeyId(Src);
if (k != -1) { Src = UsrMapH[k]; }
k = UsrMapH.GetKeyId(Dst);
if (k != -1) { Dst = UsrMapH[k]; }
src = Net->UsrNIdH.AddDatId(Src);
dst = Net->UsrNIdH.AddDatId(Dst);
IAssert(src != dst);
if (! Net->IsNode(src)) {
Net->AddNode(src, TWikiUsr(Src));
if (UsrElecId.IsKey(Src)) { printf("T"); elecSet++; // set election time
Net->GetNDat(src).ElecTm = ElecBs.GetElec(UsrElecId.GetDat(Src)).GetTm(); }
}
if (! Net->IsNode(dst)) {
Net->AddNode(dst, TWikiUsr(Dst));
if (UsrElecId.IsKey(Dst)) { printf("T"); elecSet++; // set election time
Net->GetNDat(dst).ElecTm = ElecBs.GetElec(UsrElecId.GetDat(Dst)).GetTm(); }
}
if (! Net->IsEdge(src, dst)) {
Net->AddEdge(src, dst, TWikiTalkEdge(WML.RevTm, WML.RevTm, 1, WML.RevWrds));
}
TWikiTalkEdge& TalkEdge = Net->GetEDat(src, dst);
if (TalkEdge.FirstTalk > WML.RevTm) { TalkEdge.FirstTalk = WML.RevTm; }
if (TalkEdge.LastTalk < WML.RevTm) { TalkEdge.LastTalk = WML.RevTm; }
TalkEdge.TotWords += WML.RevWrds;
TalkEdge.TotTalks += 1;
const TSecTm DstElecTm = Net->GetNDat(dst).ElecTm;
if (DstElecTm.IsDef()) { // talks before/after the election
if (WML.RevTm < DstElecTm) { TalkEdge.TalksBE++; TalkEdge.WordsBE+=WML.RevWrds; }
else { TalkEdge.TalksAE++; TalkEdge.WordsAE+=WML.RevWrds; }
}
}
}
printf("DONE NET[%s]\n", ExeTm.GetStr()); ExeTm.Tick();
printf("node election time %d / %d (%f)\n", elecSet, UsrElecId.Len(), elecSet/double(UsrElecId.Len())); }
TSnap::PrintInfo(Net, "WikiUserTalk network.");
// load barnstarts
printf(" [%s]\n Loading %s\n", ExeTm.GetStr(), BarnStartList.CStr()); ExeTm.Tick();
int cnt=0, cnt2=0;
for (TSsParser Ss(ParsedWikiDir+BarnStartList, ssfSpaceSep); Ss.Next(); cnt2++) { TChA U1=Ss[3]; U1.ToLc();
if (UsrMapH.IsKey(U1)) { U1 = UsrMapH.GetDat(U1); }
if (Net->UsrNIdH.IsKey(U1)) { cnt++;
Net->GetNDat(Net->UsrNIdH.GetDat(U1)).BarnStars += 1; }
}
printf(" %d / %d stars set [%s]\n Loading %s\n", cnt, cnt2, ExeTm.GetStr(), AdminList.CStr()); ExeTm.Tick();
// load admins
cnt=0; cnt2=0;
for (TFIn FIn(ParsedWikiDir+AdminList); FIn.GetNextLn(Ln); cnt2++) { Ln.ToLc();
if (UsrMapH.IsKey(Ln)) { Ln = UsrMapH.GetDat(Ln); }
if (Net->UsrNIdH.IsKey(Ln)) { cnt++;
Net->GetNDat(Net->UsrNIdH.GetDat(Ln)).Admin = true; }
}//*/
printf(" %d / %d admins set [%s]\n", cnt, cnt2, ExeTm.GetStr());
TIntSet AdminSet; ElecBs.GetAdminSet(AdminSet);
for (int a = 0; a < AdminSet.Len(); a++, cnt2++) {
TChA Ln = ElecBs.GetUsr(AdminSet[a]);
if (Net->UsrNIdH.IsKey(Ln)) { cnt++;
Net->GetNDat(Net->UsrNIdH.GetDat(Ln)).Admin = true; }
}
printf(" %d / %d admins set [%s]\n", cnt, cnt2, ExeTm.GetStr());
// impose election net
Net->ImposeElecNet(ElecBs, UsrMapH, true); // add also vote only edges
TSnap::PrintInfo(Net);
//Net->Save(TFOut("tmp.net"));
printf("SAVE DONE.\n\nLoading user edit statistics:\n");
//// load user stat
//TInt MnEdCnt, MnEdWrds; // number of edits, changed words (in main namespace)
printf(" Loading %s ", WikiMain.CStr());
{ TWikiMetaLoader WML(ParsedWikiDir+WikiMain);
for (int rec=0; WML.Next(); rec++) {
const TChA& U = WML.Usr;
const int keyId = Net->UsrNIdH.GetKeyId(U);
if (keyId == -1) { continue; }
TWikiUsr& WU = Net->GetNDat(Net->UsrNIdH[keyId]);
WU.MnEdCnt += 1; WU.MnEdWrds += WML.RevWrds;
WML.CommentStr.ToLc();
if (WML.CommentStr.IsPrefix("rv") || WML.CommentStr.SearchStr("revert")!=-1) {
WU.MnRevCnt+=1; WU.MnRevWrds+=WML.RevWrds; }
} }
//TInt MnTkEdCnt, MnTkEdWrds; // number of edits, changed words (in talk pages of main namespace)
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiMainTalk.CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(ParsedWikiDir+WikiMainTalk);
for (int rec=0; WML.Next(); rec++) {
const TChA& U = WML.Usr.ToLc();
const int keyId = Net->UsrNIdH.GetKeyId(U);
if (keyId == -1) { continue; }
TWikiUsr& WU = Net->GetNDat(Net->UsrNIdH[keyId]);
WU.MnTkEdCnt += 1; WU.MnTkEdWrds += WML.RevWrds;
} }
//TInt WkEdCnt, WkEdWrds; // number of edits, changed words (in wikipedia namespace)
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiWiki.CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(ParsedWikiDir+WikiWiki);
for (int rec=0; WML.Next(); rec++) {
const TChA& U = WML.Usr.ToLc();
const int keyId = Net->UsrNIdH.GetKeyId(U);
if (keyId == -1) { continue; }
TWikiUsr& WU = Net->GetNDat(Net->UsrNIdH[keyId]);
WU.WkEdCnt += 1; WU.WkEdWrds += WML.RevWrds;
} }
//TInt WkTkEdCnt, WkTkEdWrds; // number of edits, changed words (in talk pages of wikipedia namespace)
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiWikiTalk.CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(ParsedWikiDir+WikiWikiTalk);
for (int rec=0; WML.Next(); rec++) {
const TChA& U = WML.Usr.ToLc();
const int keyId = Net->UsrNIdH.GetKeyId(U);
if (keyId == -1) { continue; }
TWikiUsr& WU = Net->GetNDat(Net->UsrNIdH[keyId]);
WU.WkTkEdCnt += 1; WU.WkTkEdWrds += WML.RevWrds;
} }
TSnap::PrintInfo(Net, "WikiUserTalk network.");
printf("\n[%s]\nDONE.\n", ExeTm.GetStr());
// done */
return Net;
}
PWikiTalkNet TWikiTalkNet::LoadSlashdot(const TStr& InFNm) {
THashSet<TChA> NIdSet;
TChA LnStr;
TVec<char *> WrdV;
int Sign;
PWikiTalkNet Net = TWikiTalkNet::New();
for (TFIn FIn(InFNm); FIn.GetNextLn(LnStr); ) {
if (LnStr.Empty() || LnStr[0]=='#') { continue; }
LnStr.ToLc();
TStrUtil::SplitOnCh(LnStr, WrdV, '\t', false);
NIdSet.AddKey(WrdV[0]);
if (strcmp(WrdV[1], "friends")==0) { Sign = 1; }
else if (strcmp(WrdV[1], "fans")==0) { continue; } // skip
else if (strcmp(WrdV[1], "foes")==0) { Sign = -1; }
else { Fail; }
const int SrcNId = NIdSet.AddKey(WrdV[0]);
if (! Net->IsNode(SrcNId)) {
Net->AddNode(SrcNId, TWikiUsr(WrdV[0]));
Net->UsrNIdH.AddDat(WrdV[0], SrcNId);
}
for (int e = 2; e < WrdV.Len(); e++) {
const int DstNId = NIdSet.AddKey(WrdV[e]);
if (! Net->IsNode(DstNId)) {
Net->AddNode(DstNId, TWikiUsr(WrdV[e]));
Net->UsrNIdH.AddDat(WrdV[e], DstNId);
}
if (SrcNId != DstNId && ! Net->IsEdge(SrcNId, DstNId)) {
Net->AddEdge(SrcNId, DstNId, TWikiTalkEdge(Sign));
}
}
}
TSnap::PrintInfo(Net, InFNm);
return Net;
}
// Load: class TWikiVoteNet : public TNodeEDatNet<TStr, TInt>
PWikiTalkNet TWikiTalkNet::LoadOldNet(const TStr& InFNm) {
typedef TNodeEDatNet<TStr, TInt> TOldNet;
PWikiTalkNet Net = TWikiTalkNet::New();
TPt<TOldNet> ON = TOldNet::Load(TZipIn(InFNm));
TSnap::PrintInfo(ON);
for(TOldNet::TEdgeI EI = ON->BegEI(); EI<ON->EndEI(); EI++) {
if (! Net->IsNode(EI.GetSrcNId())) {
Net->AddNode(EI.GetSrcNId(), TWikiUsr(EI.GetSrcNDat().GetLc()));
Net->UsrNIdH.AddDat(EI.GetDstNDat().GetLc(), EI.GetSrcNId());
}
if (! Net->IsNode(EI.GetDstNId())) {
Net->AddNode(EI.GetDstNId(), TWikiUsr(EI.GetDstNDat().GetLc()));
Net->UsrNIdH.AddDat(EI.GetDstNDat().GetLc(), EI.GetDstNId());
}
Net->AddEdge(EI.GetSrcNId(), EI.GetDstNId(), TWikiTalkEdge(EI()));
}
TSnap::PrintInfo(Net);
return Net;
}
/////////////////////////////////////////////////
// Wikipedia Talk net over time
PNGraph TWikiTimeTalkNet::GetBeforeTimeG(const TSecTm& EdgeTm) const {
PNGraph G = TNGraph::New();
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI().Tm <= EdgeTm) {
if (! G->IsNode(EI.GetSrcNId())) { G->AddNode(EI.GetSrcNId()); }
if (! G->IsNode(EI.GetDstNId())) { G->AddNode(EI.GetDstNId()); }
G->AddEdge(EI.GetSrcNId(), EI.GetDstNId());
}
}
return G;
}
PSignNet TWikiTimeTalkNet::GetBeforeTimeNet(const TSecTm& EdgeTm) const {
PSignNet Net = TSignNet::New();
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI().Tm <= EdgeTm) {
if (! Net->IsNode(EI.GetSrcNId())) { Net->AddNode(EI.GetSrcNId()); }
if (! Net->IsNode(EI.GetDstNId())) { Net->AddNode(EI.GetDstNId()); }
Net->AddEdge(EI.GetSrcNId(), EI.GetDstNId());
Net->GetEDat(EI.GetSrcNId(), EI.GetDstNId()) += EI().Words;
}
}
return Net;
}
void TWikiTimeTalkNet::SaveDataset(const TWikiElecBs& ElecBs, const TStr& OutFNm) const {
FILE *F = fopen(OutFNm.CStr(), "wt");
fprintf(F, "SuccElec\tRfa\tNetNodes\tNetEdges\tNetConstraint\tBarnStars\tTalkOutDeg\tTalkInDeg\tTalkTriads\tInWords\tOutWords\tInAdmins\tOutAdmins\tAdminTriads\tInAdminWords\tOutAdminWords\n");
// load admin list
TStrSet AdminSet;
for (TSsParser Ss("W:\\Data\\wiki20080103-parseByGuerogy\\enwiki.admins2009.txt", ssfTabSep); Ss.Next(); ) {
TStr A=Ss[0]; AdminSet.AddKey(A.GetTrunc().GetLc());
}
TExeTm ExeTm;
TBarnStars BarnStars;
TIntSet AdminNIdSet;
printf("Admin list: %d\n", AdminSet.Len());
for (int e = 0; e < ElecBs.Len(); e++) {
const TWikiElec& E = ElecBs.GetElec(e);
const TStr Usr = ElecBs.GetUsr(E.UsrId);
printf("%s: %s ", Usr.CStr(), E.RfaTitle.CStr());
if (! UsrNIdH.IsKey(Usr)) {
printf(" DOES NOT TALK\n", Usr.CStr()); continue;
}
PSignNet Net = GetBeforeTimeNet(E.ElecTm);
const int NId = UsrNIdH.GetDat(Usr);
if (! Net->IsNode(NId)) {
printf(" TALKS AFTER ELECTION\n"); continue;
}
const TSignNet::TNodeI NI = Net->GetNI(NId);
printf(" deg %d:%d ", NI.GetInDeg(), NI.GetOutDeg());
int InWgt=0, OutWgt=0, InAdmins=0, OutAdmins=0, InAWgt=0, OutAWgt=0;
AdminNIdSet.Clr(false);
AdminNIdSet.AddKey(NI.GetId());
for (int i = 0; i < NI.GetOutDeg(); i++) {
OutWgt += NI.GetOutEDat(i);
if (AdminSet.IsKey(UsrNIdH.GetKey(NI.GetOutNId(i)))) {
OutAWgt += NI.GetOutEDat(i);
OutAdmins++;
AdminNIdSet.AddKey(NI.GetOutNId(e));
}
}
for (int i = 0; i < NI.GetInDeg(); i++) {
InWgt += NI.GetInEDat(i);
if (AdminSet.IsKey(UsrNIdH.GetKey(NI.GetInNId(i)))) {
InAWgt += NI.GetInEDat(i);
InAdmins++;
AdminNIdSet.AddKey(NI.GetInNId(e));
}
}
TSnap::TNetConstraint<PSignNet> NetC(Net, false);
NetC.CalcConstraints(NId);
TIntV AdminV; AdminNIdSet.GetKeyV(AdminV);
const double C = NetC.GetNodeC(NId);
const int BS = BarnStars.GetBarnStars(Usr, E.GetTm());
const int Triads = TSnap::GetNodeTriads(Net, NI.GetId());
const int AdmintTriads = TSnap::GetNodeTriads(TSnap::GetSubGraph(Net, AdminV), NI.GetId());
fprintf(F, "%d\t%s\t%d\t%d\t%f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", E.IsSucc?1:0, E.RfaTitle.CStr(), Net->GetNodes(), Net->GetEdges(), C, BS,
NI.GetOutDeg(), NI.GetInDeg(), Triads, InWgt, OutWgt, InAdmins, OutAdmins, AdmintTriads, InAWgt, OutAWgt);
fflush(F);
printf(" [%s]\n", ExeTm.GetStr());
}
fclose(F);
}
PWikiTimeTalkNet TWikiTimeTalkNet::LoadWikiTimeTalkNet() {
const TStr WikiUsrTalk = "W:\\data\\wiki20080103-parseByGuerogy\\enwiki-20080103.user_talk.7z"; // talk network
const TStr UsrChanges = "W:\\data\\wiki20080103-parseByGuerogy\\enwiki.important-username-changes.2007-08-06";
const TStr BotList = "W:\\data\\wiki20080103-parseByGuerogy\\enwiki.botlist.2007-03";
// load bot list (skip bots) and username change list
THash<TChA, TChA> UsrMapH;
THashSet<TChA> BotSet;
TChA Ln;
TExeTm ExeTm;
for (TFIn FIn(BotList); FIn.GetNextLn(Ln); ) {
BotSet.AddKey(Ln.ToLc()); }
printf("Bots: %d bots\n", BotSet.Len());
for (TSsParser Ss(UsrChanges, ssfSpaceSep); Ss.Next(); ) {
TChA U1=Ss[3], U2=Ss[4]; if (U1.ToLc()!=U2.ToLc()) { UsrMapH.AddDat(U1,U2); } }
printf("User changes: %d chages\n", UsrMapH.Len());
// create network
printf("Load Take network before the election:");
PWikiTimeTalkNet Net = TWikiTimeTalkNet::New();
printf(" Load %s ", WikiUsrTalk.CStr());
TWikiMetaLoader WML(WikiUsrTalk);
int src, dst, k;
for (int edges=0; WML.Next(); edges++) {
if (! WML.Title.IsPrefix("User_talk:")) { printf("."); continue; }
const int b = (int) strlen("User_talk:");
int e2 = WML.Title.SearchCh('/', b)-1;
if (e2<0) { e2=TInt::Mx; }
TChA Dst = WML.Title.GetSubStr(b, e2).ToLc();
TChA Src = WML.Usr.ToLc();
if (BotSet.IsKey(Src) || BotSet.IsKey(Dst)) { printf(""); continue; }
if (TWikiMetaLoader::IsIpAddr(Src) || TWikiMetaLoader::IsIpAddr(Dst)) { printf(""); continue; }
if (Src != Dst) { // skip self edges
k = UsrMapH.GetKeyId(Src);
if (k != -1) { Src = UsrMapH[k]; }
k = UsrMapH.GetKeyId(Dst);
if (k != -1) { Dst = UsrMapH[k]; }
src = Net->UsrNIdH.AddDatId(Src);
dst = Net->UsrNIdH.AddDatId(Dst);
if (src != dst) {
if (! Net->IsNode(src)) { Net->AddNode(src, Src); }
if (! Net->IsNode(dst)) { Net->AddNode(dst, Dst); }
Net->AddEdge(src, dst, -1, TWikiTalkEdge2(WML.RevTm, WML.RevWrds));
}
}
}
printf("DONE NET[%s]\n", ExeTm.GetStr()); ExeTm.Tick();
return Net;
}
/////////////////////////////////////////////////
// Wikipedia Edit Counts
// load edit counts before the user went up for election
void TWikiEditCnt::LoadTxtBeforeElec(const TWikiElecBs& ElecBs) {
const TStr WikiMain = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.main.7z";
const TStr WikiMainTalk = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.talk.7z";
const TStr WikiWiki = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.wikipedia.7z";
const TStr WikiWikiTalk = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.wikipedia_talk.7z";
const TStr UsrChanges = "W:\\data\\wiki20080103-parseByGuerogy\\enwiki.important-username-changes.2007-08-06";
THash<TChA, TChA> UsrMapH;
for (TSsParser Ss(UsrChanges, ssfSpaceSep); Ss.Next(); ) {
TChA U1=Ss[3], U2=Ss[4]; if (U1.ToLc()!=U2.ToLc()) { UsrMapH.AddDat(U1,U2); } }
// Load only statistics for users going up for election
THash<TChA, TVec<TPair<TChA, TSecTm> > > UsrToRfaTmH;
for (int e = 0; e < ElecBs.Len(); e++) {
UsrToRfaTmH.AddDat(ElecBs.GetUsr(ElecBs[e].GetUId())).Add(TPair<TChA, TSecTm>(ElecBs[e].RfaTitle, ElecBs[e].GetTm()));
}
TExeTm ExeTm;
//// load user stat
printf(" Loading %s ", WikiMain.GetFMid().CStr());
{ TWikiMetaLoader WML(WikiMain);
for (int rec=0; WML.Next(); rec++) {
TChA U = WML.Usr;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
if (! UsrToRfaTmH.IsKey(U)) { continue; }
const TVec<TPair<TChA, TSecTm> >& V = UsrToRfaTmH.GetDat(U);
for (int t = 0; t < V.Len(); t++) {
if (WML.RevTm <= V[t].Val2 ) { // edits only before the election
TEditCnt& EC = RfaEdCntH.AddDat(V[t].Val1);
EC.MainE+=1; EC.MainW+=WML.RevWrds;
WML.CommentStr.ToLc();
if (WML.CommentStr.IsPrefix("rv") || WML.CommentStr.SearchStr("revert")!=-1) {
EC.RevE+=1; EC.RevW+=WML.RevWrds;
}
}
}
} }
Save(TZipOut("wikiEditCounts.BeforeElec.rar"));
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiMainTalk.GetFMid().CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(WikiMainTalk);
for (int rec=0; WML.Next(); rec++) {
TChA U = WML.Usr;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
if (! UsrToRfaTmH.IsKey(U)) { continue; }
const TVec<TPair<TChA, TSecTm> >& V = UsrToRfaTmH.GetDat(U);
for (int t = 0; t < V.Len(); t++) {
if (WML.RevTm <= V[t].Val2 ) {
TEditCnt& EC = RfaEdCntH.AddDat(V[t].Val1);
EC.MainTE+=1; EC.MainTW+=WML.RevWrds;
}
}
} }
Save(TZipOut("wikiEditCounts.BeforeElec.rar"));
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiWiki.GetFMid().CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(WikiWiki);
for (int rec=0; WML.Next(); rec++) {
TChA U = WML.Usr;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
if (! UsrToRfaTmH.IsKey(U)) { continue; }
const TVec<TPair<TChA, TSecTm> >& V = UsrToRfaTmH.GetDat(U);
for (int t = 0; t < V.Len(); t++) {
if (WML.RevTm <= V[t].Val2 ) {
TEditCnt& EC = RfaEdCntH.AddDat(V[t].Val1);
EC.WikiE+=1; EC.WikiW+=WML.RevWrds;
}
}
} }
Save(TZipOut("wikiEditCounts.BeforeElec.rar"));
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiWikiTalk.GetFMid().CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(WikiWikiTalk);
for (int rec=0; WML.Next(); rec++) {
TChA U = WML.Usr;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
if (! UsrToRfaTmH.IsKey(U)) { continue; }
const TVec<TPair<TChA, TSecTm> >& V = UsrToRfaTmH.GetDat(U);
for (int t = 0; t < V.Len(); t++) {
if (WML.RevTm <= V[t].Val2 ) {
TEditCnt& EC = RfaEdCntH.AddDat(V[t].Val1);
EC.WikiTE+=1; EC.WikiTW+=WML.RevWrds;
}
}
} }
Save(TZipOut("wikiEditCounts.BeforeElec.rar"));
printf(" [%s]\n", ExeTm.GetStr());
}
// edit counts of all users that ever casted a vote
void TWikiEditCnt::LoadTxtAll(const TWikiElecBs& ElecBs) {
const TStr WikiMain = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.main.7z";
const TStr WikiMainTalk = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.talk.7z";
const TStr WikiWiki = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.wikipedia.7z";
const TStr WikiWikiTalk = "W:\\Data\\wiki20080103-parseByGuerogy\\enwiki-20080103.wikipedia_talk.7z";
const TStr UsrChanges = "W:\\data\\wiki20080103-parseByGuerogy\\enwiki.important-username-changes.2007-08-06";
TExeTm ExeTm;
//// load user stat
printf(" Loading %s ", WikiMain.GetFMid().CStr());
{ TWikiMetaLoader WML(WikiMain);
for (int rec=0; WML.Next(); rec++) {
if (! ElecBs.IsUsr(WML.Usr)) { continue; }
TEditCnt& EC = RfaEdCntH.AddDat(WML.Usr);
EC.MainE+=1; EC.MainW+=WML.RevWrds;
WML.CommentStr.ToLc();
if (WML.CommentStr.IsPrefix("rv") || WML.CommentStr.SearchStr("revert")!=-1) {
EC.RevE+=1; EC.RevW+=WML.RevWrds;
}
} }
Save(TZipOut("wikiEditCounts.All.rar"));
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiMainTalk.GetFMid().CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(WikiMainTalk);
for (int rec=0; WML.Next(); rec++) {
if (! ElecBs.IsUsr(WML.Usr)) { continue; }
TEditCnt& EC = RfaEdCntH.AddDat(WML.Usr);
EC.MainTE+=1; EC.MainTW+=WML.RevWrds;
} }
Save(TZipOut("wikiEditCounts.All.rar"));
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiWiki.GetFMid().CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(WikiWiki);
for (int rec=0; WML.Next(); rec++) {
TChA U = WML.Usr;
if (! ElecBs.IsUsr(WML.Usr)) { continue; }
TEditCnt& EC = RfaEdCntH.AddDat(WML.Usr);
EC.WikiE+=1; EC.WikiW+=WML.RevWrds;
} }
Save(TZipOut("wikiEditCounts.All.rar"));
printf(" [%s]\n Loading %s", ExeTm.GetStr(), WikiWikiTalk.GetFMid().CStr()); ExeTm.Tick();
{ TWikiMetaLoader WML(WikiWikiTalk);
for (int rec=0; WML.Next(); rec++) {
if (! ElecBs.IsUsr(WML.Usr)) { continue; }
TEditCnt& EC = RfaEdCntH.AddDat(WML.Usr);
EC.WikiTE+=1; EC.WikiTW+=WML.RevWrds;
} }
Save(TZipOut("wikiEditCounts.All.rar"));
printf(" [%s]\n", ExeTm.GetStr());
}
void TWikiEditCnt::SaveTxt(const TWikiElecBs& ElecBs, const TStr& OutFNm) {
FILE *F = fopen(OutFNm.CStr(), "wt");
fprintf(F, "Rfat\tMainE\tMainW\tMainTE\tMainTW\tWikiE\tWikiW\tWikiTE\tWikiTW\n");
//for (int e = 0; e < ElecBs.Len(); e++) {
for (TSsParser Ss("isSuccVote-TalkNet3.tab", ssfTabSep); Ss.Next(); ) {
//TStr Rfa = ElecBs[e].RfaTitle;
TStr Rfa = Ss[1];
if (! RfaEdCntH.IsKey(Rfa)) {
printf("%s\n", Rfa.CStr());
fprintf(F, "%s\t0\t0\t0\t0\t0\t0\t0\t0\n", Rfa.CStr());
} else {
const TEditCnt& EC = RfaEdCntH.GetDat(Rfa);
fprintf(F, "%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", Rfa.CStr(),
EC.MainE(), EC.MainW(), EC.MainTE(), EC.MainTW(), EC.WikiE(), EC.WikiW(), EC.WikiTE(), EC.WikiTW());
}
}
fclose(F);
}
/////////////////////////////////////////////////
// Wikipedia Election
TWikiElec::TWikiElec(TSIn& SIn) : RfaTitle(SIn), UsrId(SIn), NomUId(SIn), BurUId(SIn), IsSucc(SIn), ElecTm(SIn), VoteV(SIn) {
}
void TWikiElec::Save(TSOut& SOut) const {
RfaTitle.Save(SOut); UsrId.Save(SOut); NomUId.Save(SOut);
BurUId.Save(SOut); IsSucc.Save(SOut); ElecTm.Save(SOut);
VoteV.Save(SOut);
}
bool TWikiElec::operator < (const TWikiElec& WE) const {
return ElecTm<WE.ElecTm || (ElecTm==WE.ElecTm && UsrId<WE.UsrId);
}
// determine whether an item is a comment or actual vote
void TWikiElec::SetIsVoteFlag() {
THash<TInt, TIntPr> UsrVoteH(Len());
for (int i = 0; i < VoteV.Len(); i++) {
if (VoteV[i].GetIndent() != 0) { continue; } // only take vote at indent 0
if (VoteV[i].GetUId() == UsrId) { continue; } // skip self votes
if (! UsrVoteH.IsKey(VoteV[i].GetUId())) {
UsrVoteH.AddDat(VoteV[i].GetUId(), TIntPr(VoteV[i].GetTm().GetAbsSecs(), i));
} else {
TIntPr& Dat = UsrVoteH.GetDat(VoteV[i].GetUId());
if (Dat.Val1 > (int)VoteV[i].GetTm().GetAbsSecs()) { // new vote accured sooner than the previous one
Dat = TIntPr(VoteV[i].GetTm().GetAbsSecs(), i);
}
}
}
// set vote flag
for (int v = 0; v < VoteV.Len(); v++) {
VoteV[v].IsAVote = false;
}
for (int v = 0; v < UsrVoteH.Len(); v++) {
VoteV[UsrVoteH[v].Val2].IsAVote = true;
}
}
double TWikiElec::GetFracSup(const bool& OnlyVotes) const {
const TIntTr Votes = GetVotes(OnlyVotes);
return double(Votes.Val1)/double(Votes.Val1+Votes.Val3);
}
double TWikiElec::GetFracSup(int VoteId1, int VoteId2) const {
double Sup=0;
for (int v = VoteId1; v < TMath::Mn(VoteId2, Len()); v++) {
if (VoteV[v].GetVote()==1) { Sup+=1; }
}
if (VoteId1==VoteId2) { return 0.0; }
return Sup/double(VoteId2-VoteId1);
}
// fit least squares line between votes Vote1 and Vote2 and return the coefficient
double TWikiElec::GetTrend(int VoteId1, int VoteId2) const {
TFltPrV XY;
for (int v = VoteId1; v < VoteId2; v++) {
XY.Add(TFltPr(v, (double)VoteV[v].GetVote()));
}
double A, B, SigA, SigB, Chi2, R2;
TSpecFunc::LinearFit(XY, A, B, SigA, SigB, Chi2, R2);
return B;
}
TIntTr TWikiElec::GetVotes(const bool& OnlyVotes) const {
int Sup=0, Opp=0, Neu=0;
for (int i = 0; i < VoteV.Len(); i++) {
if (OnlyVotes && ! VoteV[i].IsVote()) { continue; }
if (VoteV[i].GetVote()==1) { Sup++; }
else if (VoteV[i].GetVote()==0) { Neu++; }
else if (VoteV[i].GetVote()==-1) { Opp++; }
}
return TIntTr(Sup, Neu, Opp);
}
void TWikiElec::GetVotesOt(TWikiVoteV& WVoteV, const bool& OnlyVotes) const {
// also counts opinions, changes of opinion, etc
if (! OnlyVotes) {
WVoteV = VoteV;
WVoteV.Sort();
return;
}
// take the earliest vote of a user
TIntPrV TmIdV;
for (int i = 0; i < VoteV.Len(); i++) {
if (OnlyVotes && ! VoteV[i].IsVote()) { continue; }
TmIdV.Add(TIntPr(VoteV[i].VoteTm.GetAbsSecs(), i));
}
TmIdV.Sort();
WVoteV.Clr(false);
for (int v = 0; v < TmIdV.Len(); v++) {
WVoteV.Add(VoteV[TmIdV[v].Val2]);
}
WVoteV.Sort();
}
// get average vote (fraction of positive votes) over time
int TWikiElec::GetAvgVoteOt(TFltV& AvgVoteV, const bool& OnlyVotes) const {
TWikiVoteV WVoteV; GetVotesOt(WVoteV, OnlyVotes);
double VoteSum = 0;
AvgVoteV.Clr(false);
for (int i = 0; i < WVoteV.Len(); i++) {
VoteSum += WVoteV[i].GetVote() > 0 ? 1 : 0;
AvgVoteV.Add(VoteSum/double(i+1));
}
return AvgVoteV.Len();
}
// get absolute change in the average vote (fraction of positive votes) over time
int TWikiElec::GetAvgVoteDevOt(TFltV& AvgVoteV, const bool& OnlyVotes) const {
TWikiVoteV WVoteV; GetVotesOt(WVoteV, OnlyVotes);
double XBar = WVoteV[0].GetVote() > 0 ? 1 : 0;
AvgVoteV.Clr(false);
for (int i = 1; i < WVoteV.Len(); i++) {
const double CurVote = WVoteV[i].GetVote() > 0 ? 1 : 0;
AvgVoteV.Add(fabs(CurVote-XBar)/double(i+1));
XBar = (i*XBar+CurVote)/double(i+1);
}
return AvgVoteV.Len();
}
// after the v-th vote was casted, how many people voted the same
int TWikiElec::GetRunLen(const int& VoteId) const {
const int V = VoteV[VoteId].GetVote();
int runL=0;
for (int v = VoteId+1; v < Len(); v++) {
if (VoteV[v].GetVote() == V) { runL++; }
else { return runL; }
}
return runL;
}
// shuffle the order of user votes over time (users, times remain unaltered, but votes change)
void TWikiElec::PermuteVotes() {
TIntV ValV(VoteV.Len(), 0);
for (int i = 0; i < VoteV.Len(); i++) {
ValV.Add(VoteV[i].UsrVote); }
ValV.Shuffle(TInt::Rnd);
for (int i = 0; i < ValV.Len(); i++) {
VoteV[i].UsrVote=ValV[i]; }
}
void TWikiElec::KeepVotes(const TIntSet& UIdSet) {
TWikiVoteV NewVoteV;
for (int v = 0; v < VoteV.Len(); v++) {
if (UIdSet.IsKey(VoteV[v].GetUId())) {
NewVoteV.Add(VoteV[v]);
}
}
VoteV=NewVoteV;
}
void TWikiElec::GetOnlyVotes(TWikiElec& NewElec, const bool& OnlySupOpp) const {
NewElec.RfaTitle = RfaTitle;
NewElec.UsrId = UsrId;
NewElec.NomUId = NomUId;
NewElec.BurUId = BurUId;
NewElec.IsSucc = IsSucc;
NewElec.ElecTm = ElecTm;
NewElec.VoteV.Clr(false);
for (int i = 0; i < VoteV.Len(); i++) {
if (! VoteV[i].IsVote()) { continue; }
if (OnlySupOpp && VoteV[i].GetVote()==0) { continue; }
NewElec.VoteV.Add(VoteV[i]);
}
}
void TWikiElec::RemoveSelfVotes() {
TWikiVoteV VoteV2(Len(), 0);
for (int v = 0; v < VoteV.Len(); v++) {
if (VoteV[v].GetIndent()==0 && VoteV[v].GetUId()==UsrId) { continue; } // skip self votes
VoteV2.Add(VoteV[v]);
}
VoteV.Swap(VoteV2);
}
void TWikiElec::Dump(const TStrHash<TInt>& UsrH) const {
TIntTr V = GetVotes(true);
if (UsrH.IsKeyId(UsrId)) {
printf("\nELEC %s : %s %d vote at %s votes %d\n", RfaTitle.CStr(), UsrH.GetKey(UsrId), UsrId, ElecTm.GetYmdTmStr().CStr(), VoteV.Len()); }
else {
printf("\nELEC %s : %d %d vote at %s votes %d\n", RfaTitle.CStr(), UsrId, ElecTm.GetYmdTmStr().CStr(), VoteV.Len()); }
printf(" %d / %d / %d = %f\n", V.Val1, V.Val2, V.Val3, V.Val1/double(V.Val1+V.Val3));
for (int v = 0; v < VoteV.Len(); v++) {
if (UsrH.IsKeyId(VoteV[v].UsrId)) {
printf(" %2d %2d %s: %s (%d) %s t:%d i: %d\n", v+1, VoteV[v].UsrVote, VoteV[v].IsVote()?"V":" ", UsrH.GetKey(VoteV[v].UsrId), VoteV[v].UsrId, VoteV[v].VoteTm.GetYmdTmStr().CStr(), VoteV[v].TxtLen, VoteV[v].UsrIndent);
} else {
printf(" %2d %2d %s: %d %s t:%d i: %d\n", v+1, VoteV[v].UsrVote, VoteV[v].IsVote()?"V":" ", VoteV[v].UsrId, VoteV[v].VoteTm.GetYmdTmStr().CStr(), VoteV[v].TxtLen, VoteV[v].UsrIndent);
}
}
}
/////////////////////////////////////////////////
// Wikipedia Election Base
void TWikiElecBs::GetEIdByVotes(TIntV& EIdV, const bool& AscNumVotes) const {
TIntPrV V(Len(), 0);
for (int u = 0; u < Len(); u++) {
const TWikiElec& E = GetElec(u);
V.Add(TIntPr(E.Len(), E.UsrId));
}
V.Sort(AscNumVotes);
EIdV.Clr(false);
for (int u = 0; u < V.Len(); u++) {
EIdV.Add(V[u].Val2); }
}
void TWikiElecBs::GetEIdByVotes(TIntV& EIdV, const int& MinLen, const double& FracPos, const double AboveFrac, const bool& AscNumVotes) const {
TFltIntPrV V(Len(), 0);
for (int u = 0; u < Len(); u++) {
const TWikiElec& E = GetElec(u);
if (E.Len() < MinLen) { continue; }
if ((AboveFrac && E.GetFracSup() > FracPos) || (!AboveFrac && E.GetFracSup() < FracPos)) {
V.Add(TFltIntPr(E.Len(), E.UsrId)); }
}
V.Sort(AscNumVotes);
EIdV.Clr(false);
for (int u = 0; u < V.Len(); u++) {
EIdV.Add(V[u].Val2); }
}
// get elections with final fraction and minimum number of votes
void TWikiElecBs::GetEIdByFrac(TIntV& EIdV, const int& MinLen, const double& MnFracSup, const double& MxFracSup) const {
TFltIntPrV V(Len(), 0);
for (int u = 0; u < Len(); u++) {
const TWikiElec& E = GetElec(u);
if (E.Len() < MinLen) { continue; }
const double FracSup = E.GetFracSup();
if (FracSup==1) { continue; }
if (FracSup >= MnFracSup && FracSup <= MxFracSup) {
V.Add(TFltIntPr(FracSup, E.UsrId)); }
}
V.Sort(true);
EIdV.Clr(false);
for (int u = 0; u < V.Len(); u++) {
EIdV.Add(V[u].Val2); }
}
void TWikiElecBs::GetUsrV(TIntV& UIdV) const {
TIntSet UIdSet;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
UIdSet.AddKey(E.GetUId());
for (int v = 0; v < E.Len(); v++) {
UIdSet.AddKey(E.GetVote(v).GetUId());
}
}
UIdSet.GetKeyV(UIdV);
}
// users that went up for election
void TWikiElecBs::GetElecUsrV(TIntV& ElecUsrV) const {
ElecUsrV.Clr(false);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
ElecUsrV.Add(E.UsrId);
}
}
// users that got elected (promoted into adminship)
void TWikiElecBs::GetElecAdminUsrV(TIntV& ElecAdminUsrV) const {
ElecAdminUsrV.Clr(false);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.IsSucc) {
ElecAdminUsrV.Add(E.UsrId);
}
}
}
// users that did not get promoted
void TWikiElecBs::GetElecNonAdminUsrV(TIntV& ElecNonAdminUsrV) const {
ElecNonAdminUsrV.Clr(false);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (! E.IsSucc) {
ElecNonAdminUsrV.Add(E.UsrId);
}
}
}
// get users that are frequent votes
// MinVotes=25 gives 1k users
// MinVotes=50 gives 500 users
// MinVotes=100 gives 241 users
void TWikiElecBs::GetFqVoters(TIntSet& FqVoterSet, const int& MinVotes, const int& MinElecLen, const bool& OnlyAdmins) const {
TIntH UsrCntH, CntH;
printf("%d\n", Len());
TIntSet AdminSet;
if (OnlyAdmins) {
GetAdminSet(AdminSet);
}
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinElecLen) { continue; }
for (int v = 0; v < E.Len(); v++) {
if (OnlyAdmins && ! AdminSet.IsKey(E[v].GetUId())) {
continue; } // skip non admins
UsrCntH.AddDat(E[v].GetUId()) += 1;
}
}
for (int i = 0; i < UsrCntH.Len(); i++) {
CntH.AddDat(UsrCntH[i]) += 1; }
//TGnuPlot::PlotValCntH(CntH, "votesPerUser-wiki", "", "votes per user (elections user participated in)", "count");
FqVoterSet.Clr(false);
UsrCntH.SortByDat(false);
for (int i = 0; i < UsrCntH.Len(); i++) {
if (UsrCntH[i] >= MinVotes) {
FqVoterSet.AddKey(UsrCntH.GetKey(i));
}
}
}
void TWikiElecBs::GetUsrVotes(TIntPrV& VoteUIdV) const {
TIntH UsrCntH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
for (int v = 0; v < E.Len(); v++) {
UsrCntH.AddDat(E[v].GetUId()) += 1;
}
}
VoteUIdV.Clr();
for (int i = 0; i < UsrCntH.Len(); i++) {
VoteUIdV.Add(TIntPr(UsrCntH[i], UsrCntH.GetKey(i)));
}
VoteUIdV.Sort(false);
}
void TWikiElecBs::GetAdminSet(TIntSet& AdminSet) const {
AdminSet.Clr(false);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.IsSucc) {
AdminSet.AddKey(E.UsrId);
}
}
printf(" %d admins from elecs. ", AdminSet.Len());
if (TFile::Exists("../../admin-list.txt")) {
for (TSsParser Ss("../../admin-list.txt", ssfTabSep); Ss.Next(); ) {
TStr U = Ss[0];
if (IsUsr(U)) { AdminSet.AddKey(GetUId(U)); }
if(IsUsr(U.GetLc())) { AdminSet.AddKey(GetUId(U.GetLc())); }
}
}
printf(" %d admins after admin-list.txt\n", AdminSet.Len());
}
void TWikiElecBs::GetFqVoterSet(TIntSet& FqVoterSet) const {
TIntPrV VoteUIdV;
GetUsrVotes(VoteUIdV);
int HalfVotes = GetVotes()/2, SoFar=0;
FqVoterSet.Clr(false);
for (int i = 0; i < VoteUIdV.Len() && SoFar < HalfVotes; i++) {
FqVoterSet.AddKey(VoteUIdV[i].Val2);
SoFar+=VoteUIdV[i].Val1;
}
printf("Users:%d (%d votes) FqVoters:%d (%d votes)\n", VoteUIdV.Len(), HalfVotes*2, FqVoterSet.Len(), SoFar);
}
void TWikiElecBs::GetAdminTmSet(THash<TInt, TSecTm>& AdminSet) const {
AdminSet.Clr(false);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.IsSucc) {
AdminSet.AddDat(E.UsrId, E.GetTm());
}
}
}
void TWikiElecBs::KeepFqVoters(const int& MinVotes, const int& MinElecLen, const bool& OnlyAdmins) {
TIntSet Voters;
GetFqVoters(Voters, MinVotes, MinElecLen, OnlyAdmins);
printf("freq voters %d\n", Voters.Len());
int VotesB=0, VotesA=0;
for (int e = 0; e < Len(); e++) {
TWikiElec& E = GetElec(e);
VotesB += E.Len();
if (E.Len() < MinElecLen) { E.VoteV.Clr(); }
//printf(" %d --> ", E.Len());
E.KeepVotes(Voters);
//printf("%d\n", E.Len());
VotesA += E.Len();
}
printf("Votes: %d --> %d\n", VotesB, VotesA);
}
void TWikiElecBs::KeepVoters(const bool& KeepAdmins, const bool& KeepNonAdmins) {
TIntSet KeepVoters, Admins;
GetAdminSet(Admins);
if (KeepAdmins) {
KeepVoters = Admins; }
if (KeepNonAdmins) {
TIntV UIdV; GetUsrV(UIdV);
for (int i = 0; i < UIdV.Len(); i++) {
if (! Admins.IsKey(UIdV[i])) {
KeepVoters.AddKey(UIdV[i]); } }
}
int VotesB=0, VotesA=0;
printf("voters %d\n", KeepVoters.Len());
for (int e = 0; e < Len(); e++) {
TWikiElec& E = GetElec(e);
VotesB += E.Len();
E.KeepVotes(KeepVoters);
VotesA += E.Len();
}
printf(" votes: %d --> %d\n", VotesB, VotesA);
}
void TWikiElecBs::KeepTopVoters(const int& Votes, const bool& KeepTop) {
}
void TWikiElecBs::PermuteVotes() {
printf("Permute election entries...");
for (int u = 0; u < Len(); u++) {
//for (int e = 0; e < UsrElecH[u].Len(); e++) { UsrElecH[u][e].PermuteVotes(OnlyVotes); }
GetElec(u).PermuteVotes();
}
printf("done.\n");
}
void TWikiElecBs::SortVotesByTm() {
for (int e = 0; e < Len(); e++) {
GetElec(e).VoteV.Sort();
}
}
// UIdV : user ids of users we consider
// ProbSupTmV : Probability of user voting support vs. time of user's vote (index in the election)
// FracSupTmV : Fraction of support voters in the election so far vs. time of user's vote
// ProbSupFracSupV : Probability of user voting support vs. current fraction of support votes in election
// VotesTmV : Number of votes/elections user casted vs. time of user's vote
int TWikiElecBs::GetVoteTrails(const int& MinUsrVotes, const bool& No01Prob, TIntV& UIdV, TVec<TFltPrV>& ProbSupTmV,
TVec<TFltPrV>& FracSupTmV, TVec<TFltPrV>& ProbSupFracSupV, TVec<TFltPrV>& VotesTmV) const {
UIdV.Clr(); ProbSupTmV.Clr(); FracSupTmV.Clr();
ProbSupFracSupV.Clr(); VotesTmV.Clr();
THash<TInt, TIntPrV> UIdVotesH;
TIntFltH FracSupH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10) { continue; } // skip if election has less than 10 votes
for (int v = 0; v < E.Len(); v++) {
UIdVotesH.AddDat(E[v].GetUId()).Add(TIntPr(e,v));
}
FracSupH.AddDat(e, E.GetFracSup());
}
int Votes = 0;
UIdVotesH.SortByDat(false);
TIntH AllCntH, AllCntHS, AllCntHF;
for (int u = 0; u < UIdVotesH.Len(); u++) {
THash<TInt, TMom> TProbH, TFracH, UFPH;
THash<TFlt, TFlt> TVotesH;
TIntPrV& EV = UIdVotesH[u];
EV.Sort();
const int UId = UIdVotesH.GetKey(u);
if (EV.Len() < MinUsrVotes) { continue; }
//// h2: delete first half of elections
//EV.Del(0, EV.Len()/2);
//// h1: delete last half of elections
EV.Del(EV.Len()/2, EV.Len()-1);
for (int ev = 0; ev < EV.Len(); ev++) { // for all user's elections
const TWikiElec& E = GetElec(EV[ev].Val1);
const int v = EV[ev].Val2;
if (v < 10) { continue; } // skip first 10 votes
const int Vote = E[v].GetVote()==1 ? 1:0;
const double Frac = E.GetFracSup(0, v); //!!!
if (v < 110) { // vote index
TProbH.AddDat(10*(v/10)).Add(Vote);
TFracH.AddDat(10*(v/10)).Add(Frac);
TVotesH.AddDat(10*(v/10)) += 1;
}
//UFPH.AddDat(10*int(10*Frac)).Add(Vote);
UFPH.AddDat(10*(int)TMath::Round(10*Frac)).Add(Vote);
Votes++;
}
double M;
TFltPrV TPV, TFV, TFPV, TVV;
for (int i = 0; i < TProbH.Len(); i++) {
TProbH[i].Def(); M = TProbH[i].GetMean();
if (No01Prob && M!=0 && M!=1) { TPV.Add(TFltPr(TProbH.GetKey(i).Val, M)); }
else if (! No01Prob) { TPV.Add(TFltPr(TProbH.GetKey(i).Val, M)); }
//if(TProbH[i].GetVals()>2) { TPV.Add(TFltPr(TProbH.GetKey(i).Val, M)); }
}
for (int i = 0; i < TFracH.Len(); i++) {
TFracH[i].Def(); M = TFracH[i].GetMean();
if (No01Prob && M!=0 && M!=1) { TFV.Add(TFltPr(TFracH.GetKey(i).Val, M)); }
else if (! No01Prob) { TFV.Add(TFltPr(TFracH.GetKey(i).Val, M)); }
//if(TFracH[i].GetVals()>2) { TFV.Add(TFltPr(TFracH.GetKey(i).Val, M)); }
}
for (int i = 0; i < UFPH.Len(); i++) {
UFPH[i].Def(); M = UFPH[i].GetMean();
if (No01Prob && M!=0 && M!=1) { TFPV.Add(TFltPr(UFPH.GetKey(i).Val, M)); }
else if (! No01Prob) { TFPV.Add(TFltPr(UFPH.GetKey(i).Val, M)); }
//if(UFPH[i].GetVals()>2) { TFPV.Add(TFltPr(UFPH.GetKey(i).Val, M)); }
}
TVotesH.GetKeyDatPrV(TVV); TVV.Sort();
TFPV.Sort(); TPV.Sort(); TFV.Sort();
if (TFPV[0].Val1!=0.0) { TFPV.Ins(0, TFltPr(0,0)); printf("Z");} // padd with zeros
if (TFPV.Last().Val1!=100.0) { TFPV.Add(TFltPr(100,1)); printf("O");} // padd with ones
// add data
UIdV.Add(UId);
ProbSupTmV.Add(TPV);
FracSupTmV.Add(TFV);
ProbSupFracSupV.Add(TFPV);
VotesTmV.Add(TVV);
}
IAssert(UIdV.Len() == ProbSupTmV.Len());
return Votes;
}
void TWikiElecBs::GetVoteTrails2(const int& MinUsrVotes, const bool& No01Prob, TIntV& UIdV, TVec<TFltPrV>& VoteIdxFracSupV, TVec<TFltPrV>& NVotesFracSupV) const {
UIdV.Clr(); VoteIdxFracSupV.Clr(); NVotesFracSupV.Clr();
THash<TInt, TIntPrV> UIdVotesH;
TIntFltH FracSupH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10) { continue; } // skip if election has less than 10 votes
for (int v = 0; v < E.Len(); v++) {
UIdVotesH.AddDat(E[v].GetUId()).Add(TIntPr(e,v));
}
FracSupH.AddDat(e, E.GetFracSup());
}
UIdVotesH.SortByDat(false);
TIntH AllCntH, AllCntHS, AllCntHF;
for (int u = 0; u < UIdVotesH.Len(); u++) {
THash<TInt, TMom> FSVIdxH;
TFltFltH FSVotesH;
const TIntPrV& EV = UIdVotesH[u];
const int UId = UIdVotesH.GetKey(u);
if (EV.Len() < MinUsrVotes) { continue; }
for (int ev = 0; ev < EV.Len(); ev++) { // for all user's elections
const TWikiElec& E = GetElec(EV[ev].Val1);
const int v = EV[ev].Val2;
//if (v < 10) { continue; }
const int Vote = E[v].GetVote()==1 ? 1:0;
const double Frac = E.GetFracSup(0, v); //!!!
FSVotesH.AddDat(10*int(10*Frac)) += 1;
FSVIdxH.AddDat(10*int(10*Frac)).Add(v);
}
// add data
UIdV.Add(UId);
double M = 0;
VoteIdxFracSupV.Add();
TFltPrV& VoteIdxV = VoteIdxFracSupV.Last();
for (int i = 0; i < FSVIdxH.Len(); i++) {
FSVIdxH[i].Def(); M = FSVIdxH[i].GetMean();
if (No01Prob && M!=0 && M!=1) { VoteIdxV.Add(TFltPr(FSVIdxH.GetKey(i).Val, M)); }
else if (! No01Prob) { VoteIdxV.Add(TFltPr(FSVIdxH.GetKey(i).Val, M)); }
}
VoteIdxV.Sort();
NVotesFracSupV.Add();
FSVotesH.GetKeyDatPrV(NVotesFracSupV.Last());
NVotesFracSupV.Last().Sort();
}
}
void TWikiElecBs::GetUsrVoteTrail(const TIntV& UIdV, TVec<TFltPrV>& ProbPosFracPosV) const {
ProbPosFracPosV.Clr();
THash<TInt, TIntPrV> UIdVotesH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10) { continue; } // skip if election has less than 10 votes
for (int v = 0; v < E.Len(); v++) {
UIdVotesH.AddDat(E[v].GetUId()).Add(TIntPr(e,v));
}
}
for (int u = 0; u < UIdV.Len(); u++) {
ProbPosFracPosV.Add();
if (! UIdVotesH.IsKey(UIdV[u])) { continue; }
const TIntPrV& EV = UIdVotesH.GetDat(UIdV[u]);
THash<TInt, TMom> FracProbH;
for (int ev = 0; ev < EV.Len(); ev++) { // for all user's elections
const TWikiElec& E = GetElec(EV[ev].Val1);
const int v = EV[ev].Val2;
//if (v < 10) { continue; }
const int Vote = E[v].GetVote()==1 ? 1:0;
const double Frac = E.GetFracSup(0, v); //!!!
FracProbH.AddDat(10*int(10*Frac)).Add(Vote);
}
FracProbH.SortByKey();
TFltPrV& ProbFracV = ProbPosFracPosV.Last();
for (int i = 0; i < FracProbH.Len(); i++) {
FracProbH[i].Def();
const double M = FracProbH[i].GetMean();
ProbFracV.Add(TFltPr(FracProbH.GetKey(i).Val, M));
}
ProbFracV.Sort();
}
}
void TWikiElecBs::GetUsrAreaUTrail(const TIntV& UIdV, TFltV& AreaV) const {
TVec<TFltPrV> ProbPosFracPosV;
GetUsrVoteTrail(UIdV, ProbPosFracPosV);
AreaV.Clr();
for (int u = 0; u < ProbPosFracPosV.Len(); u++) {
double Area = 0;
TFltPrV& V = ProbPosFracPosV[u];
for (int f = 0; f < V.Len(); f++) {
IAssert(V[f].Val1>= 0 && V[f].Val1<=100);
Area += (V[f].Val2 - V[f].Val1/100.0);
}
AreaV.Add(Area);
}
}
// plot vote statistics: lengths
void TWikiElecBs::PlotElecLenDistr(const TStr& OutFNm) const {
TIntH SupCntHS, OppCntHS, VotesCntHS, // succ elecs
SupCntHF, OppCntHF, VotesCntHF, // fail elecs
SupCntHA, OppCntHA, VotesCntHA; // all elecs
TIntH VotesPerUser;
THashSet<TFltPr> SupOppHS, SupOppHF;
THash<TInt, TMom> ElLenVsSucc;
TIntH SupFracA, SupFracS, SupFracF;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
const int SupFrac = (int)TMath::Round(E.GetFracSup()*10)*10;
TIntTr V = E.GetVotes();
int len = (E.Len()/5)*5;
V.Val1 = (V.Val1/5)*5;
V.Val2 = (V.Val2/5)*5;
V.Val3 = (V.Val3/5)*5;
SupFracA.AddDat(SupFrac) +=1;
if (E.IsSucc) {
SupFracS.AddDat(SupFrac) += 1;
VotesCntHS.AddDat(len) += 1;
SupCntHS.AddDat(V.Val1) += 1;
OppCntHS.AddDat(V.Val3) += 1;
SupOppHS.AddKey(TFltPr(V.Val1+0.1+TInt::Rnd.GetNrmDev(), V.Val3+0.1+TInt::Rnd.GetNrmDev()));
ElLenVsSucc.AddDat(len).Add(1);
} else {
SupFracF.AddDat(SupFrac) += 1;
VotesCntHF.AddDat(len) += 1;
SupCntHF.AddDat(V.Val1) += 1;
OppCntHF.AddDat(V.Val3) += 1;
SupOppHF.AddKey(TFltPr(V.Val1+0.1+TInt::Rnd.GetNrmDev(), V.Val3+0.1+TInt::Rnd.GetNrmDev()));
ElLenVsSucc.AddDat(len).Add(0);
}
VotesCntHA.AddDat(len) += 1;
SupCntHA.AddDat(V.Val1) += 1;
OppCntHA.AddDat(V.Val3) += 1;
}
TIntPrV VotesUIdV; GetUsrVotes(VotesUIdV);
for (int i = 0; i < VotesUIdV.Len(); i++) {
VotesPerUser.AddDat(10*(VotesUIdV[i].Val1/10))+=1;
}
TGnuPlot::PlotValCntH(VotesPerUser, "userVotes-"+OutFNm, "", "Number of votes", "Number of such users");
TGnuPlot::PlotValMomH(ElLenVsSucc, "elLenSucc-"+OutFNm, "", "Election length", "Probability of success");
{ TGnuPlot GP("suppOppScatter-"+OutFNm); GP.SetXYLabel("Support votes", "Oppose votes");
TFltPrV SuccV, FailV; SupOppHS.GetKeyV(SuccV); SupOppHF.GetKeyV(FailV);
GP.AddPlot(FailV, gpwPoints, "FAIL"); GP.AddPlot(SuccV, gpwPoints, "SUCC");
GP.SavePng(); }
{ TGnuPlot GP("countSup-"+OutFNm); GP.SetXYLabel("Support votes", "Count");
GP.AddPlot(SupCntHA, gpwLinesPoints, "ALL elections");
GP.AddPlot(SupCntHS, gpwLinesPoints, "SUCC elections");
GP.AddPlot(SupCntHF, gpwLinesPoints, "FAIL elections");
GP.SavePng(); }
{ TGnuPlot GP("countOpp-"+OutFNm); GP.SetXYLabel("Oppose votes", "Count");
GP.AddPlot(OppCntHA, gpwLinesPoints, "ALL elections");
GP.AddPlot(OppCntHS, gpwLinesPoints, "SUCC elections");
GP.AddPlot(OppCntHF, gpwLinesPoints, "FAIL elections");
GP.SavePng(); }
{ TGnuPlot GP("countVot-"+OutFNm); GP.SetXYLabel("Votes", "Count");
GP.AddPlot(VotesCntHA, gpwLinesPoints, "ALL elections");
GP.AddPlot(VotesCntHS, gpwLinesPoints, "SUCC elections");
GP.AddPlot(VotesCntHF, gpwLinesPoints, "FAIL elections");
GP.SavePng(); }
{ TGnuPlot GP("supFrac-"+OutFNm); GP.SetXYLabel("Final Fraction of support votes", "Number of such elections");
GP.AddPlot(SupFracA, gpwLinesPoints, "ALL elections");
GP.AddPlot(SupFracS, gpwLinesPoints, "SUCC elections");
GP.AddPlot(SupFracF, gpwLinesPoints, "FAIL elections");
GP.SavePng(); }
}
// plot election support-oppose votes over time
void TWikiElecBs::PlotElecSupOppOt(const TStr& OutFNm, const int& MinVotes, const int& MaxVotes) const {
int ElecCnt=0;
TGnuPlot GP("supOppOT-"+OutFNm);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinVotes || E.Len() > MaxVotes) { continue; }
TFltPrV OppSupV; OppSupV.Add(TFltPr(0,0));
for (int v = 0; v < E.Len(); v++) {
const int S = E[v].GetVote();
OppSupV.Add(TFltPr(OppSupV.Last().Val1+(S<0?1:0)+0.1*TInt::Rnd.GetNrmDev(),
OppSupV.Last().Val2+(S>0?1:0)+0.1*TInt::Rnd.GetNrmDev()));
}
//for (int i = 0; i < OppSupV.Len(); i++) {
// OppSupV[i].Val1 /= OppSupV.Last().Val1;
// OppSupV[i].Val2 /= OppSupV.Last().Val2; }
GP.AddPlot(OppSupV, gpwLines, "", TStr::Fmt("lt %d", E.IsSucc?2:1));
ElecCnt++;
}
//GP.SetXRange(0,1); GP.SetYRange(0,1);
GP.SetXYLabel("oppose votes", "support votes");
GP.SetTitle(TStr::Fmt("elections with %d -- %d votes: %d elections", MinVotes, MaxVotes, ElecCnt));
GP.SavePng();
}
// plot user vote run length statistics
void TWikiElecBs::PlotRunLenStat(const TStr& OutFNm, const int& MinVotes, const int& MaxVotes) const {
THash<TInt, TTriple<TMom, TMom, TMom> > UsrMomH;
THash<TInt, TMom> TxtLenH;
TPair<TMom, TMom> RunLStat;
THash<TInt, TInt> SupH, OppH;
int Cnt=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinVotes || E.Len() > MaxVotes) { continue; }
for (int v = 0; v < E.Len(); v++) {
const int V = E.GetVote(v).GetVote();
const int RunL = E.GetRunLen(v);
if (V == 1) {
UsrMomH.AddDat(E.GetVote(v).GetUId()).Val1.Add(RunL);
RunLStat.Val1.Add(RunL);
SupH.AddDat(RunL)++;
} else {
UsrMomH.AddDat(E.GetVote(v).GetUId()).Val2.Add(RunL);
RunLStat.Val2.Add(RunL);
OppH.AddDat(RunL)++;
}
UsrMomH.AddDat(E.GetVote(v).GetUId()).Val3.Add(E[v].GetTxtLen());
TxtLenH.AddDat(10*(E[v].GetTxtLen()/10)).Add(RunL);
}
Cnt++;
}
TGnuPlot::PlotValMomH(TxtLenH, "runLenTxtLen-"+OutFNm, "", "Length of the text supporting the vote", "Run length",
gpsAuto, gpwLinesPoints, true, true, false, false, false);
RunLStat.Val1.Def();
RunLStat.Val2.Def();
printf("SUP run len: A:%g M:%g\n", RunLStat.Val1.GetMean(), RunLStat.Val1.GetMedian());
printf("OPP run len: A:%g M:%g\n", RunLStat.Val2.GetMean(), RunLStat.Val2.GetMedian());
TGnuPlot GP("runLen-"+OutFNm, TStr::Fmt("Elecs %d--%d: %d. SUP run len: A:%g M:%g OPP: A:%g M:%g", MinVotes, MaxVotes, Cnt,
RunLStat.Val1.GetMean(), RunLStat.Val1.GetMedian(), RunLStat.Val2.GetMean(), RunLStat.Val2.GetMedian()));
GP.AddPlot(OppH, gpwLinesPoints, "OPP");
GP.AddPlot(SupH, gpwLinesPoints, "SUP");
GP.SetXYLabel("run length", "count");
GP.SavePng();
// save user stat
FILE *F = fopen(TStr::Fmt("runLenUsers-%s.tab", OutFNm.CStr()).CStr(), "wt");
fprintf(F, "#UsrId\tUser\tVotes\tSup-Votes\tOpp-Votes\tSup-Avg\tSup-Med\tOpp-Avg\tOpp-Med\tTxtLen-Avg\tTxtLen-Med\n");
for (int u = 0; u < UsrMomH.Len(); u++) {
TMom& MS = UsrMomH[u].Val1; MS.Def();
TMom& MO = UsrMomH[u].Val2; MO.Def();
TMom& TL = UsrMomH[u].Val3; TL.Def();
fprintf(F, "%d\t%s\t%d\t%d\t%d\t%g\t%g\t%g\t%g\t%g\t%g\n", UsrMomH.GetKey(u), GetUsr(UsrMomH.GetKey(u)),
MS.GetVals()+MO.GetVals(), MS.GetVals(), MO.GetVals(), MS.GetMean(), MS.GetMedian(), MO.GetMean(), MO.GetMedian(),
TL.GetMean(), TL.GetMedian());
}
fclose(F);
}
// draw election tree
void TWikiElecBs::DrawElecTree(const TStr& OutFNm, const int& MinVotes) const {
TIntV UIdV; GetEIdByVotes(UIdV);
TWikiVoteV VoteV;
THash<TInt, TIntQu> TreeH; // NId
const int TakeVotes = 3;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinVotes) { continue; }
TInt BegVote=1;
const TIntTr SNO = E.GetVotes();
{ TIntQu& V = TreeH.AddDat(BegVote);
V.Val1 += SNO.Val1; V.Val2 += SNO.Val3; V.Val3 += 1;
V.Val4 += E.IsSucc() ? 1:0; }
for (int v = 0; v < TakeVotes; v++) {
if (E[v].GetVote() == 1) { BegVote = 2*BegVote+1; } // sup
else { BegVote = 2*BegVote; } // opp
TIntQu& V = TreeH.AddDat(BegVote);
V.Val1 += SNO.Val1;
V.Val2 += SNO.Val3;
V.Val3 += 1;
V.Val4 += E.IsSucc() ? 1:0;
}
}
PNGraph G = TNGraph::New();
TIntStrH LabelH;
TreeH.SortByKey();
for (int i = 0; i < TreeH.Len(); i++) {
printf("%d\n", TreeH.GetKey(i));
const int id = TreeH.GetKey(i);
const int nid = G->AddNode(i+1);
//LabelH.AddDat(nid, TStr::Fmt("%s\\nElections:%d\\nS/O: %d/%d\\nSup: %.4f\\nSucc:%.4f", id==1?"":(id%2==1 ?"SUPPORT":"OPPOSE"),
// TreeH[i].Val3, TreeH[i].Val1, TreeH[i].Val2, TreeH[i].Val1/double(TreeH[i].Val1+TreeH[i].Val2), TreeH[i].Val4/double(TreeH[i].Val3)));
LabelH.AddDat(nid, TStr::Fmt("%sElections: %d\\nSuccessful: %.3f", id==1?"":(id%2==1 ?"SUPPORT\\n":"OPPOSE\\n"), TreeH[i].Val3, TreeH[i].Val4/double(TreeH[i].Val3)));
if (id > 1) {
G->AddEdge(id/2, nid);
printf("link %d <-- %d\n", id/2, nid);
}
}
TGraphViz::Plot(G, gvlDot, "elecTree-"+OutFNm+".gif", "", LabelH);
}
// plot how the statistics of the election as the election goes on
void TWikiElecBs::PlotVotesOt(const TStr& OutFNm, const int& MinVotes, const int& MaxVotes) const {
THash<TInt, TMom> FSupOtA, PSupOtA, DevOtA,
FSupOtS, PSupOtS, DevOtS, FSupOtF, PSupOtF, DevOtF;
int Cnt=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinVotes || E.Len() > MaxVotes) { continue; }
int S = 0;
double Dev = 0;
for (int v = 0; v < E.Len(); v++) {
const int V = E.GetVote(v).GetVote()==1? 1:0;
if (v > 0) {
Dev = fabs(V - S/double(v))/double(v+1); }
S += V; // support votes so far
if (E.IsSucc) {
FSupOtS.AddDat(v+1).Add(S/double(v+1));
PSupOtS.AddDat(v+1).Add(V);
DevOtS.AddDat(v+1).Add(Dev);
} else {
FSupOtF.AddDat(v+1).Add(S/double(v+1));
PSupOtF.AddDat(v+1).Add(V);
DevOtF.AddDat(v+1).Add(Dev);
}
FSupOtA.AddDat(v+1).Add(S/double(v+1));
PSupOtA.AddDat(v+1).Add(V);
DevOtA.AddDat(v+1).Add(Dev);
}
Cnt++;
}
{ TGnuPlot GP("votesOT-Frac-"+OutFNm, TStr::Fmt("Elections %d--%d: %d", MinVotes, MaxVotes, Cnt));
GP.SetXYLabel("Time (vote index)", "Fraction of support votes so far");
GP.AddPlot(FSupOtA, gpwLinesPoints, "ALL elections", "", true, false);
GP.AddPlot(FSupOtS, gpwLinesPoints, "SUCC elections", "", true, false);
GP.AddPlot(FSupOtF, gpwLinesPoints, "FAIL elections", "", true, false);
if (MinVotes>10) { GP.SetXRange(0, MinVotes); } GP.SavePng(); }
{ TGnuPlot GP("votesOT-Sup-"+OutFNm, TStr::Fmt("Elections %d--%d: %d", MinVotes, MaxVotes, Cnt));
GP.SetXYLabel("Time (vote index)", "Probability i-th vote is Support");
GP.AddPlot(PSupOtA, gpwLinesPoints, "ALL elections", "", true, false);
GP.AddPlot(PSupOtS, gpwLinesPoints, "SUCC elections", "", true, false);
GP.AddPlot(PSupOtF, gpwLinesPoints, "FAIL elections", "", true, false);
if (MinVotes>10) { GP.SetXRange(0, MinVotes); } GP.SavePng(); }
{ TGnuPlot GP("votesOT-Dev-"+OutFNm, TStr::Fmt("Elections %d--%d: %d", MinVotes, MaxVotes, Cnt));
GP.SetXYLabel("Time (vote index)", "Vote deviation: avg |avg(V,t+1) - avg(V,t)|");
GP.AddPlot(DevOtA, gpwLinesPoints, "ALL elections", "", true, false);
GP.AddPlot(DevOtS, gpwLinesPoints, "SUCC elections", "", true, false);
GP.AddPlot(DevOtF, gpwLinesPoints, "FAIL elections", "", true, false);
if (MinVotes>10) { GP.SetXRange(0, MinVotes); } GP.SavePng(); }
}
void TWikiElecBs::PlotCovotingUsers(const TStr& OutFNm, const TStr& MinSupStr, const int& TakeOnlyVotes) const {
PNGraph G = TNGraph::New();
TStrSet RfaSet;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
const int RfaId = Kilo(100)+RfaSet.AddKey(E.RfaTitle);
if (G->IsNode(RfaId)) { printf("%s\n", E.RfaTitle.CStr()); continue; }
IAssertR(! G->IsNode(RfaId), E.RfaTitle);
G->AddNode(RfaId);
for (int v = 0; v < E.Len(); v++) {
if (TakeOnlyVotes==1 && E[v].GetVote() != 1) { continue; } // take only supoprt votes
else if (TakeOnlyVotes==-1 && E[v].GetVote() != -1) { continue; } // only oppose votes
const int usr = E[v].GetUId();
if (! G->IsNode(usr)) { G->AddNode(usr); }
IAssert(! G->IsEdge(usr, RfaId));
G->AddEdge(usr, RfaId);
}
}
TSnap::PrintInfo(G);
printf("\n*** ALL VOTES\n");
TStrV MinSupV;
TStr(MinSupStr).SplitOnAllCh(',', MinSupV);
TGnuPlot GP(TStr::Fmt("itemSet-%s", OutFNm.CStr()), "Number and size of frequent itemsets");
for (int i = 0; i < MinSupV.Len(); i++) {
printf("\n*** MinSup = %s\n", MinSupV[i].CStr());
TTrawling Trawl(G, MinSupV[i].GetInt());
const TIntPrV SzCntV = Trawl.PlotMinFqVsMaxSet(TStr::Fmt("%s-%02d", OutFNm.CStr(), MinSupV[i].GetInt()));
GP.AddPlot(SzCntV, gpwLinesPoints, TStr::Fmt("MinSup = %d", MinSupV[i].GetInt()));
}
GP.SetXYLabel("Itemset size", "Number of itemsets");
GP.SavePng();
}
// fraction of support votes before and after the user casted a vote
void TWikiElecBs::PlotFracBeforeAfterVote(const TStr& OutFNm) const {
THash<TInt, TIntPrV> UIdVotesH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10) { continue; } // election has at least 10 votes
for (int v = 0; v < E.Len(); v++) {
UIdVotesH.AddDat(E[v].GetUId()).Add(TIntPr(e,v));
}
}
THash<TFlt, TInt> DeltaCntHA, DeltaCntHS, DeltaCntHO, DeltaCntHA2, DeltaCntHS2, DeltaCntHO2;
FILE *F = fopen(TStr::Fmt("deltabBAUsr-%s.tab", OutFNm.CStr()).CStr(), "wt");
fprintf(F, "#Usr\tVotes\tAvgDSup\tMedDSup\tSupVotes\tAvgDOpp\tMedDOpp\tOppVotes\tAvgTrendSup\tMedTrendSup\tAvgTrendOpp\tMedTrendOpp\n");
for (int u = 0; u < UIdVotesH.Len(); u++) {
const TIntPrV& EV = UIdVotesH[u];
if (EV.Len() < 10) { continue; } // user did at least 10 votes
TMom MomS, MomO, MomS2, MomO2;
for (int ev = 0; ev < EV.Len(); ev++) {
const TWikiElec& E = GetElec(EV[ev].Val1);
const int v = EV[ev].Val2;
if (v < 5 || v+5 >= E.Len()) { continue; }
const double Bef = E.GetFracSup(0, v); // v-5,v
const double Aft = E.GetFracSup(v+1, E.Len()); // full, else v+1+5
const double Bef2 = E.GetTrend(0, v);
const double Aft2 = E.GetTrend(v+1, E.Len()); // full
DeltaCntHA.AddDat(TMath::Round(Aft-Bef, 2)) += 1;
DeltaCntHA2.AddDat(TMath::Round(Aft2-Bef2, 2)) += 1;
if (E[v].GetVote() == 1) {
DeltaCntHS.AddDat(TMath::Round(Aft-Bef, 2)) += 1;
DeltaCntHS2.AddDat(TMath::Round(Aft2-Bef2, 2)) += 1;
MomS.Add(Aft-Bef);
MomS2.Add(Aft2-Bef2);
} else {
DeltaCntHO.AddDat(TMath::Round(Aft-Bef, 2)) += 1;
DeltaCntHO2.AddDat(TMath::Round(Aft2-Bef2, 2)) += 1;
MomO.Add(Aft-Bef);
MomO2.Add(Aft2-Bef2);
}
}
MomS.Def(); MomO.Def(); MomS2.Def(); MomO2.Def();
if (! MomS.IsUsable() || ! MomO.IsUsable()) { continue; }
fprintf(F, "%s\t%d\t%f\t%f\t%d\t%f\t%f\t%d\n", GetUsr(UIdVotesH.GetKey(u)), EV.Len(),
MomS.GetMean(), MomS.GetMedian(), MomS.GetVals(), MomO.GetMean(), MomO.GetMedian(), MomO.GetVals(),
MomS2.GetMean(), MomS2.GetMedian(), MomO2.GetMean(), MomO2.GetMedian());
}
fclose(F);
TGnuPlot::PlotValCntH(DeltaCntHA, "deltaBA-"+OutFNm, "Fraction of support votes After-Before user casted a vote. (min 10 votes per user, min 10 vote elections, min 5 votes before/after",
"After - Before fraction of support votes. Any vote.", "Count");
TGnuPlot::PlotValCntH(DeltaCntHS, "deltaBASup-"+OutFNm, "Fraction of support votes After-Before user casted a vote. (min 10 votes per user, min 10 vote elections, min 5 votes before/after",
"After - Before fraction of support votes. User voted +1.", "Count");
TGnuPlot::PlotValCntH(DeltaCntHO, "deltaBAOpp-"+OutFNm, "Fraction of support votes After-Before user casted a vote. (min 10 votes per user, min 10 vote elections, min 5 votes before/after",
"After - Before fraction of support votes. User voted -1.", "Count");
TGnuPlot::PlotValCntH(DeltaCntHA2, "deltaTrBA-"+OutFNm, "Trend of fraction ofsupport votes After-Before user casted a vote. (min 10 votes per user, min 10 vote elections, min 5 votes before/after",
"After - Before trend (linear fit coefficient) fraction of support votes. Any vote.", "Count");
TGnuPlot::PlotValCntH(DeltaCntHS2, "deltaTrBASup-"+OutFNm, "Trend of fraction ofsupport votes After-Before user casted a vote. (min 10 votes per user, min 10 vote elections, min 5 votes before/after",
"After - Before trend (linear fit coefficient) fraction of support votes. User voted +1.", "Count");
TGnuPlot::PlotValCntH(DeltaCntHO2, "deltaTrBAOpp-"+OutFNm, "Trend of fraction of support votes After-Before user casted a vote. (min 10 votes per user, min 10 vote elections, min 5 votes before/after",
"After - Before trend (linear fit coefficient) fraction of support votes. User voted -1.", "Count");
}
void TWikiElecBs::PlotDeltaFracSupOt(const TStr& OutFNm, const int& MinVotes, const int& MaxVotes) const {
THash<TInt, TMom> DeltaOtA, DeltaOtS, DeltaOtF;
int Cnt = 0, CntS=0, CntF=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinVotes || E.Len() > MaxVotes) { continue; }
TIntTr SNO = E.GetVotes();
const double FinalF = SNO.Val1/double(SNO.Val1+SNO.Val3);
int S = 0;
for (int v = 0; v < E.Len(); v++) {
const int V = E.GetVote(v).GetVote()==1? 1:0;
S += V; // support votes so far
if (E.IsSucc) { DeltaOtS.AddDat(v).Add(S/double(v+1)-FinalF); }
else { DeltaOtF.AddDat(v).Add(S/double(v+1)-FinalF); }
DeltaOtA.AddDat(v).Add(S/double(v+1)-FinalF);
}
if (E.IsSucc) { CntS++; }
else { CntF++; }
Cnt++;
}
TGnuPlot::PlotValMomH(DeltaOtA, "deltaFracSup-A-"+OutFNm, TStr::Fmt("ALL Elections %d--%d: %d", MinVotes, MaxVotes, Cnt),
"Vote index", "Deviation from the final fraction of support votes");
TGnuPlot::PlotValMomH(DeltaOtS, "deltaFracSup-S-"+OutFNm, TStr::Fmt("SUCC Elections %d--%d: %d", MinVotes, MaxVotes, CntS),
"Vote index", "Deviation from the final fraction of support votes");
TGnuPlot::PlotValMomH(DeltaOtF, "deltaFracSup-F-"+OutFNm, TStr::Fmt("FAIL Elections %d--%d: %d", MinVotes, MaxVotes, CntF),
"Vote index", "Deviation from the final fraction of support votes");
}
void TWikiElecBs::PlotUsrVoteVsTime(const TStr& OutFNm, const int& MinUsrVotes, const TIntSet& UsrSplitSet) const {
THash<TInt, TIntPrV> UIdVotesH;
TIntFltH FracSupH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
//if (E.Len() < 10) { continue; } // election has at least 10 votes
for (int v = 0; v < E.Len(); v++) {
UIdVotesH.AddDat(E[v].GetUId()).Add(TIntPr(e,v));
}
FracSupH.AddDat(e, E.GetFracSup());
}
UIdVotesH.SortByDat(false);
THash<TInt, TMom> AllMomH, AllMomHS, AllMomHF, AdmMomH, NAdmMomH;
TIntH AllCntH, AllCntHS, AllCntHF, AdmCntH, NAdmCntH;
//TIntSet AdminSet; GetAdminSet(AdminSet);
int Cnt=0, UCnt=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
for (int v = 0; v < TMath::Mn(E.Len(),101); v++) {
const int Vote = E.GetVote(v).GetVote()==1?1:0;
AllMomH.AddDat(v).Add(Vote);
AllCntH.AddDat(v) += 1;
if (E.IsSucc) {
AllMomHS.AddDat(v).Add(Vote);
AllCntHS.AddDat(v) += 1; }
else {
AllMomHF.AddDat(v).Add(Vote);
AllCntHF.AddDat(v) += 1;
}
// admins vs. non-admins
//if (AdminSet.IsKey(E[v].GetUId())) {
if (UsrSplitSet.IsKey(E[v].GetUId())) {
AdmMomH.AddDat(v).Add(Vote);
AdmCntH.AddDat(v) += 1;
} else {
NAdmMomH.AddDat(v).Add(Vote);
NAdmCntH.AddDat(v) += 1;
}
}
}
/*
for (int u = 0; u < UIdVotesH.Len(); u++) {
THash<TInt, TMom> UsrMomH;
const TIntPrV& EV = UIdVotesH[u];
//if (EV.Len() < MinUsrVotes) { continue; }
for (int ev = 0; ev < EV.Len(); ev++) {
const TWikiElec& E = GetElec(EV[ev].Val1);
const int v = EV[ev].Val2;
const int Vote = E[v].GetVote()==1 ? 1:0;
//const double Vote = E[v].GetVote()==1 ? FracSupH.GetDat(EV[ev].Val1):1-FracSupH.GetDat(EV[ev].Val1);
if (v > 100) { continue; }
UsrMomH.AddDat(v).Add(Vote);
AllMomH.AddDat(v).Add(Vote);
AllCntH.AddDat(v) += 1;
if (E.IsSucc) {
AllMomHS.AddDat(v).Add(Vote);
AllCntHS.AddDat(v) += 1; }
else {
AllMomHF.AddDat(v).Add(Vote);
AllCntHF.AddDat(v) += 1;
}
Cnt++;
}
//TGnuPlot::PlotValMomH(UsrMomH, TStr::Fmt("usrVoteVsTm-%s-%03d", OutFNm.CStr(), u),
// TStr::Fmt("%d votes of user %s", EV.Len(), GetUsr(UIdVotesH.GetKey(u))), "time when user voted", "fraction of positive votes",
// gpsAuto, gpwLinesPoints, true, false, false, false, false, false);
UCnt++;
} //*/
TGnuPlot::PlotValMomH(AllMomH, TStr::Fmt("usrVoteVsTm-%s-all", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "fraction of positive votes",
gpsAuto, gpwLinesPoints, true, false, false, false, false, false);
TGnuPlot::PlotValCntH(AllCntH, TStr::Fmt("usrVoteVsTm-%s-CNT-all", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "number of votes");
TGnuPlot::PlotValMomH(AdmMomH, TStr::Fmt("usrVoteVsTm-%s-admin", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "fraction of positive votes",
gpsAuto, gpwLinesPoints, true, false, false, false, false, false);
TGnuPlot::PlotValCntH(AdmCntH, TStr::Fmt("usrVoteVsTm-%s-CNT-admin", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "number of votes");
TGnuPlot::PlotValMomH(NAdmMomH, TStr::Fmt("usrVoteVsTm-%s-nonadmin", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "fraction of positive votes",
gpsAuto, gpwLinesPoints, true, false, false, false, false, false);
TGnuPlot::PlotValCntH(NAdmCntH, TStr::Fmt("usrVoteVsTm-%s-CNT-nonadmin", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "number of votes");
/*TGnuPlot::PlotValMomH(AllMomHS, TStr::Fmt("usrVoteVsTm-%s-succ", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. SUCC ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "fraction of positive votes",
gpsAuto, gpwLinesPoints, true, false, false, false, false, false);
TGnuPlot::PlotValMomH(AllMomHF, TStr::Fmt("usrVoteVsTm-%s-fail", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. FAIL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "fraction of positive votes",
gpsAuto, gpwLinesPoints, true, false, false, false, false, false);*/
/*TGnuPlot::PlotValCntH(AllCntHS, TStr::Fmt("usrVoteVsTm-%s-CNT-succ", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. SUCC ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "number of votes");
TGnuPlot::PlotValCntH(AllCntHF, TStr::Fmt("usrVoteVsTm-%s-CNT-fail", OutFNm.CStr()),
TStr::Fmt("%d votes of %d users with more than %d votes. FAIL ELEC.", Cnt, UCnt, MinUsrVotes),
"time when user voted", "number of votes");*/
}
// plot as a function of outcome
void TWikiElecBs::PlotFirstOppOutcome(const TStr& OutFNm, const int& NVotes) const {
THash<TInt, TMom> FOppH, FOpp2H;
TIntH FOppCntH;
int NElec=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10 || E.Len() < NVotes) { continue; } // election has at least 10 votes
int FirstOpp=-1, VoteSum=0;
for (int v = 0; v < NVotes; v++) {
if (E[v].GetVote()==-1 && FirstOpp==-1) { FirstOpp = v+1; }
VoteSum += E[v].GetVote();
}
if (VoteSum != NVotes-2) { continue; }
FOppCntH.AddDat(FirstOpp) += 1;
FOppH.AddDat(FirstOpp).Add(E.IsSucc?1:0);
FOpp2H.AddDat(FirstOpp).Add(E.GetFracSup());
NElec++;
}
TGnuPlot::PlotValMomH(FOppH, "firstOpp1-"+OutFNm, TStr::Fmt("Take first %d votes of an election, where %d Sup and 1 Opp. %d such elections", NVotes, NVotes-1, NElec),
"Index of the oppose vote", "Fraction of successful elections", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(FOpp2H, "firstOpp2-"+OutFNm, TStr::Fmt("Take first %d votes of an election, where %d Sup and 1 Opp. %d such elections", NVotes, NVotes-1, NElec),
"Index of the oppose vote", "Final fraction of support votes in the election", gpsAuto, gpwLinesPoints, true, false, false, false, true, false);
TGnuPlot::PlotValCntH(FOppCntH, "firstOppCnt-"+OutFNm, TStr::Fmt("Take first %d votes of an election, where %d Sup and 1 Opp. %d such elections", NVotes, NVotes-1, NElec),
"Index of the oppose vote", "Number of such elections");
}
void TWikiElecBs::PlotVoteTrails(const TStr& OutFNm, const int& MinUsrVotes, const bool& No01Prob) const {
TIntSet AdminSet;
TIntV UIdV;
TVec<TFltPrV> ProbSupTmV, FracSupTmV, ProbSupFracSupV, VotesTmV, VoteIdxFracSupV, NVotesFracSupV;
const int TotalVotes = GetVoteTrails(MinUsrVotes, No01Prob, UIdV, ProbSupTmV, FracSupTmV, ProbSupFracSupV, VotesTmV);
GetVoteTrails2(MinUsrVotes, No01Prob, UIdV, VoteIdxFracSupV, NVotesFracSupV);
/// admins
GetAdminSet(AdminSet);
/// frequent voters (take top half of the voters by votes)
/*TIntPrV VotesV; GetUsrVotes(VotesV);
TIntH VotesH;
for (int i = 0; i < VotesV.Len(); i++) {
if (UIdV.IsIn(VotesV[i].Val2)) {
VotesH.AddDat(VotesV[i].Val2, VotesV[i].Val1); }
}
VotesH.SortByDat(false);
for (int i = 0; i < VotesH.Len()/2;i++) {
AdminSet.AddKey(VotesH.GetKey(i)); } //*/
//// votes by the time of their first vote
//
TIntH UsrLnTy;
for (int u = 0; u < UIdV.Len(); u++) { UsrLnTy.AddDat(UIdV[u], AdminSet.IsKey(UIdV[u])?2:1); }
//for (int u = 0; u < UIdV.Len(); u++) { UsrLnTy.AddDat(UIdV[u], u+1); }
/*//// color based on time of adminship (green early, red late)
THash<TInt, TSecTm> AdminTmH;
GetAdminTmSet(AdminTmH); AdminTmH.SortByDat(true);
for (int u = 0; u < UIdV.Len(); u++) {
if (! AdminTmH.IsKey(UIdV[u])) { UsrLnTy.AddDat(UIdV[u], 3); }
else { UsrLnTy.AddDat(UIdV[u], (AdminTmH.GetKeyId(UIdV[u])>=AdminTmH.Len()/2)?2:1); }
}//*/
/*//// Save WikiTalk net on frequent voters
PWikiTalkNet Net = TWikiTalkNet::Load(TZipIn("data/wikiTalkFull.net.rar"));
TIntH UIdTalkH;
TIntStrH ColorH; TIntV SubNIdV;
for (int u = 0; u < UIdV.Len(); u++) {
const TStr U = GetUsr(UIdV[u]);
if (! Net->IsUsr(U)) { UIdTalkH.AddDat(UIdV[u], 0); printf("x"); }
else { UIdTalkH.AddDat(UIdV[u], Net->GetNI(Net->GetUsrNId(U)).GetOutDeg()); printf(".");
//else { UIdTalkH.AddDat(UIdV[u], Net->GetNDat(Net->GetUsrNId(U)).GetTkEdCnt()); printf(".");
SubNIdV.Add(Net->GetUsrNId(U)); ColorH.AddDat(SubNIdV.Last(), AdminSet.IsKey(UIdV[u])?"Blue":"Red");
}
}
UIdTalkH.SortByDat();
for (int i = 0; i < UIdTalkH.Len(); i++) {
if (i < UIdTalkH.Len()/2) { UsrLnTy.AddDat(UIdTalkH.GetKey(i), 1); }
else { UsrLnTy.AddDat(UIdTalkH.GetKey(i), 2); }
}
TSnap::SavePajek(TSnap::GetSubGraph(Net, SubNIdV), "200votes-talknet-all.net", ColorH);
TSnap::SavePajek(TSnap::GetSubGraph(Net, SubNIdV, TWikiTalkEdge(TSecTm(), TSecTm(), 10, 10), true), "200votes-talknet-10talks.net", ColorH);
//*/
// plot
TGnuPlot GPP("voteTrailP-"+OutFNm+"-r10"); //r10==10buckets
TGnuPlot GPF("voteTrailF-"+OutFNm+"-r10");
TGnuPlot GPPF("voteTrailPF-"+OutFNm+"-r10");
TGnuPlot GPV("voteHist-"+OutFNm+"-r10"); // votes over time
TGnuPlot GPFI("voteFIdx-"+OutFNm+"-r10");
TGnuPlot GPFC("voteFCnt-"+OutFNm+"-r10");
THash<TFlt, TMom> AvgAdm, AvgNAdm;
bool FirstA=true, FirstNA=true;
for (int u = 0; u < UIdV.Len(); u++) {
const int UId = UIdV[u];
TStr Tit;
if (FirstA && UsrLnTy.GetDat(UId) == 2) { Tit="Admin (HIGH)"; FirstA=false; }
if (FirstNA && UsrLnTy.GetDat(UId) == 1) { Tit="NonAdmin (LOW)"; FirstNA=false; }
GPP.AddPlot(ProbSupTmV[u], gpwLines, Tit, TStr::Fmt("lt %d lw 1 smooth bezier", UsrLnTy.GetDat(UId)));
GPF.AddPlot(FracSupTmV[u], gpwLines, Tit, TStr::Fmt("lt %d lw 1 smooth bezier", UsrLnTy.GetDat(UId)));
GPV.AddPlot(VotesTmV[u], gpwLines, Tit, TStr::Fmt("lt %d lw 1 smooth bezier", UsrLnTy.GetDat(UId)));
GPPF.AddPlot(ProbSupFracSupV[u], gpwLinesPoints, Tit, TStr::Fmt("lt %d lw 1 smooth bezier", UsrLnTy.GetDat(UId)));
GPFI.AddPlot(VoteIdxFracSupV[u], gpwLines, Tit, TStr::Fmt("lt %d lw 1 smooth bezier", UsrLnTy.GetDat(UId)));
GPFC.AddPlot(NVotesFracSupV[u], gpwLines, Tit, TStr::Fmt("lt %d lw 1 smooth bezier", UsrLnTy.GetDat(UId)));
for (int i = 0; i < ProbSupFracSupV[u].Len(); i++) {
if (AdminSet.IsKey(UId) || AdminSet.Empty()) { // admins
AvgAdm.AddDat(ProbSupFracSupV[u][i].Val1).Add(ProbSupFracSupV[u][i].Val2); }
else { // non-admins
AvgNAdm.AddDat(ProbSupFracSupV[u][i].Val1).Add(ProbSupFracSupV[u][i].Val2); }
}
}
TFltPrV AvgAdmV, AvgNAdmV;
for (int i =0; i < AvgAdm.Len(); i++) { AvgAdm[i].Def();
AvgAdmV.Add(TFltPr(AvgAdm.GetKey(i), AvgAdm[i].GetMean())); }
for (int i =0; i < AvgNAdm.Len(); i++) { AvgNAdm[i].Def();
AvgNAdmV.Add(TFltPr(AvgNAdm.GetKey(i), AvgNAdm[i].GetMean())); }
AvgAdmV.Sort(); AvgNAdmV.Sort();
GPPF.AddPlot(AvgAdmV, gpwLinesPoints, "AVG ADMIN (HIGH)", TStr::Fmt("lt %d lw 5 smooth bezier", 4));
GPPF.AddPlot(AvgNAdmV, gpwLinesPoints, "AVG NON-ADMIN (LOW)", TStr::Fmt("lt %d lw 5 smooth bezier", 3));
GPP.SetTitle(TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", TotalVotes, UIdV.Len(), MinUsrVotes));
GPP.SetXYLabel("vote index", "probability of support vote");
GPP.SetYRange(0,1.01);
//GPP.SavePng();
GPF.SetTitle(TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", TotalVotes, UIdV.Len(), MinUsrVotes));
GPF.SetXYLabel("vote index", "fraction of support votes so far");
GPF.SetYRange(0,1.01);
//GPF.SavePng();
GPPF.SetTitle(TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", TotalVotes, UIdV.Len(), MinUsrVotes));
GPPF.SetXYLabel("Fraction of support votes at time of vote", "Probability of voting positively");
GPPF.SetYRange(0,1.01);
GPPF.SavePng();
GPV.SetTitle(TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", TotalVotes, UIdV.Len(), MinUsrVotes));
GPV.SetXYLabel("vote index", "number of votes");
//GPV.SavePng();
GPFI.SetTitle(TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", TotalVotes, UIdV.Len(), MinUsrVotes));
GPFI.SetXYLabel("Fraction of support votes at time of vote", "Average vote index (time) of a user voting");
//GPFI.SavePng();
GPFC.SetTitle(TStr::Fmt("%d votes of %d users with more than %d votes. ALL ELEC.", TotalVotes, UIdV.Len(), MinUsrVotes));
GPFC.SetXYLabel("Fraction of support votes at time of vote", "Number of times user voted at that fraction");
//GPFC.SavePng();
}
void TWikiElecBs::PlotVoteTrailGlobal(const TStr& OutFNm) const {
THash<TInt, TMom> SuppVoteH, Set1, Set2;
TIntSet UIdSet;
//GetFqVoterSet(UIdSet);
GetAdminSet(UIdSet);
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
int nsup=0;
if (E.Len()<10) { continue; }
for (int v = 0; v < E.Len(); v++) {
const int supFrac = v==0? 0 : int(TMath::Round(10.0*nsup/double(v)))*10;
nsup += E.GetVote(v).GetVote()==1?1:0;
//if (supFrac==0) { continue; }
if (v<10) { continue; } // skip first 10 votes
SuppVoteH.AddDat(supFrac).Add(E.GetVote(v).GetVote()==1?1:0);
if (UIdSet.IsKey(E.GetVote(v).GetUId())) { // set 1
Set1.AddDat(supFrac).Add(E.GetVote(v).GetVote()==1?1:0);
} else { // set 2
Set2.AddDat(supFrac).Add(E.GetVote(v).GetVote()==1?1:0);
}
}
}
TGnuPlot::PlotValMomH(SuppVoteH, "voteTrailAll-"+OutFNm, "Global vote trail", "Fraction of support votes at time of vote", "Probability of voting positively", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(Set1, "voteTrailAll1-"+OutFNm, "Global vote trail. Set1", "Fraction of support votes at time of vote", "Probability of voting positively", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
TGnuPlot::PlotValMomH(Set2, "voteTrailAll2-"+OutFNm, "Global vote trail. Set2", "Fraction of support votes at time of vote", "Probability of voting positively", gpsAuto, gpwLinesPoints, true, false, false, false, false, true);
}
void TWikiElecBs::PlotFinalFracVoteCnt(const TStr& OutFNm, const int& MinUsrVotes, const TIntSet& UsrSplitSet) const {
TIntPrV VoteUIdV; GetUsrVotes(VoteUIdV);
THash<TInt, TIntH> UIdVoteCntH;
TIntH FracVotesH, Set1, Set2;
VoteUIdV.Sort(false);
for (int i = 0; i < VoteUIdV.Len() && VoteUIdV[i].Val1>MinUsrVotes; i++) {
UIdVoteCntH.AddKey(VoteUIdV[i].Val2); }
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
//if (E.Len() < 10) { continue; } // election has at least 10 votes
const int SupFrac= (int(100*E.GetFracSup())/10)*10;
for (int v = 0; v < E.Len(); v++) {
const int V = E[v].GetVote()==1?1:0;
const int U = E[v].GetUId();
FracVotesH.AddDat(SupFrac) += 1;
if (UsrSplitSet.IsKey(U)) { Set1.AddDat(SupFrac) += 1; }
else { Set2.AddDat(SupFrac) += 1; }
if (UIdVoteCntH.IsKey(U)) { UIdVoteCntH.AddDat(U).AddDat(SupFrac) += 1; }
}
}
TGnuPlot::PlotValCntH(FracVotesH, "voteFrac-"+OutFNm+"-all", "All users", "Final fraction of support votes", "Number of votes");
TGnuPlot::PlotValCntH(Set1, "voteFrac-"+OutFNm+"-set1", "UsrSplitSet users", "Final fraction of support votes", "Number of votes");
TGnuPlot::PlotValCntH(Set2, "voteFrac-"+OutFNm+"-set2", "Users no in UsrSplitSet", "Final fraction of support votes", "Number of votes");
TGnuPlot GP("voteFrac-"+OutFNm);
for (int u = 0; u < UIdVoteCntH.Len(); u++) {
TIntPrV ValV;
UIdVoteCntH[u].GetKeyDatPrV(ValV);
ValV.Sort();
GP.AddPlot(ValV, gpwLinesPoints, "", TStr::Fmt("lw 1 smooth bezier"));
}
GP.SetXYLabel("Final fraction of support votes", "Number of votes");
GP.SavePng();
}
void TWikiElecBs::PlotConfusionMatrix(const TStr& OutFNm, const int& MinUsrVotes) const {
THash<TInt, TTuple<TFlt, 4> > TupH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
const int R = E.IsSucc?1:0;
for (int v = 0; v < E.Len(); v++) {
const int V = E[v].GetVote()==1?1:0;
TupH.AddDat(E[v].GetUId())[2*R+V] += 1;
}
}
FILE *F=fopen(TStr::Fmt("confusion-%s.tab", OutFNm.CStr()).CStr(), "wt");
for (int u = 0; u < TupH.Len(); u++) {
const double S = TupH[u][0]+TupH[u][1]+TupH[u][2]+TupH[u][3];
if (S < MinUsrVotes) { continue; }
//TupH[u][0]/=S; TupH[u][1]/=S; TupH[u][2]/=S; TupH[u][3]/=S;
fprintf(F, "%f\t%f\t%f\t%f\n", TupH[u][0], TupH[u][1], TupH[u][2], TupH[u][3]);
}
fclose(F);
}
void TWikiElecBs::PlotSlopeHist(const TStr& OutFNm, const int& MinElecLen) const {
const double BPrec = 1000;
TIntH R21A, R22A, K1A, K2A;
TIntH R21S, R22S, K1S, K2S;
TIntH R21F, R22F, K1F, K2F;
int Cnt=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < MinElecLen) { continue; }
TFltPrV XyV, Xy2;
for (int v = 0; v < E.Len(); v++) {
XyV.Add(TFltPr(v, E[v].GetVote()));
Xy2.Add(TFltPr(v, E.GetFracSup(0, v+1)));
}
double A, B, SigA, SigB, Chi2, R2=0;
TSpecFunc::LinearFit(XyV, A, B, SigA, SigB, Chi2, R2);
if (R2 < -1 || _isnan(R2)) R2 = 0;
K1A.AddDat(int(BPrec*B))+=1;
R21A.AddDat(int(100*R2))+=1;
if (E.IsSucc) {
K1S.AddDat(int(BPrec*B))+=1;
R21S.AddDat(int(100*R2))+=1;
} else {
K1F.AddDat(int(BPrec*B))+=1;
R21F.AddDat(int(100*R2))+=1;
}
TSpecFunc::LinearFit(Xy2, A, B, SigA, SigB, Chi2, R2);
if (R2 < -1 || _isnan(R2)) R2 = 0;
K2A.AddDat(int(BPrec*B))+=1;
R22A.AddDat(int(100*R2))+=1;
if (E.IsSucc) {
K2S.AddDat(int(BPrec*B))+=1;
R22S.AddDat(int(100*R2))+=1;
} else {
K2F.AddDat(int(BPrec*B))+=1;
R22F.AddDat(int(100*R2))+=1;
}
Cnt++;
}
TGnuPlot::PlotValCntH(K1A, "ALL ELEC", K1S, "SUCC ELEC", K1F, "FAIL ELEC", "slopeK1-"+OutFNm, TStr::Fmt("%d elections with >%d votes", Cnt, MinElecLen), "slope (fit of Prob(+|t) vs t)", "count", gpsLog10Y);
TGnuPlot::PlotValCntH(K2A, "ALL ELEC", K2S, "SUCC ELEC", K2F, "FAIL ELEC", "slopeK2-"+OutFNm, TStr::Fmt("%d elections with >%d votes", Cnt, MinElecLen), "slope (fit of FracSup(1..t) vs t)", "count", gpsLog10Y);
TGnuPlot::PlotValCntH(R21A, "ALL ELEC", R21S, "SUCC ELEC", R21F, "FAIL ELEC", "slopeR1-"+OutFNm, TStr::Fmt("%d elections with >%d votes", Cnt, MinElecLen), "R2 (fit of Prob(+|t) vs t)", "count", gpsLog10Y);
TGnuPlot::PlotValCntH(R22A, "ALL ELEC", R22S, "SUCC ELEC", R22F, "FAIL ELEC", "slopeR2-"+OutFNm, TStr::Fmt("%d elections with >%d votes", Cnt, MinElecLen), "R2 (fit of FracSup(1..t) vs t)", "count", gpsLog10Y);
}
//// old plots
void TWikiElecBs::PlotBarnStarsDelta(const TStr& OutFNm) const {
TBarnStars BarnStars;
THash<TInt, TMom> DiffMomH;
TIntH DiffCntH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
const TStr TargetUsr = GetUsr(E.GetUId());
const int TB = BarnStars.GetBarnStars(TargetUsr, E.GetTm());
for (int v = 0; v < E.Len(); v++) {
if (! E[v].IsVote()) { continue; }
const int DeltaStars = BarnStars.GetBarnStars(GetUsr(E[v].GetUId()), E[v].GetTm()) - TB;
DiffMomH.AddDat(DeltaStars).Add(E[v].GetVote()==1?1:0);
DiffCntH.AddDat(DeltaStars) += 1;
}
}
TGnuPlot::PlotValMomH(DiffMomH, "dBarnStars-"+OutFNm, "Number of BarnStars (over ALL VOTES): "+OutFNm, "Barnstars delta (source - destination)",
"Fraction of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false);
TGnuPlot::PlotValCntH(DiffCntH, "dBarnStarts2-"+OutFNm, "Number of BarnSTars (over aLL VOES): "+OutFNm, "Barnstars delta (source - destination)",
"Number of such users", gpsAuto, false, gpwLinesPoints, false, false);
}
// plot the distribution on the number of in-votes for people that went up for adminship
// and were/were not promoted
void TWikiElecBs::PlotAdminVotes(const TStr& OutFNm) const {
TIntH APos, NAPos, ANeg, NANeg;
TIntPrSet AVotes, NAVotes;
for (int e = 0; e < Len(); e++) {
const TIntTr V = GetElec(e).GetVotes(true);
if (GetElec(e).IsSucc) {
APos.AddDat(V.Val1) += 1;
ANeg.AddDat(V.Val3) += 1;
AVotes.AddKey(TIntPr(V.Val1, V.Val3));
} else {
NAPos.AddDat(V.Val1) += 1;
NANeg.AddDat(V.Val3) += 1;
NAVotes.AddKey(TIntPr(V.Val1, V.Val3));
}
}
// election results for admins vs. non-admins
{ TGnuPlot GP("adminSup-"+OutFNm, OutFNm);
GP.AddPlot(APos, gpwLinesPoints, "Support votes for ADMINS");
GP.AddPlot(NAPos, gpwLinesPoints, "Support votes for NON-ADMINS");
GP.SetXYLabel("Number of support votes", "Number of elections");
GP.SavePng(); }
{ TGnuPlot GP("adminOpp-"+OutFNm, OutFNm);
GP.AddPlot(ANeg, gpwLinesPoints, "Oppose votes for ADMINS");
GP.AddPlot(NANeg, gpwLinesPoints, "Oppose votes for NON-ADMINS");
GP.SetXYLabel("Number of oppose votes", "Number of elections");
GP.SavePng(); }
{ TGnuPlot GP("adminSupOpp-"+OutFNm, OutFNm);
TIntPrV V; AVotes.GetKeyV(V);
GP.AddPlot(V, gpwPoints, "Votes for ADMINS");
NAVotes.GetKeyV(V);
GP.AddPlot(V, gpwPoints, "Votes for NON-ADMINS");
GP.SetXYLabel("Number of support votes", "Number of oppose votes");
GP.SavePng(); }
}
void TWikiElecBs::PlotAvgVote(const TStr& OutFNm, const int& MinVotes, const int& MaxVotes) const {
TIntV ElecV;
for (int e = 0; e < Len(); e++) {
//if (GetElec(e).Len() >= MinVotes && GetElec(e).Len() <= MaxVotes) {
if (! GetElec(e).IsSucc()) {
ElecV.Add(e); }
}
PlotAvgVote(ElecV, OutFNm, TStr::Fmt("Elections with %d--%d votes, %d elections", MinVotes, MaxVotes, ElecV.Len()));
}
// running vote average over time
void TWikiElecBs::PlotAvgVote(const TIntV& ElecIdV, const TStr& OutFNm, const TStr& Desc) const {
THash<TInt, TMom> MomH;
THash<TInt, TMom> Mom2H;
TFltV AvgVoteV;
for (int i = 0; i < ElecIdV.Len(); i++) {
GetElec(ElecIdV[i]).GetAvgVoteOt(AvgVoteV, true);
for (int v = 0; v < AvgVoteV.Len(); v++) {
MomH.AddDat(v+1).Add(AvgVoteV[v]); }
const TWikiElec& E = GetElec(ElecIdV[i]);
for (int v = 0; v < E.Len(); v++) {
Mom2H.AddDat(v).Add(E.GetVote(v).GetVote()==1?1:0);
}
}
TGnuPlot::PlotValMomH(MomH, "voteAvg-"+OutFNm, TStr::Fmt("%s. %d elections", Desc.CStr(), ElecIdV.Len()),
"n (vote index, time)", "Running average of positive votes", gpsAuto, gpwLinesPoints, true, false, false, false, false);
TGnuPlot::PlotValMomH(Mom2H, "voteAvg2-"+OutFNm, TStr::Fmt("%s. %d elections", Desc.CStr(), ElecIdV.Len()),
"n (vote index, time)", "Probability of positive vote", gpsAuto, gpwLinesPoints, true, false, false, false, false);
}
// running vote deviation over time
void TWikiElecBs::PlotAvgVoteDev(const TIntV& ElecIdV, const TStr& OutFNm, const TStr& Desc) const {
THash<TInt, TMom> MomH;
TFltV AvgVoteV;
for (int i = 0; i < ElecIdV.Len(); i++) {
GetElec(ElecIdV[i]).GetAvgVoteDevOt(AvgVoteV, true);
for (int v = 0; v < AvgVoteV.Len(); v++) {
MomH.AddDat(v+1).Add(AvgVoteV[v]); }
}
TGnuPlot::PlotValMomH(MomH, "voteDev-"+OutFNm, TStr::Fmt("%s. %d elections", Desc.CStr(), ElecIdV.Len()),
"n (vote index, time)", "Deviation of the running average", gpsAuto, gpwLinesPoints, true, false, false, false, false);
MomH.SortByKey();
for (int v = 0; v < MomH.Len(); v+=10) {
printf(" %d\t%g\n", v, MomH[v].GetWgt());
}
}
void TWikiElecBs::PlotAvgSupFrac(const TIntV& ElecIdV, const TStr& OutFNm, const TStr& Desc) const {
THash<TInt, TMom> MomH;
TFltV AvgVoteV;
for (int i = 0; i < ElecIdV.Len(); i++) {
TWikiVoteV VoteV;
GetElec(ElecIdV[i]).GetVotesOt(VoteV);
for (int v = 0; v < VoteV.Len(); v++) {
MomH.AddDat(v+1).Add(VoteV[v].GetVote()==1?1:0); }
}
TGnuPlot::PlotValMomH(MomH, "voteFrac-"+OutFNm, TStr::Fmt("%s. %d elections", Desc.CStr(), ElecIdV.Len()),
"T (vote index, time)", "Fraction of all votes casted at time T that were supporting", gpsAuto, gpwLinesPoints, true, false, false, false, false);
}
void TWikiElecBs::PlotOutcomes(const TStr& OutFNm) const {
TWikiVoteV VoteV;
TIntV UIdV; GetEIdByVotes(UIdV);
TGnuPlot GP("votes-otime3-0"), GP2("votes-otime4-0");
for (int u = 0; u < 100; u++) {
const TWikiElec& E = GetElec(UIdV[u]);
E.GetVotesOt(VoteV, true);
const int b = VoteV[0].GetTm().GetAbsSecs();
TFltPrV FracV, FracV2;
int pos=0, neg=0;
for (int v = 0; v < VoteV.Len(); v++) {
if (VoteV[v].GetVote()==1) { pos++; }
else if (VoteV[v].GetVote()==-1) { neg++; } else { continue; }
FracV.Add(TFltPr(v, pos/double(pos+neg)));
//if (v < 10) { continue; }
FracV2.Add(TFltPr(v/double(VoteV.Len()), pos/double(pos+neg)));
}
GP.AddPlot(FracV, gpwLines);
GP2.AddPlot(FracV2, gpwLines);
if ((u+1) % 10 == 0) {
GP.SavePng();
GP2.SavePng();
GP = TGnuPlot(TStr::Fmt("votes-otime3-%d", u/10));
GP2 = TGnuPlot(TStr::Fmt("votes-otime4-%d", u/10));
}
}
GP.SavePng();
GP2.SavePng();
}
void TWikiElecBs::PlotSupFracVsElecLen(const TStr& OutFNm) const {
THash<TInt, TMom> ElecMom;
THash<TInt, TMom> ElecMom5;
THash<TInt, TMom> ElecMom10;
for (int e = 0; e < Len(); e++) {
ElecMom.AddDat(GetElec(e).Len()).Add(GetElec(e).GetFracSup());
ElecMom5.AddDat(5*(GetElec(e).Len()/5)).Add(GetElec(e).GetFracSup());
ElecMom10.AddDat(10*(GetElec(e).Len()/10)).Add(GetElec(e).GetFracSup());
}
TGnuPlot::PlotValMomH(ElecMom, "fracSupLen-"+OutFNm, "Bucket size 1", "Number of votes in the election", "Final fraction of support votes");
TGnuPlot::PlotValMomH(ElecMom5, "fracSupLen-"+OutFNm+"5", "Bucket size 5", "Number of votes in the election", "Final fraction of support votes");
TGnuPlot::PlotValMomH(ElecMom10, "fracSupLen-"+OutFNm+"10", "Bucket size 10", "Number of votes in the election", "Final fraction of support votes");
}
void TWikiElecBs::PlotSupOpp(const TStr& OutFNm) const {
/*TWikiVoteV VoteV;
TIntV UIdV; GetEIdByVotes(UIdV);
TGnuPlot GP("votes-posneg2-00");
TVec<TMom> SupV, OppV;
THash<TFlt, TMom> SupH;
for (int u = 0; u < 2000; u++) {
const TWikiElec& E = GetElec(UIdV[u]);
E.GetVotesOt(VoteV, true);
//printf("%d\t%d\t%d\n", PON.Val1, PON.Val2, PON.Val3);
TFltPrV SupOppV;
int pos=0, neg=0;
for (int v = 0, cnt=0; v < VoteV.Len(); v++) {
if (VoteV[v].GetVote()==1) { pos++; }
else if (VoteV[v].GetVote()==-1) { neg++; } else { continue; }
//SupOppV.Add(TFltPr(pos, neg));
SupOppV.Add(TFltPr(pos/double(PON.Val1), neg/double(PON.Val2)));//2
while (SupV.Len() <= cnt) { SupV.Add(); OppV.Add(); }
SupV[cnt].Add(pos);
OppV[cnt].Add(neg);
if (PON.Val1!=0 && PON.Val2!=0) {
SupH.AddDat(TMath::Round(pos/double(PON.Val1), 1)).Add(neg/double(PON.Val2)); }
cnt++;
}
//GP.AddPlot(SupOppV, gpwLines);
if ((u+1) % 10 == 0) {
//GP.SetXRange(0,1); GP.SetYRange(0,1);
//GP.AddPlot(TIntPrV::GetV(TIntPr(0,0), TIntPr(1,1)), gpwLines, "", "lw 3");
//GP.SavePng();
//GP = TGnuPlot(TStr::Fmt("votes-posneg2-%02d", u/10));
}
}
GP.SavePng();
TFltPrV AvgV, MedV;
for (int i = 0; i < SupV.Len(); i++) {
SupV[i].Def(); OppV[i].Def();
AvgV.Add(TFltPr(SupV[i].GetMean(), OppV[i].GetMean()));
MedV.Add(TFltPr(SupV[i].GetMedian(), OppV[i].GetMedian()));
}
TGnuPlot::PlotValV(AvgV, "votes-posneg-avg", "", "","", gpsAuto, false, gpwLines);
TGnuPlot::PlotValV(MedV, "votes-posneg-median", "", "","", gpsAuto, false, gpwLines);
AvgV.Clr(); MedV.Clr(); SupH.SortByKey();
for (int i = 0; i < SupH.Len(); i++) {
SupH[i].Def();
AvgV.Add(TFltPr(SupH.GetKey(i), SupH[i].GetMean()));
MedV.Add(TFltPr(SupH.GetKey(i), SupH[i].GetMedian()));
}
TGnuPlot::PlotValV(AvgV, "votes-posneg2-avg", "", "","", gpsAuto, false, gpwLines);
TGnuPlot::PlotValV(MedV, "votes-posneg2-median", "", "","", gpsAuto, false, gpwLines);
// */
}
void TWikiElecBs::PlotVoteDistr(const TStr& OutFNm) const {
TWikiVoteV VoteV;
TIntV UIdV; GetEIdByVotes(UIdV);
TVec<TMom> SupV, OppV;
THash<TInt, TIntH> PosH, NegH;
for (int u = 0; u < 2000; u++) {
const TWikiElec& E = GetElec(UIdV[u]);
const TIntTr PON = E.GetVotes(true);
if ((PON.Val1+2*PON.Val2) < 50) {
PosH.AddDat((PON.Val1+PON.Val2)/10).AddDat((PON.Val1))++;
NegH.AddDat((PON.Val1+PON.Val2)/10).AddDat((PON.Val1-PON.Val2))++;
printf("%d ", PON.Val1+PON.Val2);
}
//int pos=0, neg=0;
/*for (int v = 0, cnt=0; v < VoteV.Len(); v++) {
if (VoteV[v].GetVote()==1) { pos++; }
else if (VoteV[v].GetVote()==-1) { neg++; } else { continue; }
if ((pos+neg) % 5 == 0 && (pos+neg) < 100) {
PosH.AddDat((pos+neg)/10).AddDat((pos-neg))++;
NegH.AddDat((pos+neg)/10).AddDat((neg))++;
}
}*/
}
PosH.SortByKey(); NegH.SortByKey();
for (int i = 0; i < PosH.Len(); i++) {
TGnuPlot GP(TStr::Fmt("voteX-distr%02d", PosH.GetKey(i)));
TFltPrV PrV1, PrV2;
IAssert(PosH.GetKey(i) == NegH.GetKey(i));
TIntH& CntH1 = PosH[i]; CntH1.SortByKey();
TIntH& CntH2 = NegH[i]; CntH2.SortByKey();
for (int j = 0; j < CntH1.Len(); j++) {
PrV1.Add(TFltPr(CntH1.GetKey(j).Val, CntH1[j].Val)); }
for (int j = 0; j < CntH2.Len(); j++) {
PrV2.Add(TFltPr(CntH2.GetKey(j).Val, CntH2[j].Val)); }
GP.AddPlot(PrV1, gpwLinesPoints, "Pos");
//GP.AddPlot(PrV2, gpwLinesPoints, "Neg");
GP.AddCmd("set yzeroaxis lt -1");
GP.SavePng();
}
}
// nodes are users that voted on, edges are who voted on whom
// take only users successfully promoted for adminship
PSignNet TWikiElecBs::GetAdminUsrVoteNet() const {
TIntV UIdV;
GetElecAdminUsrV(UIdV);
return GetVoteNet(UIdV);
}
// nodes are users that voted on, edges are who voted on whom
// take only users who went up for promotion
PSignNet TWikiElecBs::GetElecUsrVoteNet() const {
TIntV UIdV;
GetElecUsrV(UIdV);
return GetVoteNet(UIdV);
}
PSignNet TWikiElecBs::GetAllUsrVoteNet() const {
TIntV UIdV;
GetUsrV(UIdV);
return GetVoteNet(UIdV);
}
// nodes are users that voted on, edges are who voted on whom
PSignNet TWikiElecBs::GetVoteNet(const TIntV& UsrIdV) const {
TIntSet UsrSet;
for (int u = 0; u < UsrIdV.Len(); u++) {
UsrSet.AddKey(UsrIdV[u]);
}
PSignNet Net = TSignNet::New();
THash<TIntPr, TStr> EdgeElecH;
for (int e = 0; e < Len(); e++) {
const TWikiElec& FullE = GetElec(e);
const int Dst = FullE.GetUId();
if (! UsrSet.IsKey(Dst)) { continue; }
TWikiElec NewElec;
FullE.GetOnlyVotes(NewElec, true);
for (int v = 0; v < NewElec.Len(); v++) {
const int Src = NewElec[v].GetUId();
if (! UsrSet.IsKey(Src)) { continue; }
if (Src == Dst) { continue; }
if (! Net->IsNode(Dst)) {
Net->AddNode(Dst); }
if (! Net->IsNode(Src)) {
Net->AddNode(Src); }
if (Net->IsEdge(Src, Dst)) { // some edges will already exis (as people go for election multiple times)
//TStr oldRfa = EdgeElecH.GetDat(TIntPr(Src, Dst));
//printf("Edge exists: %s %s \t\t %d --> %d \tvote %d -- %d\n", oldRfa.CStr(),
// FullE.RfaTitle.CStr(), Src, Dst, Net->GetEDat(Src, Dst), NewElec[v].GetVote());
//FullE.Dump(UsrH);
}
//EdgeElecH.AddDat(TIntPr(Src, Dst), FullE.RfaTitle);
Net->AddEdge(Src, Dst, NewElec[v].GetVote());
}
}
return Net;
}
void TWikiElecBs::GetOnlyVoteElecBs(TWikiElecBs& NewElecBs, const bool& OnlySupOpp) const {
NewElecBs.UsrH = UsrH;
NewElecBs.ElecV = ElecV;
for (int e = 0; e < ElecV.Len(); e++) {
ElecV[e].GetOnlyVotes(NewElecBs.ElecV[e], OnlySupOpp); // only keep only actual votes
}
}
bool TWikiElecBs::AddElecRes(const TWikiMetaHist& WMH, const THash<TStr, TStr>& UsrMapH, const THash<TStr, TWikiElecBs::TElecSum>& ElecSumH) {
if (! WMH.Title.IsPrefix("Wikipedia:Requests_for_adminship/")) { return false; }
const int b = WMH.Title.SearchCh('/')+1;
const int e = WMH.Title.SearchCh('/', b+1)-1;
TChA RfaTitle = WMH.Title.GetSubStr(b, e>b?e:TInt::Mx);
TWikiElec WikiElec(-1, WMH.RevTm); // time of revision
ParseVotes(WMH, UsrMapH, WikiElec);
WikiElec.SetIsVoteFlag();
WikiElec.RfaTitle = RfaTitle;
TIntTr V = WikiElec.GetVotes();
// custom ifs to correct errors
if (RfaTitle.IsSuffix("_Couriano")) { RfaTitle = "Couriano"; } // J sk _Couriano --> Couriano
if (ElecSumH.IsKey(RfaTitle)) {
const TElecSum& ElSum = ElecSumH.GetDat(RfaTitle);
WikiElec.IsSucc = true;
TChA U = ElSum.Usr;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
WikiElec.UsrId = AddUsr(ElSum.Usr.CStr()); // is lower case
if (! ElSum.Bureaucrat.Empty()) {
TChA U = ElSum.Bureaucrat;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
WikiElec.BurUId = AddUsr(U);
}
if (! ElSum.NominatedBy.Empty()) {
TChA U = ElSum.NominatedBy;
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
WikiElec.NomUId = AddUsr(U);
}
if (abs(V.Val1-ElSum.Sup) > 0) { printf("SUP VOTES: %d != %d\n", V.Val1, ElSum.Sup); }
if (abs(V.Val2-ElSum.Neu) > 0) { printf("NEU VOTES: %d != %d\n", V.Val2, ElSum.Neu); }
if (abs(V.Val3-ElSum.Opp) > 0) { printf("OPP VOTES: %d != %d\n", V.Val3, ElSum.Opp); }
//if ((abs(V.Val1-ElSum.Sup)>(2+V.Val1/10)) || (abs(V.Val2-ElSum.Neu)>(2+V.Val2/10)) || (abs(V.Val3-ElSum.Opp)>(2+V.Val3/10)) ) {
// WikiElec.Dump(UsrH);
// FILE* F=fopen("page.html","wt"); fprintf(F, "%s",WMH.Text.CStr()); fclose(F);
// return false;
//}
} else {
TChA U = RfaTitle.ToLc(); // is lower case
if (UsrMapH.IsKey(U)) { U = UsrMapH.GetDat(U); }
WikiElec.UsrId = AddUsr(U); // is lower case
}
if (V.Val1+V.Val2+V.Val3 == 0) {
printf("no votes\n"); return false;
}
// good election, add to the set
ElecV.Add(WikiElec);
return true;
}
int TWikiElecBs::GetWikiTxtLen(char* LineStr) {
int Len=0;
for (char *ch=LineStr+1; *ch != NULL; ch++) {
if (TCh::IsAlNum(*ch)) { Len++; }
if (*ch=='[' && *(ch-1)=='[') {
while (*ch && *ch!=']' && *(ch-1)!=']') { ch++; }
}
}
return Len;
}
void TWikiElecBs::LoadElecSumTxt(const TStr& FNm, THash<TStr, TWikiElecBs::TElecSum>& ElecSumH) {
ElecSumH.Clr();
for (TSsParser SS(FNm, ssfTabSep); SS.Next(); ) {
IAssert(SS.Len() == 9);
TElecSum& S = ElecSumH.AddDat(SS[1]); // RfA title
S.Usr = SS[0]; S.Usr.ToLc();
S.RfA = SS[1];
S.Sup = SS.GetInt(2);
S.Opp = SS.GetInt(3);
S.Neu = SS.GetInt(4);
S.NominatedBy = SS[7]; S.NominatedBy.ToLc();
S.Bureaucrat = SS[8]; S.Bureaucrat.ToLc();
}
}
bool EndOfSection(char* Line, const TStr& WhatStr) {
if (Line[0]=='#' || Line[0]==':') { return false; }
TChA LnStr(Line);
LnStr.ToTrunc();
// support
if (LnStr.SearchStr(TStr::Fmt("'''%s'''", WhatStr.CStr()))!=-1) { return true; }
if (LnStr.SearchStr(TStr::Fmt("====%s====", WhatStr.CStr()))!=-1) { return true; }
if (LnStr.SearchStr(TStr::Fmt("==== %s ====", WhatStr.CStr()))!=-1) { return true; }
if (LnStr.SearchStr(TStr::Fmt("'''%s:'''", WhatStr.CStr()))!=-1) { return true; }
if (LnStr.SearchStr(TStr::Fmt("====%s:====", WhatStr.CStr()))!=-1) { return true; }
if (LnStr.IsPrefix(TStr::Fmt("; %s", WhatStr.CStr()))) { return true; }
if (LnStr.IsPrefix(TStr::Fmt(";%s", WhatStr.CStr()))) { return true; }
if (LnStr==TStr::Fmt("%s", WhatStr.CStr())) { return true; }
if (LnStr==TStr::Fmt("%s:", WhatStr.CStr())) { return true; }
return false;
}
void TWikiElecBs::ParseVotes(const TWikiMetaHist& WMH, const THash<TStr, TStr>& UsrMapH, TWikiElec& WikiElec) {
TVec<char *> LineV; TChA Tmp = WMH.Text;
Tmp.ToLc();
TStrUtil::SplitLines(Tmp, LineV);
int l = 0, goodVote=0;
int NSup=0, NOpp=0, NNeu=0;
for (; l < LineV.Len(); l++) {
if (EndOfSection(LineV[l], "support")) { l++; break; }
// parse "(31/1/0) ending"
char *vote=strstr(LineV[l], ") end");
if (vote == NULL) { vote=strstr(LineV[l], ") end"); }
if (vote != NULL && TCh::IsNum(*(vote-1)) && NSup==-1) {
*vote=0; vote--;
while(TCh::IsNum(*vote)) { vote--; }
if (*vote == '/') {
NNeu = atoi(vote+1); *vote=0; vote--;
while(TCh::IsNum(*vote)) { vote--; }
if (*vote == '/') {
NOpp = atoi(vote+1); *vote=0; vote--;
while(TCh::IsNum(*vote)) { vote--; }
if (*vote == '(') { NSup = atoi(vote+1); } }
} }//*/
}
TChA Usr; TSecTm Tm; int Indent;
// support votes
for (; l < LineV.Len(); l++) {
if(GetUsrTm(LineV[l], Usr, Tm, Indent)) { goodVote++;
if (UsrMapH.IsKey(Usr)) { Usr = UsrMapH.GetDat(Usr); }
WikiElec.VoteV.Add(TWikiVote(AddUsr(Usr), +1, Indent, GetWikiTxtLen(LineV[l]), Tm));
}
if (EndOfSection(LineV[l], "oppose")) { l++; break; }
}
// oppose votes
for (; l < LineV.Len(); l++) {
if(GetUsrTm(LineV[l], Usr, Tm, Indent)) { goodVote++;
if (UsrMapH.IsKey(Usr)) { Usr = UsrMapH.GetDat(Usr); }
WikiElec.VoteV.Add(TWikiVote(AddUsr(Usr), -1, Indent, GetWikiTxtLen(LineV[l]), Tm));
}
if (EndOfSection(LineV[l], "neutral")) { l++; break; }
}
// neutral votes
for (; l < LineV.Len(); l++) {
if(GetUsrTm(LineV[l], Usr, Tm, Indent)) { goodVote++;
if (UsrMapH.IsKey(Usr)) { Usr = UsrMapH.GetDat(Usr); printf("u"); }
WikiElec.VoteV.Add(TWikiVote(AddUsr(Usr), 0, Indent, GetWikiTxtLen(LineV[l]), Tm));
}
if (LineV[l][0]!='#' && (strstr(LineV[l], "'''comments")!=NULL || strstr(LineV[l], "'''no vote")!=NULL
|| strstr(LineV[l], "====")!=NULL || strstr(LineV[l], ";comments")!=NULL || strstr(LineV[l], "; comments")!=NULL ||
strcmp(LineV[l],"comment")==0 || strcmp(LineV[l],"comments")==0)) { l++; break; }
}
// sort votes over time
//WikiElec.VoteV.Sort(); // DON'T SORT so that the order is not lost
// dump the post if difference > 500 votes
const TIntTr SON = WikiElec.GetVotes(true);
if (SON.Val1+SON.Val2+SON.Val3 > 100 && (SON.Val1==0 || SON.Val2==0)) {
//printf("EXTRACT %s (text val==extracted vals): %d=%d %d=%d %d=%d\n", WMH.Title.CStr(), NSup, SON.Val1, NOpp, SON.Val2, NNeu, SON.Val3);
//WMH.Dump(true);
}
}
void TWikiElecBs::SetUserIdFromRfa() {
THash<TChA, TChA> RfaUsrMapH;
RfaUsrMapH.AddDat("White_Cat_(01)", "White_Cat");
RfaUsrMapH.AddDat("White_Cat_(02)", "White_Cat");
RfaUsrMapH.AddDat("White_Cat_(03)", "White_Cat");
RfaUsrMapH.AddDat("White_Cat_(04)", "White_Cat");
RfaUsrMapH.AddDat("Computerjoe_(4)", "Computerjoe");
RfaUsrMapH.AddDat("Purplefeltangel2", "Purplefeltangel");
RfaUsrMapH.AddDat("Haham_Hanuka_(3)", "Haham_Hanuka");
RfaUsrMapH.AddDat("dbertman_(archive)", "dbertman");
RfaUsrMapH.AddDat("Agentsoo_(archive)", "Agentsoo");
RfaUsrMapH.AddDat("Guanaco3", "Guanaco");
RfaUsrMapH.AddDat("Brendenhull2", "Brendenhull");
RfaUsrMapH.AddDat("Xerocs2", "Xerocs");
RfaUsrMapH.AddDat("Wikiwoohoo2", "Wikiwoohoo");
RfaUsrMapH.AddDat("Folajimi2", "Folajimi");
RfaUsrMapH.AddDat("FuriousFreddy_r1", "FuriousFreddy");
RfaUsrMapH.AddDat("General_Eisenhower3", "General_Eisenhower");
RfaUsrMapH.AddDat("HolyRomanEmperor2", "HolyRomanEmperor");
RfaUsrMapH.AddDat("HolyRomanEmperor3", "HolyRomanEmperor");
RfaUsrMapH.AddDat("HolyRomanEmperor3a", "HolyRomanEmperor");
RfaUsrMapH.AddDat("Jet123_(2nd_nom)", "Jet123");
RfaUsrMapH.AddDat("Natl1_(2nd_nom)", "Natl1");
RfaUsrMapH.AddDat("NickCatal2", "NickCatal");
RfaUsrMapH.AddDat("P.B._Pilhet_2nd_Nomination", "P.B._Pilhet");
RfaUsrMapH.AddDat("Patchouli2", "Patchouli");
RfaUsrMapH.AddDat("Patchouli3", "Patchouli");
RfaUsrMapH.AddDat("The_Wookieepedian2", "The_Wookieepedian");
RfaUsrMapH.AddDat("Son_of_a_Peach_II", "Son_of_a_Peach");
RfaUsrMapH.AddDat("SVera1NY_(second_nomination)", "SVera1NY");
RfaUsrMapH.AddDat("Tellyaddict2", "Tellyaddict");
RfaUsrMapH.AddDat("Tenebrae2", "Tenebrae");
RfaUsrMapH.AddDat("Poccil2", "Poccil");
RfaUsrMapH.AddDat("Purplefeltangel2", "Purplefeltangel");
RfaUsrMapH.AddDat("Ramsquire2", "Ramsquire");
RfaUsrMapH.AddDat("ScienceApologist2", "ScienceApologist");
RfaUsrMapH.AddDat("Jor2", "Jor");
for (int e = 0; e < Len(); e++) {
TWikiElec& E = GetElec(e);
if (E.IsSucc()) { continue; }
TChA Rfa = E.RfaTitle;
const int l = Rfa.Len();
TChA User;
if (l>2 && Rfa[l-2]=='_' && TCh::IsNum(Rfa[l-1])) { User = Rfa.GetSubStr(0, l-3); } // _[num]
else if (Rfa.IsSuffix(".08") || Rfa.IsSuffix(".09") || Rfa.IsSuffix(".10")) { User = Rfa.GetSubStr(0, l-4); }
else if (Rfa.IsSuffix("_(renomination)")) { User = Rfa.GetSubStr(0, l-(int)strlen("_(renomination)")-1); }
else if (Rfa.IsSuffix("_(2)")) { User = Rfa.GetSubStr(0, l-5); }
else if (Rfa.IsSuffix("_(2nd)")) { User = Rfa.GetSubStr(0, l-7); }
else if (Rfa.IsSuffix("_(2nd_nomination)")) { User = Rfa.GetSubStr(0, l-(int)strlen("_(2nd_nomination)")-1); }
else if (RfaUsrMapH.IsKey(Rfa)) { User = RfaUsrMapH.GetDat(Rfa); }
else { continue; }
User.ToLc();
printf("%20s\t->\t%s\n", Rfa.CStr(), User.CStr());
E.UsrId = AddUsr(User.CStr());
}
}
void TWikiElecBs::Dump() const {
int v=0, Sup=0, Opp=0, Neu=0;
int VSup=0, VOpp=0, VNeu=0;
for (int e=0; e< Len(); e++) {
v += GetElec(e).Len();
TIntTr Votes = GetElec(e).GetVotes(false);
Sup += Votes.Val1; Neu += Votes.Val2; Opp += Votes.Val3;
Votes = GetElec(e).GetVotes(true);
VSup += Votes.Val1; VNeu += Votes.Val2; VOpp += Votes.Val3;
}
printf("%5d users, %3d elections, %d all votes (%d/%d/%d)\n", UsrH.Len(), Len(), v, Sup, Opp, Neu);
printf(" %d all votes (%d/%d/%d)\n", VSup+VOpp+VNeu, VSup, VOpp, VNeu);
// election outcome for admins vs. non-admins
TIntSet AdminSet, NAdminSet;
TMom SupA, OppA, NeuA, SupNA, OppNA, NeuNA, ASupFrac, NASupFrac;
TFltIntPrV AElecV, NAElecV;
int nsucc=0;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
const TIntTr V = E.GetVotes(true);
double SupFrac = V.Val1+V.Val3>0 ? V.Val1/double(V.Val1+V.Val3) : 0;
if (V.Val1+V.Val3 == 0) { continue; }
if (E.IsSucc) {
AdminSet.AddKey(E.UsrId);
SupA.Add(V.Val1()); NeuA.Add(V.Val2()); OppA.Add(V.Val3());
AElecV.Add(TFltIntPr(SupFrac, e));
ASupFrac.Add(SupFrac);
nsucc++;
} else {
NAdminSet.AddKey(E.UsrId());
SupNA.Add(V.Val1()); NeuNA.Add(V.Val2()); OppNA.Add(V.Val3());
NAElecV.Add(TFltIntPr(SupFrac, e));
NASupFrac.Add(SupFrac);
}
}
printf("succ elecs %d\n", nsucc);
SupA.Def(); OppA.Def(); NeuA.Def(); SupNA.Def(); OppNA.Def(); NeuNA.Def();
ASupFrac.Def(); NASupFrac.Def();
printf("succ elecs vs. failed elecs: %d admins. Votes:\n", AdminSet.Len());
printf(" sup: %.1f : %.1f\n", SupA.GetMean(), SupNA.GetMean());
printf(" neu: %.1f : %.1f\n", NeuA.GetMean(), NeuNA.GetMean());
printf(" fail: %.1f : %.1f\n", OppA.GetMean(), OppNA.GetMean());
printf(" support fraction: %f : %f\n", ASupFrac.GetMean(), NASupFrac.GetMean());
// votes casted by admins/non-admins/othes
TInt ASup, AOpp, NASup, NAOpp, OSup, OOpp, AllSup, AllOpp; // sup/opp votes by admins, non-admins, others
TInt AEl, NAEl, OEl;
TIntPrV TmV;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
TWikiElec NewElec; E.GetOnlyVotes(NewElec, true);
bool IsA=false, IsNA=false, IsO=false;
TmV.Add(TIntPr(E.GetTm().GetAbsSecs(), e));
for (int v = 0; v < NewElec.Len(); v++) {
const int vote = NewElec[v].GetVote();
const int uid = NewElec[v].GetUId();
if (AdminSet.IsKey(uid)) {
if (vote == 1) { ASup++; } else { AOpp++; }
IsA=true; }
else if (NAdminSet.IsKey(uid)) {
if (vote == 1) { NASup++; } else { NAOpp++; }
IsNA=true; }
else {
if (vote == 1) { OSup++; } else { OOpp++; }
IsO=true; }
if (vote == 1) { AllSup++; }
if (vote == -1) { AllOpp++; }
}
if (IsA) { AEl++; }
if (IsNA) { NAEl++; }
if (IsO) { OEl++; }
}
TmV.Sort();
printf("elections from:\t%s\n\t%s\n", TSecTm(TmV[0].Val1()).GetStr().CStr(), TSecTm(TmV.Last().Val1()).GetStr().CStr());
for (int i = 0; i <100; i++) { printf("%d\n", TmV[i].Val2); }
for (int i = TmV.Len()-100; i <TmV.Len(); i++) { printf("%d\n", TmV[i].Val2); }
TIntV UsrV; GetUsrV(UsrV);
printf("voters: %d\n", UsrV.Len());
printf("votes by:\n");
printf(" all: %5d : %5d = %f elecs: %d users: %d\n", AllSup, AllOpp, AllSup/double(AllSup+AllOpp), Len(), UsrV.Len());
printf(" admins: %5d : %5d = %f elecs: %d users: %d\n", ASup, AOpp, ASup/double(ASup+AOpp), AEl, AdminSet.Len());
printf(" non-admins: %5d : %5d = %f elecs: %d users: %d\n", NASup, NAOpp, NASup/double(NASup+NAOpp), NAEl, NAdminSet.Len());
printf(" others: %5d : %5d = %f elecs: %d users: %d\n\n", OSup, OOpp, OSup/double(OSup+OOpp), OEl, UsrH.Len()-AdminSet.Len()-NAdminSet.Len());
/*printf("\n10 admin elections with lowest support:\n");
AElecV.Sort(true);
for (int e =0; e < 100; e++) {
GetElec(AElecV[e].Val2).Dump(UsrH); }
printf("\n10 non-admin elections with highest support:\n");
NAElecV.Sort(false);
for (int e =0; e < 100; e++) {
GetElec(NAElecV[e].Val2).Dump(UsrH); }
// */
}
// save: eid isSucc\tUsers that votes
void TWikiElecBs::SaveElecUserVotes(const TStr& OutFNm) const {
TIntSet USet;
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10) { continue; }
for (int v = 0; v < E.Len(); v++) {
USet.AddKey(E[v].GetUId()); }
}
FILE *F = fopen(OutFNm.CStr(), "wt");
fprintf(F, "IsSucc");
for (int u = 0; u < USet.Len(); u++) {
fprintf(F, "\tu%d", USet[u]);
}
fprintf(F, "\n");
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
if (E.Len() < 10) { continue; }
TIntSet Voters;
for (int v = 0; v < E.Len(); v++) {
Voters.AddKey(E[v].GetUId()); }
fprintf(F, "%d", E.IsSucc?1:0);
for (int u = 0; u < USet.Len(); u++) {
if (Voters.IsKey(USet[u])) { fprintf(F, "\t1"); }
else { fprintf(F, "\t0"); }
}
fprintf(F, "\n");
}
fclose(F);
}
void TWikiElecBs::SaveTxt(const TStr& OutFNm) {
SortVotesByTm();
FILE *F = fopen(OutFNm.CStr(), "wt");
fprintf(F, "# Wikipedia elections (http://cs.stanford.edu/people/jure/pubs/triads-chi10.pdf). Data format:\n");
fprintf(F, "# E: is election succesful (1) or not (0)\n");
fprintf(F, "# T: time election was closed\n");
fprintf(F, "# U: user id (and username) of editor that is being considered for promotion\n");
fprintf(F, "# N: user id (and username) of the nominator\n");
fprintf(F, "# V: <vote(1:support, 0:neutral, -1:oppose)> <user_id> <time> <username>\n");
for (int e = 0; e < Len(); e++) {
const TWikiElec& E = GetElec(e);
//if (E.Len() < 10) { continue; }
fprintf(F, "E\t%d\n", E.IsSucc?1:0);
fprintf(F, "T\t%s\n", E.ElecTm.GetYmdTmStr().CStr());
fprintf(F, "U\t%d\t%s\n", E.UsrId, GetUsr(E.UsrId));
fprintf(F, "N\t%d\t%s\n", E.NomUId, E.NomUId==-1?"UNKNOWN":GetUsr(E.NomUId));
for (int v = 0; v < E.Len(); v++) {
if (! E[v].IsVote()) { continue; }
fprintf(F, "V\t%d\t%d\t%s\t%s\n", E[v].GetVote(), E[v].GetUId(), E[v].GetTm().GetYmdTmStr().CStr(), GetUsr(E[v].GetUId()));
}
fprintf(F, "\n");
}
fclose(F);
}
void TWikiElecBs::SaveOnlyVotes() {
TWikiElecBs NewElBs;
GetOnlyVoteElecBs(NewElBs, true);
NewElBs.SortVotesByTm();
TStrSet RfaSet;
for (int e = 0; e < NewElBs.Len(); e++) {
TWikiElec& E = NewElBs.GetElec(e);
if (RfaSet.IsKey(E.RfaTitle)) {
// add _# to RFA until it is unique
for (int i = 2; ; i++) {
TStr NewRfa = TStr::Fmt("%s_%d", E.RfaTitle.CStr(), i);
if (! RfaSet.IsKey(NewRfa)) {
printf(" %s --> %s\n", E.RfaTitle.CStr(), NewRfa.CStr());
E.RfaTitle= NewRfa;
break;
}
}
}
RfaSet.AddKey(E.RfaTitle);
}
NewElBs.Save(TZipOut("wikiElec-Votes.ElecBs3.rar"));
}
/*void TWikiVotes::PlotAll() {
TGnuPlot::PlotValCntH(SupCntH, "cnt-support");
TGnuPlot::PlotValCntH(OppCntH, "cnt-oppose");
TGnuPlot::PlotValCntH(NeuCntH, "cnt-neutral");
THash<TIntPr, TInt> PosNegH;
for (int i = 0; i < VoteH.Len(); i++) {
const TVec<TWikiVote>& V = VoteH[i];
int pos=0, neg=0;
for (int v = 0; v < V.Len(); v++) {
if (V[v].GetVote() == 1) { pos++; }
else if (V[v].GetVote() == -1) { neg++; }
}
PosNegH.AddKey(TIntPr(pos, neg));
}
TIntPrV PrV; PosNegH.GetKeyV(PrV);
TGnuPlot::PlotValV(PrV, "pos-neg-votes", "", "positive", "negative", gpsAuto, false, gpwPoints);
}*/
// parse: #:: tralala [[User:Renesis13|Renesis]] ([[User talk:Renesis13|talk]]) 21:39, 29 November 2006 (UTC)
bool TWikiElecBs::GetUsrTm(char* LineStr, TChA& Usr, TSecTm& Tm, int& Indent) {
TChA TmpLine=LineStr;
TChA SearchStr = "[[user:";
char *UsrId = NULL;
// find last mention of a user in a line
for (char *next=LineStr; next=strstr(next, SearchStr.CStr()); ) {
UsrId=next; next++; }
if (UsrId == NULL) {
SearchStr = "[[user talk:";
for (char *next=LineStr; next=strstr(next, SearchStr.CStr()); ) {
UsrId=next; next++; }
}
if (UsrId == NULL) {
SearchStr = "[[user_talk:";
for (char *next=LineStr; next=strstr(next, SearchStr.CStr()); ) {
UsrId=next; next++; }
}
if (UsrId == NULL) {
return false;
}
UsrId += SearchStr.Len();
while (*UsrId && TCh::IsWs(*UsrId)) { UsrId++; }
char *c = UsrId;
while (*c && *c!='|' && *c!=']' && *c!='/' && *c!='#' && *c!=' ' && *c!='&') {
if (*c==' ') { *c='_'; }
c++;
}
*c = 0; c++;
Usr = UsrId; Usr.ToLc();
// find date " (UTC)---- 19:22:32, 16 Nov 2004 (UTC)"
char *utc = strstr(c, " (utc)");
if (utc == NULL) { return false; }
while (strstr(utc+1, "(utc)")!=NULL) { utc = strstr(utc+1, "(utc)"); }
*utc = 0; utc--;
// parse backward, take 5 (YMDHM) fields + until the first space
int FldCnt=0;
char *e = utc;
while (e>c && (*e==' ' || *e=='-' || *e==',')) { e--; }
while(e>c) {
while (e>c && ! (*e==' ' || *e=='-' || *e==',')) { e--; }
if (++FldCnt==4) { break; }
while (e>c && (*e==' ' || *e=='-' || *e==',')) { e--; }
}
e += 1;
if (! TStrUtil::GetTmFromStr(e, Tm)) {
return false; }
// extract indent
Indent=0;
for (char *ch=LineStr; *ch && ! TCh::IsAlNum(*ch); ch++) {
if (*ch == ':' || *ch == '*') { Indent++; }
}
return true;
}
// nodes are people, signed directed edge A->B means that
// A votes on B's promotion and the edge sign tells the vote
/*PWikiVoteNet TWikiElecBs::GetVoteNet() {
PWikiVoteNet Net = TWikiVoteNet::New();
TWikiVoteV VoteV;
TIntV ElecIdV; GetEIdByVotes(ElecIdV, false);
int conflict=0, same=0;
int sup=0, opp=0, neu=0;
for (int u = 0; u < ElecIdV.Len(); u++) {
const TWikiElec& E = GetElec(ElecIdV[u]);
E.GetVotesOt(VoteV, true);
VoteV.Sort(false);
const int DstUId = E.UsrId;
if (! Net->IsNode(DstUId)) { Net->AddNode(DstUId); }
for (int v1 = 0; v1 < VoteV.Len(); v1++) {
const int SrcUId = VoteV[v1].GetUId();
if (VoteV[v1].GetVote() == 0) { neu++; continue; } // skip neutral vote
if (SrcUId == DstUId) { continue; } // skip self votes (about 150)
if (! Net->IsNode(SrcUId)) { Net->AddNode(SrcUId); }
Net->AddEdge(SrcUId, DstUId, VoteV[v1].GetVote());
//Net->AddEdge(SrcUId, DstUId, TIntPr(VoteV[v1].GetVote(), ElecIdV[u]));
if(Net->IsEdge(DstUId, SrcUId)) {
if (Net->GetEDat(SrcUId, DstUId) != Net->GetEDat(DstUId, SrcUId)) { conflict++; }
else { same++; }
}
if (VoteV[v1].GetVote()==1) { sup++; } else { opp++; }
}
}
printf("votes %d users, %d elections: %d/%d/%d\n", UsrH.Len(), UsrElecH.Len(), sup, opp, neu);
printf("both way edges %d, %d edges have same sign, %d opposite sign\n", conflict+same, same, conflict);
printf("net: %d nodes, %d edges\n", Net->GetNodes(), Net->GetEdges());
return Net;
}
/*
// connect nodes that vote on the same matter
// + edges: nodes tend to agree (both vote yes or no), -: nodes tend to disagree
void TWikiElecBs::GetVoteNet(TNodeEdgeNet<TInt, TInt>& Net) {
TWikiVoteV VoteV;
TIntV UIdV; GetUIdByVotes(UIdV);
THash<TIntPr, TIntTr> CmnVoteH;
int sup=0, opp=0, neu=0;
for (int u = 0; u < UIdV.Len(); u++) {
const TWikiElec& E = GetElec(UIdV[u]);
const TIntTr PON = E.GetVotesOt(VoteV, true);
for (int v1 = 0; v1 < VoteV.Len(); v1++) {
for (int v2 = v1+1; v2 < VoteV.Len(); v2++) {
const int uid1= TMath::Mn(VoteV[v1].UId(), VoteV[v2].UId());
const int uid2= TMath::Mx(VoteV[v1].UId(), VoteV[v2].UId());
TIntTr& Vt = CmnVoteH.AddDat(TIntPr(uid1, uid2));
if (VoteV[v1].GetVote() != VoteV[v2].GetVote()) { Vt.Val3++; }
else if (VoteV[v1].GetVote()==1) { Vt.Val1++; }
else if (VoteV[v1].GetVote()==-1) { Vt.Val2++; }
}
if (VoteV[v1].GetVote()==1) { sup++; }
else if (VoteV[v1].GetVote()==-1) { opp++; }
else { neu++; }
}
}
printf("votes %d users, %d elections: %d/%d/%d\n", UsrH.Len(), UsrElecH.Len(), sup, opp, neu);
TIntH CmnSupH, CmnOppH, NotCmnH;
int supedge=0, oppedge=0, potEdges=0;
for (int i = 0; i < CmnVoteH.Len(); i++) {
CmnSupH.AddDat(CmnVoteH[i].Val1)++;
CmnOppH.AddDat(CmnVoteH[i].Val2)++;
NotCmnH.AddDat(CmnVoteH[i].Val3)++;
if (CmnVoteH[i].Val1+CmnVoteH[i].Val2+CmnVoteH[i].Val3 > 10) {
if ((CmnVoteH[i].Val1+CmnVoteH[i].Val2) > 1.5*CmnVoteH[i].Val3) {
//printf("++ %d\t%d\t%d\n", CmnVoteH[i].Val1, CmnVoteH[i].Val2, CmnVoteH[i].Val3);
supedge++;
if (! Net.IsNode(CmnVoteH.GetKey(i).Val1)) { Net.AddNode(CmnVoteH.GetKey(i).Val1); }
if (! Net.IsNode(CmnVoteH.GetKey(i).Val2)) { Net.AddNode(CmnVoteH.GetKey(i).Val2); }
Net.AddEdge(CmnVoteH.GetKey(i).Val1, CmnVoteH.GetKey(i).Val2, -1, TInt(+1));
Net.AddEdge(CmnVoteH.GetKey(i).Val2, CmnVoteH.GetKey(i).Val1, -1, TInt(+1));
}
if ((CmnVoteH[i].Val1+CmnVoteH[i].Val2)*1.5 < CmnVoteH[i].Val3) {
oppedge++;
if (! Net.IsNode(CmnVoteH.GetKey(i).Val1)) { Net.AddNode(CmnVoteH.GetKey(i).Val1); }
if (! Net.IsNode(CmnVoteH.GetKey(i).Val2)) { Net.AddNode(CmnVoteH.GetKey(i).Val2); }
Net.AddEdge(CmnVoteH.GetKey(i).Val1, CmnVoteH.GetKey(i).Val2, -1, TInt(-1));
Net.AddEdge(CmnVoteH.GetKey(i).Val2, CmnVoteH.GetKey(i).Val1, -1, TInt(-1));
}
}
potEdges++;
}
printf("supEdge: %d, oppEdge: %d, potentialEdge: %d\n", supedge, oppedge, potEdges);
printf("net: %d nodes, %d edges\n", Net.GetNodes(), Net.GetEdges());
TGnuPlot::PlotValCntH(CmnSupH, "common-support", "", "common support votes", "count", gpsLog10XY);
TGnuPlot::PlotValCntH(CmnOppH, "common-oppose", "", "common oppose votes", "count", gpsLog10XY);
TGnuPlot::PlotValCntH(NotCmnH, "common-notagree", "", "votes where decision was different", "count", gpsLog10XY);
// count triangles
THash<TIntPr, TInt> EdgeH;
for (TNodeEdgeNet<TInt, TInt>::TEdgeI EI = Net.BegEI(); EI < Net.EndEI(); EI++) {
if (EI() == -1) {
TNodeEdgeNet<TInt, TInt>::TNodeI LN = Net.GetNI(EI.GetSrcNId());
TNodeEdgeNet<TInt, TInt>::TNodeI RN = Net.GetNI(EI.GetDstNId());
if (LN>=RN) { continue; }
for (int n1 = 0; n1 < LN.GetOutDeg(); n1++) {
for (int n2 = 0; n2 < RN.GetOutDeg(); n2++) {
if (LN.GetOutNId(n1) == RN.GetOutNId(n2)) {
const int e1 = Net.GetEDat(LN.GetOutEId(n1));
const int e2 = Net.GetEDat(RN.GetOutEId(n2));
EdgeH.AddDat(TIntPr(TMath::Mn(e1, e2), TMath::Mx(e1, e2)))++;
}
}
}
}
}
TGPlot::PlotDegDistr(Net.GetNEGraph(), "deg-distr", "");
for (int e = 0; e < EdgeH.Len(); e++) {
printf("-1 %2d %2d : %d\n", EdgeH.GetKey(e).Val1, EdgeH.GetKey(e).Val2, EdgeH[e]);
}
}
// nodes are people, signed directed edge A->B means that
// A votes on B's promotion and the edge sign tells the vote
void TWikiElecBs::GetVoteNet2(TNodeEdgeNet<TInt, TInt>& Net) {
TWikiVoteV VoteV;
TIntV UIdV; GetUIdByVotes(UIdV);
THash<TIntPr, TIntTr> CmnVoteH;
int sup=0, opp=0, neu=0;
for (int u = 0; u < UIdV.Len(); u++) {
const TWikiElec& E = GetElec(UIdV[u]);
const TIntTr PON = E.GetVotesOt(VoteV, true);
const int DstUId = E.UsrId;
if (! Net.IsNode(DstUId)) { Net.AddNode(DstUId); }
for (int v1 = 0; v1 < VoteV.Len(); v1++) {
const int SrcUId = VoteV[v1].UId();
if (VoteV[v1].GetVote() == 0) { continue; }
if (! Net.IsNode(SrcUId)) { Net.AddNode(SrcUId); }
//IAssert(Net.IsEdge(SrcUId, DstUId, false));
Net.AddEdge(SrcUId, DstUId, -1, VoteV[v1].GetVote());
Net.AddEdge(DstUId,SrcUId, -1, VoteV[v1].GetVote());
if (VoteV[v1].GetVote()==1) { sup++; }
else {opp++; }
}
}
printf("votes %d users, %d elections: %d/%d/%d\n", UsrH.Len(), UsrElecH.Len(), sup, opp, neu);
printf("net: %d nodes, %d edges\n", Net.GetNodes(), Net.GetEdges());
// count triangles
THash<TIntTr, TInt> EdgeH;
for (TNodeEdgeNet<TInt, TInt>::TEdgeI EI = Net.BegEI(); EI < Net.EndEI(); EI++) {
//if (EI() == -1) {
TNodeEdgeNet<TInt, TInt>::TNodeI LN = Net.GetNI(EI.GetSrcNId());
TNodeEdgeNet<TInt, TInt>::TNodeI RN = Net.GetNI(EI.GetDstNId());
if (LN>=RN) { continue; }
for (int n1 = 0; n1 < LN.GetOutDeg(); n1++) {
for (int n2 = 0; n2 < RN.GetOutDeg(); n2++) {
if (LN.GetOutNId(n1) == RN.GetOutNId(n2)) {
const int e1 = Net.GetEDat(LN.GetOutEId(n1));
const int e2 = Net.GetEDat(RN.GetOutEId(n2));
EdgeH.AddDat(TIntTr(EI(), TMath::Mn(e1, e2), TMath::Mx(e1, e2)))++;
}
}
}
//}
}
printf("sup: %d\n opp: %d\n", sup, opp);
EdgeH.SortByKey(true);
for (int e = 0; e < EdgeH.Len(); e++) {
printf("%2d %2d %2d : %d\n", EdgeH.GetKey(e).Val1, EdgeH.GetKey(e).Val2, EdgeH.GetKey(e).Val3, EdgeH[e]);
}
}*/
/////////////////////////////////////////////////
// Wikipedia Meta parser
// loads processed version of wikipedia prepared by Gueorgi Kossinets
// for each revision the following fields are extracted
// REVISION article_id rev_id article_title timestamp [ip:]username user_id
// CATEGORY list of categories
// IMAGE list of images (each listed as many times as it occurs)
// MAIN, TALK, USER, USER_TALK, OTHER cross-references to pages in other namespaces
// EXTERNAL hyperlinks to pages outside Wikipedia
// TEMPLATE list of all templates (each listed as many times as it occurs)
// COMMENT contains the comments as entered by the author
// MINOR whether the edit was marked as minor by the author
// TEXTDATA word count of revision's plain text
TWikiMetaLoader::TWikiMetaLoader(const TStr& InFNm) {
if (TZipIn::IsZipExt(InFNm.GetFExt())) { SInPt = TZipIn::New(InFNm); }
else if (! InFNm.Empty()) { SInPt = TFIn::New(InFNm); }
else { SInPt = TStdIn::New(); } // empty file name loads from stdin (useful for compressed files)
}
bool TWikiMetaLoader::IsIpAddrUsr() const {
return IsIpAddr(Usr);
}
bool TWikiMetaLoader::Next() {
TSIn& SIn = *SInPt;
static TChA LnStr;
for (int rec=0; SIn.GetNextLn(LnStr); rec++) {
if (! LnStr.IsPrefix("REVISION ")) {
//if (LnStr.Len() > 0) { printf("TWikiMetaLoader::Next[%d]: bad line '%s'\n", rec, LnStr.CStr()); }
continue;
}
TChA Tmp = LnStr;
TVec<char *> FldV; TStrUtil::SplitWords(Tmp, FldV);
if (FldV.Len() != 7) {
//printf("TWikiMetaLoader::Next[%d]: bad line2 '%s'\n", rec, LnStr.CStr());
continue;
}
IAssert(FldV.Len() == 7);
ArticleId = atoi(FldV[1]);
RevisionId = atoi(FldV[2]);
Title = FldV[3];
RevTm = TSecTm::GetDtTmFromStr(FldV[4]);
Usr = FldV[5]; Usr.ToLc(); Usr.ChangeCh(' ', '_'); // usernames are in lower case
UsrId = atoi(FldV[6]);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("CATEGORY"));
CatStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("IMAGE"));
ImgStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("MAIN"));
MainLStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("TALK"));
TalkLStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("USER"));
UserLStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("USER_TALK"));
UserTalkLStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("OTHER"));
OtherLStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("EXTERNAL"));
ExternalLStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("TEMPLATE"));
TemplateStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("COMMENT"));
CommentStr = LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx);
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("MINOR"));
MonorEdit = LnStr[LnStr.SearchCh(' ')+1] == '1';
IAssert(SIn.GetNextLn(LnStr)); IAssert(LnStr.IsPrefix("TEXTDATA"));
RevWrds = atoi(LnStr.GetSubStr(LnStr.SearchCh(' ')+1, TInt::Mx).CStr());
return true;
}
return false;
}
bool TWikiMetaLoader::IsIpAddr(const TChA& Usr) {
if (Usr.IsPrefix("ip:")) { return true; }
int i = 0, Len=Usr.Len();
while (i<Len && TCh::IsNum(Usr[i])) { i++; }
if (! (i<Len && Usr[i]=='.')) { return false; }
i++;
while (i<Len && TCh::IsNum(Usr[i])) { i++; }
if (! (i<Len && Usr[i]=='.')) { return false; }
i++;
while (i<Len && TCh::IsNum(Usr[i])) { i++; }
if (i==Len) { return true; }
return false;
}
/////////////////////////////////////////////////
// Wikipedia pages-meta-history parser
TWikiMetaHist::TWikiMetaHist(const TStr& InFNm) : SInPt(TZipIn::IsZipFNm(InFNm) ? TZipIn::New(InFNm) : TFIn::New(InFNm)), XmlInPt(TXmlParser::New(SInPt)), PageCnt(0) {
printf("Init from %s\n skip till <page>...", InFNm.CStr());
XmlInPt->SkipTillTag("page");
printf("done\n");
}
TWikiMetaHist::TWikiMetaHist(const PSIn& SIn) : SInPt(SIn), XmlInPt() {
}
void TWikiMetaHist::Save(TSOut& SOut) const {
SOut.Save(PageId);
SOut.Save(RevId);
SOut.Save(UsrId);
RevTm.Save(SOut);
Usr.Save(SOut);
Cmt.Save(SOut);
Title.Save(SOut);
Text.Save(SOut);
}
void TWikiMetaHist::Clr() {
PageId = RevId = UsrId = -1;
RevTm = TSecTm();
Usr.Clr(); Cmt.Clr();
Title.Clr(); Text.Clr(); Tmp.Clr();
}
bool TWikiMetaHist::LoadNextBin() {
TSIn& SIn = *SInPt;
if (SIn.Eof()) { Clr(); return false; }
SIn.Load(PageId);
SIn.Load(RevId);
SIn.Load(UsrId);
RevTm.Load(SIn);
Usr.Load(SIn);
Cmt.Load(SIn);
Title.Load(SIn);
Text.Load(SIn);
for (int i = 0; i < Usr.Len(); i++) {
if (Usr[i]==' ') { Usr[i]='_'; }
}
for (int i = 0; i < Title.Len(); i++) {
if (Title[i]==' ') { Title[i]='_'; }
}
return true;
}
bool TWikiMetaHist::LoadNextTxt() {
IAssert(! XmlInPt.Empty());
//Clr(); //!!! DON'T clear so that the Title remains
TXmlParser& XmlIn = *XmlInPt;
// skip till <page> or <revision>
while (! (XmlIn.Sym == xsySTag && (XmlIn.SymStr == "page" || XmlIn.SymStr == "revision"))) {
XmlIn.GetSym();
if (XmlIn.Sym == xsyEof) { return false; }
}
// page info
if (XmlIn.SymStr == "page") {
XmlIn.GetTagVal("title", Title);
XmlIn.GetTagVal("id", Tmp);
PageId = atoi(Tmp.CStr());
XmlIn.GetSym();
if (XmlIn.SymStr != "revision") {
while (XmlIn.SymStr != "revision") { printf("NEW_TAG: %s\n", XmlIn.SymStr.CStr()); XmlIn.GetSym(); }
}
}
EAssertR(XmlIn.SymStr == "revision", XmlIn.SymStr); // revision
XmlIn.GetTagVal("id", Tmp);
//printf("%s\n", Tmp.CStr());
RevId = atoi(Tmp.CStr()); // 012345678901234567890
XmlIn.GetTagVal("timestamp", Tmp); // 2001-01-19T01:12:51Z
Tmp[4]=0; Tmp[7]=0; Tmp[10]=0; Tmp[13]=0; Tmp[16]=0; Tmp[19]=0;
RevTm = TSecTm(atoi(Tmp.CStr()), atoi(Tmp.CStr()+5), atoi(Tmp.CStr()+8),
atoi(Tmp.CStr()+11), atoi(Tmp.CStr()+14), atoi(Tmp.CStr()+17));
EAssert(XmlIn.GetTag("contributor") == xsySTag);
XmlIn.GetSym();
if (XmlIn.SymStr == "ip" && XmlIn.Sym==xsySTag) {
XmlIn.GetSym(); Usr="ip:"; Usr+=XmlIn.SymStr;
XmlIn.GetTag("ip"); IAssert(! XmlIn.SymStr.IsPrefix("ip:")); }
else if (XmlIn.SymStr == "username") {
if (XmlIn.Sym == xsySTag) { XmlIn.GetSym(); Usr=XmlIn.SymStr; EAssert(XmlIn.GetTag("username") == xsyETag); } // not-empty username tag
else { EAssert(XmlIn.Sym == xsyETag && XmlIn.SymStr == "username"); } // empty username tag
XmlIn.GetTagVal("id", Tmp); UsrId = atoi(Tmp.CStr());
}
// remove spaces in the username
for (int i = 0; i < Usr.Len(); i++) {
if (Usr[i]==' ') { Usr[i]='_'; }
}
EAssert(XmlIn.GetTag("contributor") == xsyETag);
//XmlIn.GetTagVal("comment", Cmt);
XmlIn.GetSym();
if (XmlIn.Sym == xsyETag && XmlIn.SymStr == "minor") { XmlIn.GetSym(); }
if (XmlIn.Sym == xsySTag && XmlIn.SymStr == "comment") {
XmlIn.GetSym();
if (XmlIn.Sym == xsyStr) { Cmt=XmlIn.SymStr; EAssert(XmlIn.GetTag("comment") == xsyETag); } // not-empty comment tag
else { EAssert(XmlIn.Sym == xsyETag && XmlIn.SymStr == "comment"); } // empty comment tag
XmlIn.GetSym();
}
EAssertR(XmlIn.SymStr.IsPrefix("text"), XmlIn.SymStr);
if (XmlIn.Sym == xsySTag) {
XmlIn.GetSym(Text);
if (XmlIn.Sym == xsyStr) { EAssert(XmlIn.GetTag("text") == xsyETag); } // non-empty text tag
else { EAssert(XmlIn.Sym == xsyETag && XmlIn.SymStr == "text"); } // empty text tag <text> </text>
}
EAssert(XmlIn.GetTag("revision") == xsyETag);
if (++PageCnt % 10000 == 0) {
printf("** %dk items: %s time %f\n", PageCnt/1000, ExeTm.GetStr(), ExeTm.GetSecs()); fflush(stdout); }
return true;
}
void TWikiMetaHist::Dump(const bool& AlsoText) const {
printf("page: %d %s\n", PageId, Title.CStr());
printf("rev: %d %s\n", RevId, RevTm.GetYmdTmStr().CStr());
printf("user: %d %s\n", UsrId, Usr.CStr());
printf("cmt: %s\n", Cmt.CStr());
if (AlsoText) { printf("text:\n%s\n", Text.CStr()); }
printf("\n");
}
void TWikiMetaHist::DumpNextXmlTags(const int& DumpN) {
TXmlParser& XmlIn = *XmlInPt;
for (int i = 0; i < DumpN; i++) {
printf("%s\n", XmlIn.SymStr.CStr());
XmlIn.GetSym();
if (XmlIn.Sym == xsyEof) { return; }
}
}
/*
/////////////////////////////////////////////////
// Wikipedia Voting Network
void TWikiVoteNet::PermuteOutEdgeSigns(const bool& OnlySigns) {
printf("\nPermute out-edge signs\n");
TIntV SignV;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
SignV.Clr(false);
for (int i = 0; i < NI.GetOutDeg(); i++) {
if (OnlySigns) {
if (NI.GetOutEDat(i)!=0) {
SignV.Add(NI.GetOutEDat(i)); } }
else { SignV.Add(NI.GetOutEDat(i)); }
}
SignV.Shuffle(TInt::Rnd);
for (int i = 0, s=0; i < NI.GetOutDeg(); i++) {
if (OnlySigns) {
if (NI.GetOutEDat(i)!=0) {
NI.GetOutEDat(i) = SignV[s++]; } }
else { NI.GetOutEDat(i) = SignV[s++]; }
}
}
}
void TWikiVoteNet::PermuteAllEdgeSigns(const bool& OnlySigns) {
TIntV SignV;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int i = 0; i < NI.GetOutDeg(); i++) {
if (OnlySigns) {
if (NI.GetOutEDat(i)!=0) {
SignV.Add(NI.GetOutEDat(i)); } }
else { SignV.Add(NI.GetOutEDat(i)); }
}
}
SignV.Shuffle(TInt::Rnd);
int s = 0;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int i = 0; i < NI.GetOutDeg(); i++) {
if (OnlySigns) {
if (NI.GetOutEDat(i)!=0) {
NI.GetOutEDat(i) = SignV[s++]; } }
else { NI.GetOutEDat(i) = SignV[s++]; }
}
}
}
void TWikiVoteNet::CountTriads() const {
TIntSet NbrIdSet;
THash<TIntTr, TInt> TriadCntH;
TIntH SignH;
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
SignH.AddDat(EI()) += 1;
}
printf("Count triads:\nbackground sign distribution:\n");
SignH.SortByKey(false);
for (int i = 0; i < SignH.Len(); i++) {
printf("\t%2d\t%d\n", SignH.GetKey(i), SignH[i]);
}
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
const TNodeI SrcNI = GetNI(EI.GetSrcNId());
const TNodeI DstNI = GetNI(EI.GetDstNId());
const TInt E1Dat = EI();
NbrIdSet.Clr(false);
for (int es = 0; es < SrcNI.GetDeg(); es++) {
NbrIdSet.AddKey(SrcNI.GetNbrNId(es)); }
for (int ed = 0; ed < DstNI.GetDeg(); ed++) {
const int nbr = DstNI.GetNbrNId(ed);
if (! NbrIdSet.IsKey(nbr)) { continue; }
const TInt E2Dat = SrcNI.GetNbrEDat(NbrIdSet.GetKeyId(nbr));
const TInt E3Dat = DstNI.GetNbrEDat(ed);
//printf("triad: %d -- %d -- %d : %d %d %d\n", SrcNI.GetId(), DstNI.GetId(), nbr, E1Dat, E2Dat, E3Dat);
//TriadCntH.AddDat(E1Dat+E2Dat+E3Dat) += 1;
TriadCntH.AddDat(TIntTr(TMath::Mx(E1Dat, E2Dat, E3Dat),
TMath::Median(E1Dat, E2Dat, E3Dat), TMath::Mn(E1Dat, E2Dat, E3Dat))) += 1;
}
}
TriadCntH.SortByKey(false);
printf("triad counts (all counts times 3):\n");
int SumTriad = 0, SignTriad=0;
for (int i = 0; i < TriadCntH.Len(); i++) {
SumTriad += TriadCntH[i];
TIntTr SignTr = TriadCntH.GetKey(i);
if (SignTr.Val1!=0 && SignTr.Val2!=0 && SignTr.Val3!=0) {
SignTriad += TriadCntH[i];; }
}
for (int i = 0; i < TriadCntH.Len(); i++) {
TIntTr SignTr = TriadCntH.GetKey(i);
printf("\t%2d %2d %2d\t%8d\t%f", SignTr.Val1, SignTr.Val2, SignTr.Val3,
TriadCntH[i], TriadCntH[i]/double(SumTriad));
if (SignTr.Val1!=0 && SignTr.Val2!=0 && SignTr.Val3!=0) {
printf("\t%f", TriadCntH[i]/double(SignTriad)); }
printf("\n");
}
}
void TWikiVoteNet::GetTwoPartScore() const {
TIntFltH NIdScoreH, NIdNewScoreH;
TInt::Rnd.PutSeed(0);
double sum = 0;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
NIdScoreH.AddDat(NI.GetId(), 1-2*TInt::Rnd.GetUniDev()); }
for (int i = 0; i < NIdScoreH.Len(); i++) { sum += fabs(NIdScoreH[i]); }
for (int i = 0; i < NIdScoreH.Len(); i++) { NIdScoreH[i] /= sum; }
for (int i = 0; i < 100; i++) {
double delta = 0;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
TMom Mom;
double sum = 0;
for (int e = 0; e < NI.GetOutDeg(); e++) {
const double s = NI.GetOutEDat(e) * NIdScoreH.GetDat(NI.GetOutNId(e));
IAssert(s <= 1 && s >= -1);
Mom.Add(s); sum += s;
}
for (int e = 0; e < NI.GetInDeg(); e++) {
const double s = NI.GetInEDat(e)() * NIdScoreH.GetDat(NI.GetInNId(e));
Mom.Add(s); sum += s;
}
Mom.Def();
delta += fabs(NIdScoreH.GetDat(NI.GetId()) - Mom.GetMean());
//NIdNewScoreH.AddDat(NI.GetId(), Mom.GetMean());
NIdNewScoreH.AddDat(NI.GetId(), sum);
}
NIdScoreH = NIdNewScoreH;
sum = 0;
for (int i = 0; i < NIdScoreH.Len(); i++) { sum += fabs(NIdScoreH[i]); }
for (int i = 0; i < NIdScoreH.Len(); i++) { NIdScoreH[i] /= sum; }
printf("delta %f\n", delta);
}
TIntH ScoreH;
for (int i = 0; i < NIdScoreH.Len(); i++) {
ScoreH.AddDat(int(NIdScoreH[i]*100.0)) += 1;
if (int(NIdScoreH[i]*100) != 0 || i < 100) {
TNodeI NI = GetNI(NIdScoreH.GetKey(i));
//printf("%g\to:%d\ti:%d\n", NIdScoreH[i], NI.GetOutDeg(), NI.GetInDeg());
}
}
TGnuPlot::PlotValCntH(ScoreH, "partyScore-wiki", "Distribution of party score", "Score", "Number of people");
}
// return the number of ok edges - number of conflicting edges
// edge is ok if + edge links same sign nodes, - edge links opposite sign nodes
int TWikiVoteNet::GetEnergy() const {
TInt::Rnd.PutSeed(0);
TIntH NIdSignH;
TIntV NIdV;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
NIdSignH.AddDat(NI.GetId(), TInt::Rnd.GetUniDev()<0.5?1:-1);
NIdV.Add(NI.GetId());
}
int FulEnergy;
for (int iters =0; iters < 20; iters++) {
int Energy = 0, PosCnt=0;
NIdV.Shuffle(TInt::Rnd);
for (int n = 0; n < NIdV.Len(); n++) {
TNodeI NI = GetNI(NIdV[n]);
const int MySign = NIdSignH.GetDat(NI.GetId());
for (int e = 0; e < NI.GetOutDeg(); e++) {
Energy += MySign * NI.GetOutEDat(e) * NIdSignH.GetDat(NI.GetOutNId(e)); }
if (MySign == +1) { PosCnt++; }
}
printf(" Energy\t%d\t+%d\t-%d", Energy, PosCnt, NIdSignH.Len()-PosCnt);
FulEnergy = Energy;
int NFlips = 0;
//for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int n = 0; n < NIdV.Len(); n++) {
TNodeI NI = GetNI(NIdV[n]);
int MyEnerg = 0;
for (int e = 0; e < NI.GetOutDeg(); e++) {
MyEnerg += NI.GetOutEDat(e) * NIdSignH.GetDat(NI.GetOutNId(e)); }
int NewSign = MyEnerg < 0 ? -1 : 1;
//if (MyEnerg == 0) { MyEnerg = TInt::Rnd.GetUniDev()<0.5?1:-1; }
Energy = abs(MyEnerg);
if (NIdSignH.GetDat(NI.GetId()) != NewSign) {
NIdSignH.AddDat(NI.GetId(), NewSign);
NFlips++;
}
}
printf("\tflips\t%d\n", NFlips);
if (NFlips == 0) { break; }
}
for (int n = 0; n < NIdSignH.Len(); n++) {
//printf(" nid sign: %d: %d\n", NIdSignH.GetKey(n), NIdSignH[n]);
}
return FulEnergy;
}
// keep only edges of a given sign
PWikiVoteNet TWikiVoteNet::GetEdgeSubNet(const int& EdgeDat) const {
PWikiVoteNet Net = TWikiVoteNet::New();
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
Net->AddNode(NI.GetId(), NI.GetDat()); }
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (NI.GetOutEDat(e) == EdgeDat) {
Net->AddEdge(NI.GetId(), NI.GetOutNId(e), NI.GetOutEDat(e)); }
}
}
return Net;
}
PWikiVoteNet TWikiVoteNet::GetSubGraph(const TIntV& NIdV, const bool& RenumberNodes) const {
PWikiVoteNet Net = TWikiVoteNet::New();
IAssert(! RenumberNodes);
for (int node = 0; node < NIdV.Len(); node++) {
Net->AddNode(NIdV[node], GetNDat(NIdV[node])); } // also copy the node data
for (int node = 0; node < NIdV.Len(); node++) {
const TNodeI NI = GetNI(NIdV[node]);
const int SrcNId = NI.GetId();
for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
const int OutNId = NI.GetOutNId(edge);
if (Net->IsNode(OutNId)) {
Net->AddEdge(SrcNId, OutNId, NI.GetOutEDat(edge)); }
}
}
return Net;
}
PWikiVoteNet TWikiVoteNet::GetSignedSubNet(const bool& OnlySignEdges) const {
TIntSet SignedSet;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int i = 0; i < NI.GetOutDeg(); i++) {
if (NI.GetOutEDat(i) != 0) {
SignedSet.AddKey(NI.GetId());
SignedSet.AddKey(NI.GetOutNId(i));
}
}
}
TIntV NIdV;
SignedSet.GetKeyV(NIdV);
if (! OnlySignEdges) {
return GetSubGraph(NIdV);
}
PWikiVoteNet Net = TWikiVoteNet::New();
for (int n = 0; n < NIdV.Len(); n++) {
Net->AddNode(GetNI(NIdV[n])); }
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI() != 0) {
IAssert(Net->IsNode(EI.GetSrcNId()));
IAssert(Net->IsNode(EI.GetDstNId()));
Net->AddEdge(EI.GetSrcNId(), EI.GetDstNId(), EI());
}
}
return Net;
}
PWikiVoteNet TWikiVoteNet::GetSubSignGraph(const int& EdgeSign) const {
TIntSet SignedSet;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int i = 0; i < NI.GetOutDeg(); i++) {
if (NI.GetOutEDat(i) == EdgeSign) {
SignedSet.AddKey(NI.GetId());
SignedSet.AddKey(NI.GetOutNId(i));
}
}
}
TIntV NIdV;
SignedSet.GetKeyV(NIdV);
PWikiVoteNet Net = TWikiVoteNet::New();
for (int n = 0; n < NIdV.Len(); n++) {
Net->AddNode(GetNI(NIdV[n])); }
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
if (EI() == EdgeSign) {
IAssert(Net->IsNode(EI.GetSrcNId()));
IAssert(Net->IsNode(EI.GetDstNId()));
Net->AddEdge(EI.GetSrcNId(), EI.GetDstNId(), EI());
}
}
return Net;
}
// plot the span of a particular edge:
// number of common friends of the endpoints
// path length between the endpoints
void TWikiVoteNet::PlotSignRange(const TStr& OutFNm) const {
TFltFltH SupRngH, OppRngH; // path length
TFltFltH SupCmnH, OppCmnH; // common friends
THash<TFlt, TMom> RngFracH, CmnFracH; // fraction of supporters
PWikiVoteNet ThisPt = PWikiVoteNet((TWikiVoteNet*) this);
for (TEdgeI EI = BegEI(); EI < EndEI(); EI++) {
const int C = TGAlg::GetCmnNbrs(ThisPt, EI.GetSrcNId(), EI.GetDstNId(), false);
const int R = TGAlg::GetRangeDist(ThisPt, EI.GetSrcNId(), EI.GetDstNId(), false);
if (EI() == 1) {
SupRngH.AddDat(R)++; RngFracH.AddDat(R).Add(1);
SupCmnH.AddDat(C)++; CmnFracH.AddDat(C).Add(1);
} else if (EI() == -1) {
OppRngH.AddDat(R)++; RngFracH.AddDat(R).Add(0);
OppCmnH.AddDat(C)++; CmnFracH.AddDat(C).Add(0);
}
}
TGnuPlot::PlotValCntH(SupRngH, "rngSup-"+OutFNm, "range of support votes", "range (path length after edge is removed)", "count");
TGnuPlot::PlotValCntH(OppRngH, "rngOpp-"+OutFNm, "range of opposing votes", "range (path length after edge is removed)", "count");
TGnuPlot::PlotValCntH(SupCmnH, "cmnSup-"+OutFNm, "number of common friends of support votes", "number of common friends", "count", gpsLog);
TGnuPlot::PlotValCntH(OppCmnH, "cmnOpp-"+OutFNm, "number of common friends of opposing votes", "number of common friends", "count", gpsLog);
TGnuPlot::PlotValMomH(RngFracH, "fracRng-"+OutFNm, "fraction of support edges spanning range X", "range", "fraction of support edges");
TGnuPlot::PlotValMomH(CmnFracH, "fracCmn-"+OutFNm, "fraction of support edges having X common neighbors", "number of common neighbors", "fraction of support edges", gpsLog);
}
void TWikiVoteNet::SaveMatlabSparseMtx(const TStr& OutFNm, const bool& IsDir) const {
FILE *F = fopen(OutFNm.CStr(), "wt");
if (IsDir) {
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int e = 0; e < NI.GetOutDeg(); e++) {
fprintf(F, "%d\t%d\t%d\n", NI.GetId(), NI.GetOutNId(e), NI.GetOutEDat(e).Val); }
}
} else {
THash<TIntPr, TInt> EdgeH;
for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
for (int e = 0; e < NI.GetOutDeg(); e++) {
EdgeH.AddDat(TIntPr(NI.GetId(), NI.GetOutNId(e)), NI.GetOutEDat(e));
EdgeH.AddDat(TIntPr(NI.GetOutNId(e), NI.GetId()), NI.GetOutEDat(e));
}
}
EdgeH.SortByKey();
for (int i = 0; i < EdgeH.Len(); i++) {
fprintf(F, "%d\t%d\t%d\n", EdgeH.GetKey(i).Val1(), EdgeH.GetKey(i).Val2(), EdgeH[i].Val);
}
}
fclose(F);
}
// 1---2
// \ /|
// 4---0-3
PWikiVoteNet TWikiVoteNet::GetSmallNet() {
PWikiVoteNet Net = TWikiVoteNet::New();
/*for (int i = 0; i < 5; i++) { Net->AddNode(i, i); }
Net->AddEdge(0,1, 1);
Net->AddEdge(0,2, 1);
Net->AddEdge(1,2, 1);
Net->AddEdge(0,3, -1);
Net->AddEdge(2,3, 1);
Net->AddEdge(0,4, -1);
return Net;
}
PWikiVoteNet TWikiVoteNet::LoadSlashdot(const TStr& InFNm, const TStr& PosEdge, const TStr& NegEdge) {
PWikiVoteNet Net = TWikiVoteNet::New();
TStrHash<TInt> StrNIdH;
StrNIdH.AddKey(" ");
TSsParser Ss(InFNm, ssfTabSep);
while (Ss.Next()) {
const int SrcNId = StrNIdH.AddKey(Ss[0]);
if (! Net->IsNode(SrcNId)) {
Net->AddNode(SrcNId, TChA(Ss[0]).ToLc()); }
int EdgeVal = 0;
if (PosEdge == Ss[1]) { EdgeVal=+1; }
else if (NegEdge == Ss[1]) { EdgeVal=-1; }
else { continue; } // only add signed edges
for (int s = 2; s < Ss.Len(); s++) {
const int DstNId = StrNIdH.AddKey(Ss[s]);
if (! Net->IsNode(DstNId)) {
Net->AddNode(DstNId, TChA(Ss[s]).ToLc()); }
if (SrcNId != DstNId) { // skip self edges
Net->AddEdge(SrcNId, DstNId, EdgeVal); }
}
}
TSnap::PrintInfo(Net, "Slashdot network", false);
return Net;
}
// there is a directed edge if one user edited the talk page of another user
// user and node ids between the TWikiElecBs and TWikiVoteNet match
/*PWikiVoteNet TWikiMetaHist::LoadUserTalkNet(const TStr& FNm, const TWikiElecBs& ElecBs) {
PWikiVoteNet Net = TWikiVoteNet::New();
TZipIn FIn(FNm);
TStrSet UsrNIdH;
// add nodes of users ids of people that casted votes
for (int u = 0; u < ElecBs.GetUsrs(); u++) {
UsrNIdH.AddKey(ElecBs.GetUsr(u));
}
// add remaining users and edges
for (TChA LnStr; FIn.GetNextLn(LnStr); ) {
if (! LnStr.IsPrefix("REVISION ")) { continue; }
const int b = LnStr.SearchStr("User_talk:")+(int)strlen("User_talk:");
int e1 = LnStr.SearchCh(' ', b)-1;
int e2 = LnStr.SearchCh('/', b)-1;
if (e1<0) { e1=TInt::Mx; }
if (e2<0) { e2=TInt::Mx; }
const TChA Dst = LnStr.GetSubStr(b, TMath::Mn(e1, e2)).ToLc();
const int e = LnStr.SearchChBack(' ');
const TChA Src = LnStr.GetSubStr(LnStr.SearchChBack(' ', e-1)+1, e-1).ToLc();
if (Src != Dst) { // skip self edges
const int src = UsrNIdH.AddKey(Src);
const int dst = UsrNIdH.AddKey(Dst);
if (! Net->IsNode(src)) { Net->AddNode(src, Src); }
if (! Net->IsNode(dst)) { Net->AddNode(dst, Dst); }
Net->AddEdge(src, dst);
}
}
// add vote data on the edges
printf("Set edge signs...\n");
int nset = 0, nfound=0;
TIntSet NodeSet;
printf("%d elections\n", ElecBs.Len());
for (int e = 0; e < ElecBs.Len(); e++) {
const TWikiElec& E = ElecBs.GetElec(e);
const int nid1 = E.GetUId();
if (! Net->IsNode(nid1)) { continue; } // not a node
TWikiVoteNet::TNodeI NI = Net->GetNI(nid1);
printf(" %d,%d", NI.GetOutDeg(), NI.GetInDeg());
nfound++;
// set out edge signs
NodeSet.Clr(false);
for (int i = 0; i < NI.GetOutDeg(); i++) {
NodeSet.AddKey(NI.GetOutNId(i)); }
for (int v = 0; v < E.Len(); v++) {
const int dst = NodeSet.GetKeyId(E.GetVote(v).GetUId());
if (Net->IsNode(E.GetVote(v).GetUId())) {
const int id = E.GetVote(v).GetUId();
if (Net->GetNDat(id) != ElecBs.GetUsr(id)) { printf("ERR: %s %s\n", Net->GetNDat(id).CStr(), ElecBs.GetUsr(id)); }
}
if (dst != -1) { nset++;
NI.GetOutEDat(dst) = E.GetVote(v).GetVote(); }
}
// also set in-edge signes (if they are not set)
NodeSet.Clr(false);
for (int i = 0; i < NI.GetInDeg(); i++) {
NodeSet.AddKey(NI.GetInNId(i)); }
for (int v = 0; v < E.Len(); v++) {
const int dst = NodeSet.GetKeyId(E.GetVote(v).GetUId());
if (Net->IsNode(E.GetVote(v).GetUId())) {
const int id = E.GetVote(v).GetUId();
if (Net->GetNDat(id) != ElecBs.GetUsr(id)) { printf("ERR: %s %s\n", Net->GetNDat(id).CStr(), ElecBs.GetUsr(id)); }
}
if (dst != -1) { nset++;
TInt& Vote = NI.GetInEDat(dst);
if (Vote == 0) { Vote = E.GetVote(v).GetVote(); }
}
}
}
printf("\n%d admins on vote found\n", nfound);
printf("%d edges with sign set\n\n", nset);
TSnap::PrintInfo(Net, "WIKI USER TALK NET");
return Net;
}*/
| 44.445397 | 229 | 0.602617 | [
"3d"
] |
f62e12c4cd6deadef218504289229ecc0dbc6239 | 2,422 | cpp | C++ | utilities/C++/Linkedin high frequency/127. Word Ladder.cpp | JanathonL-CMU/tech-interview-handbook | be3adc5142ade45c5677eeb0b082e18e7ca5df92 | [
"MIT"
] | null | null | null | utilities/C++/Linkedin high frequency/127. Word Ladder.cpp | JanathonL-CMU/tech-interview-handbook | be3adc5142ade45c5677eeb0b082e18e7ca5df92 | [
"MIT"
] | null | null | null | utilities/C++/Linkedin high frequency/127. Word Ladder.cpp | JanathonL-CMU/tech-interview-handbook | be3adc5142ade45c5677eeb0b082e18e7ca5df92 | [
"MIT"
] | null | null | null | // 127. Word Ladder
// Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
// Only one letter can be changed at a time.
// Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
// Note:
// Return 0 if there is no such transformation sequence.
// All words have the same length.
// All words contain only lowercase alphabetic characters.
// You may assume no duplicates in the word list.
// You may assume beginWord and endWord are non-empty and are not the same.
// Example 1:
// Input:
// beginWord = "hit",
// endWord = "cog",
// wordList = ["hot","dot","dog","lot","log","cog"]
// Output: 5
// Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
// return its length 5.
// Example 2:
// Input:
// beginWord = "hit"
// endWord = "cog"
// wordList = ["hot","dot","dog","lot","log"]
// Output: 0
// Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
minstep=INT_MAX;
unordered_set<string> dict;
queue<string> toVisit;
toVisit.push(beginWord);
for(int i = 0;i<wordList.size();i++){
dict.insert(wordList[i]);
}
int dist = 1;
while(!toVisit.empty()){
int num = toVisit.size();
for(int i =0;i<num;i++){
string word = toVisit.front();
toVisit.pop();
if(word==endWord) return dist;
addNext(word,dict,toVisit);
}
dist++;
}
return 0;
}
void addNext(string beginWord, unordered_set<string>& dict, queue<string>& toVisit){
for(int i =0; i<beginWord.size();i++){
for(int j =0;j<26;j++){
if(beginWord[i]==j+'a') continue;
string old = beginWord;
beginWord[i]=j+'a';
if(dict.find(beginWord)!=dict.end()){
dict.erase(beginWord);
toVisit.push(beginWord);
}
beginWord=old;
}
}
}
private:
int minstep;
vector<int> visit;
}; | 29.901235 | 163 | 0.556565 | [
"vector"
] |
f632b3451a3ba5353200d45c6dd71f005564c766 | 19,190 | cxx | C++ | main/xmloff/source/text/XMLRedlineExport.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/xmloff/source/text/XMLRedlineExport.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/xmloff/source/text/XMLRedlineExport.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLRedlineExport.hxx"
#include <tools/debug.hxx>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#include <com/sun/star/container/XEnumerationAccess.hpp>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/document/XRedlinesSupplier.hpp>
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/text/XTextContent.hpp>
#include <com/sun/star/text/XTextSection.hpp>
#include <com/sun/star/util/DateTime.hpp>
#include <xmloff/xmltoken.hxx>
#include "xmloff/xmlnmspe.hxx"
#include <xmloff/xmlexp.hxx>
#include <xmloff/xmluconv.hxx>
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::beans::UnknownPropertyException;
using ::com::sun::star::document::XRedlinesSupplier;
using ::com::sun::star::container::XEnumerationAccess;
using ::com::sun::star::container::XEnumeration;
using ::com::sun::star::text::XText;
using ::com::sun::star::text::XTextContent;
using ::com::sun::star::text::XTextSection;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::util::DateTime;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::std::list;
XMLRedlineExport::XMLRedlineExport(SvXMLExport& rExp)
: sDelete(RTL_CONSTASCII_USTRINGPARAM("Delete"))
, sDeletion(GetXMLToken(XML_DELETION))
, sFormat(RTL_CONSTASCII_USTRINGPARAM("Format"))
, sFormatChange(GetXMLToken(XML_FORMAT_CHANGE))
, sInsert(RTL_CONSTASCII_USTRINGPARAM("Insert"))
, sInsertion(GetXMLToken(XML_INSERTION))
, sIsCollapsed(RTL_CONSTASCII_USTRINGPARAM("IsCollapsed"))
, sIsStart(RTL_CONSTASCII_USTRINGPARAM("IsStart"))
, sRedlineAuthor(RTL_CONSTASCII_USTRINGPARAM("RedlineAuthor"))
, sRedlineComment(RTL_CONSTASCII_USTRINGPARAM("RedlineComment"))
, sRedlineDateTime(RTL_CONSTASCII_USTRINGPARAM("RedlineDateTime"))
, sRedlineSuccessorData(RTL_CONSTASCII_USTRINGPARAM("RedlineSuccessorData"))
, sRedlineText(RTL_CONSTASCII_USTRINGPARAM("RedlineText"))
, sRedlineType(RTL_CONSTASCII_USTRINGPARAM("RedlineType"))
, sStyle(RTL_CONSTASCII_USTRINGPARAM("Style"))
, sTextTable(RTL_CONSTASCII_USTRINGPARAM("TextTable"))
, sUnknownChange(RTL_CONSTASCII_USTRINGPARAM("UnknownChange"))
, sStartRedline(RTL_CONSTASCII_USTRINGPARAM("StartRedline"))
, sEndRedline(RTL_CONSTASCII_USTRINGPARAM("EndRedline"))
, sRedlineIdentifier(RTL_CONSTASCII_USTRINGPARAM("RedlineIdentifier"))
, sIsInHeaderFooter(RTL_CONSTASCII_USTRINGPARAM("IsInHeaderFooter"))
, sRedlineProtectionKey(RTL_CONSTASCII_USTRINGPARAM("RedlineProtectionKey"))
, sRecordChanges(RTL_CONSTASCII_USTRINGPARAM("RecordChanges"))
, sMergeLastPara(RTL_CONSTASCII_USTRINGPARAM("MergeLastPara"))
, sChangePrefix(RTL_CONSTASCII_USTRINGPARAM("ct"))
, rExport(rExp)
, pCurrentChangesList(NULL)
{
}
XMLRedlineExport::~XMLRedlineExport()
{
// delete changes lists
for( ChangesMapType::iterator aIter = aChangeMap.begin();
aIter != aChangeMap.end();
aIter++ )
{
delete aIter->second;
}
aChangeMap.clear();
}
void XMLRedlineExport::ExportChange(
const Reference<XPropertySet> & rPropSet,
sal_Bool bAutoStyle)
{
if (bAutoStyle)
{
// For the headers/footers, we have to collect the autostyles
// here. For the general case, however, it's better to collet
// the autostyles by iterating over the global redline
// list. So that's what we do: Here, we collect autostyles
// only if we have no current list of changes. For the
// main-document case, the autostyles are collected in
// ExportChangesListAutoStyles().
if (pCurrentChangesList != NULL)
ExportChangeAutoStyle(rPropSet);
}
else
{
ExportChangeInline(rPropSet);
}
}
void XMLRedlineExport::ExportChangesList(sal_Bool bAutoStyles)
{
if (bAutoStyles)
{
ExportChangesListAutoStyles();
}
else
{
ExportChangesListElements();
}
}
void XMLRedlineExport::ExportChangesList(
const Reference<XText> & rText,
sal_Bool bAutoStyles)
{
// in the header/footer case, auto styles are collected from the
// inline change elements.
if (bAutoStyles)
return;
// look for changes list for this XText
ChangesMapType::iterator aFind = aChangeMap.find(rText);
if (aFind != aChangeMap.end())
{
ChangesListType* pChangesList = aFind->second;
// export only if changes are found
if (pChangesList->size() > 0)
{
// changes container element
SvXMLElementExport aChanges(rExport, XML_NAMESPACE_TEXT,
XML_TRACKED_CHANGES,
sal_True, sal_True);
// iterate over changes list
for( ChangesListType::iterator aIter = pChangesList->begin();
aIter != pChangesList->end();
aIter++ )
{
ExportChangedRegion( *aIter );
}
}
// else: changes list empty -> ignore
}
// else: no changes list found -> empty
}
void XMLRedlineExport::SetCurrentXText(
const Reference<XText> & rText)
{
if (rText.is())
{
// look for appropriate list in map; use the found one, or create new
ChangesMapType::iterator aIter = aChangeMap.find(rText);
if (aIter == aChangeMap.end())
{
ChangesListType* pList = new ChangesListType;
aChangeMap[rText] = pList;
pCurrentChangesList = pList;
}
else
pCurrentChangesList = aIter->second;
}
else
{
// don't record changes
SetCurrentXText();
}
}
void XMLRedlineExport::SetCurrentXText()
{
pCurrentChangesList = NULL;
}
void XMLRedlineExport::ExportChangesListElements()
{
// get redlines (aka tracked changes) from the model
Reference<XRedlinesSupplier> xSupplier(rExport.GetModel(), uno::UNO_QUERY);
if (xSupplier.is())
{
Reference<XEnumerationAccess> aEnumAccess = xSupplier->getRedlines();
// redline protection key
Reference<XPropertySet> aDocPropertySet( rExport.GetModel(),
uno::UNO_QUERY );
// redlining enabled?
sal_Bool bEnabled = *(sal_Bool*)aDocPropertySet->getPropertyValue(
sRecordChanges ).getValue();
// only export if we have redlines or attributes
if ( aEnumAccess->hasElements() || bEnabled )
{
// export only if we have changes, but tracking is not enabled
if ( !bEnabled != !aEnumAccess->hasElements() )
{
rExport.AddAttribute(
XML_NAMESPACE_TEXT, XML_TRACK_CHANGES,
bEnabled ? XML_TRUE : XML_FALSE );
}
// changes container element
SvXMLElementExport aChanges(rExport, XML_NAMESPACE_TEXT,
XML_TRACKED_CHANGES,
sal_True, sal_True);
// get enumeration and iterate over elements
Reference<XEnumeration> aEnum = aEnumAccess->createEnumeration();
while (aEnum->hasMoreElements())
{
Any aAny = aEnum->nextElement();
Reference<XPropertySet> xPropSet;
aAny >>= xPropSet;
DBG_ASSERT(xPropSet.is(),
"can't get XPropertySet; skipping Redline");
if (xPropSet.is())
{
// export only if not in header or footer
// (those must be exported with their XText)
aAny = xPropSet->getPropertyValue(sIsInHeaderFooter);
if (! *(sal_Bool*)aAny.getValue())
{
// and finally, export change
ExportChangedRegion(xPropSet);
}
}
// else: no XPropertySet -> no export
}
}
// else: no redlines -> no export
}
// else: no XRedlineSupplier -> no export
}
void XMLRedlineExport::ExportChangeAutoStyle(
const Reference<XPropertySet> & rPropSet)
{
// record change (if changes should be recorded)
if (NULL != pCurrentChangesList)
{
// put redline in list if it's collapsed or the redline start
Any aIsStart = rPropSet->getPropertyValue(sIsStart);
Any aIsCollapsed = rPropSet->getPropertyValue(sIsCollapsed);
if ( *(sal_Bool*)aIsStart.getValue() ||
*(sal_Bool*)aIsCollapsed.getValue() )
pCurrentChangesList->push_back(rPropSet);
}
// get XText for export of redline auto styles
Any aAny = rPropSet->getPropertyValue(sRedlineText);
Reference<XText> xText;
aAny >>= xText;
if (xText.is())
{
// export the auto styles
rExport.GetTextParagraphExport()->collectTextAutoStyles(xText);
}
}
void XMLRedlineExport::ExportChangesListAutoStyles()
{
// get redlines (aka tracked changes) from the model
Reference<XRedlinesSupplier> xSupplier(rExport.GetModel(), uno::UNO_QUERY);
if (xSupplier.is())
{
Reference<XEnumerationAccess> aEnumAccess = xSupplier->getRedlines();
// only export if we actually have redlines
if (aEnumAccess->hasElements())
{
// get enumeration and iterate over elements
Reference<XEnumeration> aEnum = aEnumAccess->createEnumeration();
while (aEnum->hasMoreElements())
{
Any aAny = aEnum->nextElement();
Reference<XPropertySet> xPropSet;
aAny >>= xPropSet;
DBG_ASSERT(xPropSet.is(),
"can't get XPropertySet; skipping Redline");
if (xPropSet.is())
{
// export only if not in header or footer
// (those must be exported with their XText)
aAny = xPropSet->getPropertyValue(sIsInHeaderFooter);
if (! *(sal_Bool*)aAny.getValue())
{
ExportChangeAutoStyle(xPropSet);
}
}
}
}
}
}
void XMLRedlineExport::ExportChangeInline(
const Reference<XPropertySet> & rPropSet)
{
// determine element name (depending on collapsed, start/end)
enum XMLTokenEnum eElement = XML_TOKEN_INVALID;
Any aAny = rPropSet->getPropertyValue(sIsCollapsed);
sal_Bool bCollapsed = *(sal_Bool *)aAny.getValue();
sal_Bool bStart = sal_True; // ignored if bCollapsed = sal_True
if (bCollapsed)
{
eElement = XML_CHANGE;
}
else
{
aAny = rPropSet->getPropertyValue(sIsStart);
bStart = *(sal_Bool *)aAny.getValue();
eElement = bStart ? XML_CHANGE_START : XML_CHANGE_END;
}
if (XML_TOKEN_INVALID != eElement)
{
// we always need the ID
rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_CHANGE_ID,
GetRedlineID(rPropSet));
// export the element (no whitespace because we're in the text body)
SvXMLElementExport aChangeElem(rExport, XML_NAMESPACE_TEXT,
eElement, sal_False, sal_False);
}
}
void XMLRedlineExport::ExportChangedRegion(
const Reference<XPropertySet> & rPropSet)
{
// Redline-ID
rExport.AddAttributeIdLegacy(XML_NAMESPACE_TEXT, GetRedlineID(rPropSet));
// merge-last-paragraph
Any aAny = rPropSet->getPropertyValue(sMergeLastPara);
if( ! *(sal_Bool*)aAny.getValue() )
rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_MERGE_LAST_PARAGRAPH,
XML_FALSE);
// export change region element
SvXMLElementExport aChangedRegion(rExport, XML_NAMESPACE_TEXT,
XML_CHANGED_REGION, sal_True, sal_True);
// scope for (first) change element
{
aAny = rPropSet->getPropertyValue(sRedlineType);
OUString sType;
aAny >>= sType;
SvXMLElementExport aChange(rExport, XML_NAMESPACE_TEXT,
ConvertTypeName(sType), sal_True, sal_True);
ExportChangeInfo(rPropSet);
// get XText from the redline and export (if the XText exists)
aAny = rPropSet->getPropertyValue(sRedlineText);
Reference<XText> xText;
aAny >>= xText;
if (xText.is())
{
rExport.GetTextParagraphExport()->exportText(xText);
// default parameters: bProgress, bExportParagraph ???
}
// else: no text interface -> content is inline and will
// be exported there
}
// changed change? Hierarchical changes can onl be two levels
// deep. Here we check for the second level.
aAny = rPropSet->getPropertyValue(sRedlineSuccessorData);
Sequence<PropertyValue> aSuccessorData;
aAny >>= aSuccessorData;
// if we actually got a hierarchical change, make element and
// process change info
if (aSuccessorData.getLength() > 0)
{
// The only change that can be "undone" is an insertion -
// after all, you can't re-insert an deletion, but you can
// delete an insertion. This assumption is asserted in
// ExportChangeInfo(Sequence<PropertyValue>&).
SvXMLElementExport aSecondChangeElem(
rExport, XML_NAMESPACE_TEXT, XML_INSERTION,
sal_True, sal_True);
ExportChangeInfo(aSuccessorData);
}
// else: no hierarchical change
}
const OUString XMLRedlineExport::ConvertTypeName(
const OUString& sApiName)
{
if (sApiName == sDelete)
{
return sDeletion;
}
else if (sApiName == sInsert)
{
return sInsertion;
}
else if (sApiName == sFormat)
{
return sFormatChange;
}
else
{
DBG_ERROR("unknown redline type");
return sUnknownChange;
}
}
/** Create a Redline-ID */
const OUString XMLRedlineExport::GetRedlineID(
const Reference<XPropertySet> & rPropSet)
{
Any aAny = rPropSet->getPropertyValue(sRedlineIdentifier);
OUString sTmp;
aAny >>= sTmp;
OUStringBuffer sBuf(sChangePrefix);
sBuf.append(sTmp);
return sBuf.makeStringAndClear();
}
void XMLRedlineExport::ExportChangeInfo(
const Reference<XPropertySet> & rPropSet)
{
SvXMLElementExport aChangeInfo(rExport, XML_NAMESPACE_OFFICE,
XML_CHANGE_INFO, sal_True, sal_True);
Any aAny = rPropSet->getPropertyValue(sRedlineAuthor);
OUString sTmp;
aAny >>= sTmp;
if (sTmp.getLength() > 0)
{
SvXMLElementExport aCreatorElem( rExport, XML_NAMESPACE_DC,
XML_CREATOR, sal_True,
sal_False );
rExport.Characters(sTmp);
}
aAny = rPropSet->getPropertyValue(sRedlineDateTime);
util::DateTime aDateTime;
aAny >>= aDateTime;
{
OUStringBuffer sBuf;
rExport.GetMM100UnitConverter().convertDateTime(sBuf, aDateTime);
SvXMLElementExport aDateElem( rExport, XML_NAMESPACE_DC,
XML_DATE, sal_True,
sal_False );
rExport.Characters(sBuf.makeStringAndClear());
}
// comment as <text:p> sequence
aAny = rPropSet->getPropertyValue(sRedlineComment);
aAny >>= sTmp;
WriteComment( sTmp );
}
void XMLRedlineExport::ExportChangeInfo(
const Sequence<PropertyValue> & rPropertyValues)
{
OUString sComment;
sal_Int32 nCount = rPropertyValues.getLength();
for(sal_Int32 i = 0; i < nCount; i++)
{
const PropertyValue& rVal = rPropertyValues[i];
if( rVal.Name.equals(sRedlineAuthor) )
{
OUString sTmp;
rVal.Value >>= sTmp;
if (sTmp.getLength() > 0)
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_CHG_AUTHOR, sTmp);
}
}
else if( rVal.Name.equals(sRedlineComment) )
{
rVal.Value >>= sComment;
}
else if( rVal.Name.equals(sRedlineDateTime) )
{
util::DateTime aDateTime;
rVal.Value >>= aDateTime;
OUStringBuffer sBuf;
rExport.GetMM100UnitConverter().convertDateTime(sBuf, aDateTime);
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_CHG_DATE_TIME,
sBuf.makeStringAndClear());
}
else if( rVal.Name.equals(sRedlineType) )
{
// check if this is an insertion; cf. comment at calling location
OUString sTmp;
rVal.Value >>= sTmp;
DBG_ASSERT(sTmp.equals(sInsert),
"hierarchical change must be insertion");
}
// else: unknown value -> ignore
}
// finally write element
SvXMLElementExport aChangeInfo(rExport, XML_NAMESPACE_OFFICE,
XML_CHANGE_INFO, sal_True, sal_True);
WriteComment( sComment );
}
void XMLRedlineExport::ExportStartOrEndRedline(
const Reference<XPropertySet> & rPropSet,
sal_Bool bStart)
{
if( ! rPropSet.is() )
return;
// get appropriate (start or end) property
Any aAny;
try
{
aAny = rPropSet->getPropertyValue(bStart ? sStartRedline : sEndRedline);
}
catch( UnknownPropertyException e )
{
// If we don't have the property, there's nothing to do.
return;
}
Sequence<PropertyValue> aValues;
aAny >>= aValues;
const PropertyValue* pValues = aValues.getConstArray();
// seek for redline properties
sal_Bool bIsCollapsed = sal_False;
sal_Bool bIsStart = sal_True;
OUString sId;
sal_Bool bIdOK = sal_False; // have we seen an ID?
sal_Int32 nLength = aValues.getLength();
for(sal_Int32 i = 0; i < nLength; i++)
{
if (sRedlineIdentifier.equals(pValues[i].Name))
{
pValues[i].Value >>= sId;
bIdOK = sal_True;
}
else if (sIsCollapsed.equals(pValues[i].Name))
{
bIsCollapsed = *(sal_Bool*)pValues[i].Value.getValue();
}
else if (sIsStart.equals(pValues[i].Name))
{
bIsStart = *(sal_Bool*)pValues[i].Value.getValue();
}
}
if( bIdOK )
{
DBG_ASSERT( sId.getLength() > 0, "Redlines must have IDs" );
// TODO: use GetRedlineID or elimiate that function
OUStringBuffer sBuffer(sChangePrefix);
sBuffer.append(sId);
rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_CHANGE_ID,
sBuffer.makeStringAndClear());
// export the element
// (whitespace because we're not inside paragraphs)
SvXMLElementExport aChangeElem(
rExport, XML_NAMESPACE_TEXT,
bIsCollapsed ? XML_CHANGE :
( bIsStart ? XML_CHANGE_START : XML_CHANGE_END ),
sal_True, sal_True);
}
}
void XMLRedlineExport::ExportStartOrEndRedline(
const Reference<XTextContent> & rContent,
sal_Bool bStart)
{
Reference<XPropertySet> xPropSet(rContent, uno::UNO_QUERY);
if (xPropSet.is())
{
ExportStartOrEndRedline(xPropSet, bStart);
}
else
{
DBG_ERROR("XPropertySet expected");
}
}
void XMLRedlineExport::ExportStartOrEndRedline(
const Reference<XTextSection> & rSection,
sal_Bool bStart)
{
Reference<XPropertySet> xPropSet(rSection, uno::UNO_QUERY);
if (xPropSet.is())
{
ExportStartOrEndRedline(xPropSet, bStart);
}
else
{
DBG_ERROR("XPropertySet expected");
}
}
void XMLRedlineExport::WriteComment(const OUString& rComment)
{
if (rComment.getLength() > 0)
{
// iterate over all string-pieces separated by return (0x0a) and
// put each inside a paragraph element.
SvXMLTokenEnumerator aEnumerator(rComment, sal_Char(0x0a));
OUString aSubString;
while (aEnumerator.getNextToken(aSubString))
{
SvXMLElementExport aParagraph(
rExport, XML_NAMESPACE_TEXT, XML_P, sal_True, sal_False);
rExport.Characters(aSubString);
}
}
}
| 28.684604 | 80 | 0.701928 | [
"model"
] |
f6334ad218cfc04debb73665bf8cdb78d3fa32df | 1,186 | cpp | C++ | LeetCode/1254. Number of Closed Islands/solution.cpp | InnoFang/oh-my-algorithms | f559dba371ce725a926725ad28d5e1c2facd0ab2 | [
"Apache-2.0"
] | 1 | 2017-03-31T15:24:01.000Z | 2017-03-31T15:24:01.000Z | LeetCode/1254. Number of Closed Islands/solution.cpp | InnoFang/Algorithm-Library | 1896b9d8b1fa4cd73879aaecf97bc32d13ae0169 | [
"Apache-2.0"
] | null | null | null | LeetCode/1254. Number of Closed Islands/solution.cpp | InnoFang/Algorithm-Library | 1896b9d8b1fa4cd73879aaecf97bc32d13ae0169 | [
"Apache-2.0"
] | null | null | null | /**
* 47 / 47 test cases passed.
* Runtime: 12 ms
* Memory Usage: 9.1 MB
*/
class Solution {
public:
int direct[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int m, n;
void dfs(vector<vector<int>> &grid, int x, int y) {
grid[x][y] = 1;
for (auto &d : direct) {
int xx = x + d[0];
int yy = y + d[1];
if (xx < 0 || xx >= m || yy < 0 || yy >= n) continue;
if (grid[xx][yy]) continue;
dfs(grid, xx, yy);
}
}
int closedIsland(vector<vector<int>>& grid) {
m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; ++ i) {
if (!grid[i][0]) dfs(grid, i, 0);
if (!grid[i][n - 1]) dfs(grid, i, n - 1);
}
for (int i = 1; i < n - 1; ++ i) {
if (!grid[0][i]) dfs(grid, 0, i);
if (!grid[m - 1][i]) dfs(grid, m - 1, i);
}
int ans = 0;
for (int i = 1; i < m - 1; ++ i) {
for (int j = 1; j < n - 1; ++ j) {
if (!grid[i][j]) {
++ ans;
dfs(grid, i, j);
}
}
}
return ans;
}
};
| 28.238095 | 65 | 0.352445 | [
"vector"
] |
f6375a0aab7acc3505b29a2f575e4bbe0263b2c6 | 7,996 | cpp | C++ | src/core/HDCSCore.cpp | isabella232/HDCS | 1a5ae046e3ff947cc7a42219b9b1959766687612 | [
"Apache-2.0"
] | null | null | null | src/core/HDCSCore.cpp | isabella232/HDCS | 1a5ae046e3ff947cc7a42219b9b1959766687612 | [
"Apache-2.0"
] | 1 | 2021-02-23T19:10:26.000Z | 2021-02-23T19:10:26.000Z | src/core/HDCSCore.cpp | isabella232/HDCS | 1a5ae046e3ff947cc7a42219b9b1959766687612 | [
"Apache-2.0"
] | null | null | null | // Copyright [2017] <Intel>
#include "core/HDCSCore.h"
#include "core/policy/CachePolicy.h"
#include "core/policy/TierPolicy.h"
#include "store/SimpleStore/SimpleBlockStore.h"
#include "store/KVStore/KVStore.h"
#include "store/DataStore.h"
#include "store/RBD/RBDImageStore.h"
#include "common/HDCS_REQUEST_HANDLER.h"
#include <string>
#include <boost/algorithm/string.hpp>
namespace hdcs {
namespace core {
HDCSCore::HDCSCore(std::string host, std::string name,
std::string cfg_file,
hdcs_repl_options &&replication_options_param):
host(host),
name(name),
replication_options(replication_options_param) {
config = new Config(host + "_" + name, cfg_file);
std::string log_path = config->get_config("HDCSCore")["log_to_file"];
std::cout << "log_path: " << log_path << std::endl;
if( log_path!="false" ){
log_path = "hdcs_" + name + ".log";
int stderr_no = dup(fileno(stderr));
log_fd = fopen( log_path.c_str(), "w" );
if(log_fd==NULL){}
if(-1==dup2(fileno(log_fd), STDERR_FILENO)){}
}
int hdcs_thread_max = stoi(config->get_config("HDCSCore")["op_threads_num"]);
hdcs_op_threads = new TWorkQueue(hdcs_thread_max);
uint64_t total_size = stoull(config->get_config("HDCSCore")["total_size"]);
uint64_t block_size = stoull(config->get_config("HDCSCore")["cache_min_alloc_size"]);
bool cache_policy_mode = config->get_config("HDCSCore")["policy_mode"].compare(std::string("cache")) == 0 ? true : false;
std::string engine_type = config->get_config("HDCSCore")["entine_type"];
std::string path = config->get_config("HDCSCore")["cache_dir_run"];
std::string pool_name = config->get_config("HDCSCore")["rbd_pool_name"];
std::string volume_name = name;
//connect to its replication_nodes
std::cout << "replication_options.role : " << replication_options.role << std::endl;
std::cout << "replication_options.nodes : ";
for (auto &it : replication_options.replication_nodes) {
std::cout << it << ",";
}
std::cout << std::endl;
if ("master" == replication_options.role && replication_options.replication_nodes.size() != 0) {
connect_to_replica(replication_options.replication_nodes);
}
block_guard = new BlockGuard(total_size, block_size,
replication_core_map.size(),
std::move(replication_core_map));
BlockMap* block_ptr_map = block_guard->get_block_map();
store::DataStore* datastore = nullptr;
if (cache_policy_mode) {
uint64_t cache_size = stoull(config->get_config("HDCSCore")["cache_total_size"]);
float cache_ratio_health = stof(config->get_config("HDCSCore")["cache_ratio_health"]);
uint64_t timeout_nanosecond = stoull(config->get_config("HDCSCore")["cache_dirty_timeout_nanoseconds"]);
CACHE_MODE_TYPE cache_mode = config->get_config("HDCSCore")["cache_mode"].compare(std::string("readonly")) == 0 ? CACHE_MODE_READ_ONLY : CACHE_MODE_WRITE_BACK;
policy = new CachePolicy(total_size, cache_size, block_size, block_ptr_map,
datastore->create_engine(engine_type, path, total_size, cache_size, block_size),
new store::RBDImageStore(pool_name, volume_name, block_size),
cache_ratio_health, &request_queue,
timeout_nanosecond, cache_mode, hdcs_thread_max);
} else {
policy = new TierPolicy(total_size, block_size, block_ptr_map,
datastore->create_engine(engine_type, path, total_size, total_size, block_size),
new store::RBDImageStore(pool_name, volume_name, block_size),
&request_queue, hdcs_thread_max);
}
go = true;
main_thread = new std::thread(std::bind(&HDCSCore::process, this));
}
HDCSCore::~HDCSCore() {
go = false;
main_thread->join();
delete hdcs_op_threads;
for (auto& hdcs_replica : replication_core_map) {
((hdcs_ioctx_t*)hdcs_replica.second)->conn->close();
free((hdcs_ioctx_t*)hdcs_replica.second);
}
delete policy;
delete block_guard;
delete main_thread;
}
void HDCSCore::close() {
#if defined(CACHE_POLICY)
policy->flush_all();
#endif
}
void HDCSCore::promote_all() {
#if defined(TIER_POLICY)
((TierPolicy*)policy)->promote_all();
#endif
}
void HDCSCore::flush_all() {
#if defined(TIER_POLICY)
((TierPolicy*)policy)->flush_all();
#endif
}
void HDCSCore::queue_io(std::shared_ptr<Request> req) {
//request_queue.enqueue((void*)req);
process_request(req);
}
void HDCSCore::process() {
while(go){
std::shared_ptr<Request> req = request_queue.dequeue();
if (req != nullptr) {
process_request(req);
}
}
}
void HDCSCore::process_request(std::shared_ptr<Request> req) {
//std::mutex block_request_list_lock;
//BlockRequestList block_request_list;
std::lock_guard<std::mutex> lock(block_request_list_lock);
block_guard->create_block_requests(req, &block_request_list);
for (BlockRequestList::iterator it = block_request_list.begin(); it != block_request_list.end();) {
if (!it->block->in_discard_process) {
map_block(std::move(*it));
block_request_list.erase(it++);
} else {
it++;
}
}
}
void HDCSCore::map_block(BlockRequest &&block_request) {
BlockOp *block_ops_end;
Block* block = block_request.block;
bool do_process = false;
block->block_mutex.lock();
// If this block_request belongs to discard block,
// append to wait list firstly.
BlockOp *block_ops_head = policy->map(std::move(block_request), &block_ops_end);
if (!block->in_process) {
block->in_process = true;
block->block_ops_end = block_ops_end;
do_process = true;
log_print("Block not in process, block: %lu, new end: %p", block->block_id, block_ops_end);
} else {
log_print("Block in process, append request, block: %lu, append BlockOp: %p after BlockOp: %p, new end: %p", block->block_id, block_ops_head, block->block_ops_end, block_ops_end);
block->block_ops_end->block_op_next = block_ops_head;
block->block_ops_end = block_ops_end;
}
block->block_mutex.unlock();
if (do_process) {
hdcs_op_threads->add_task(std::bind(&BlockOp::send, block_ops_head, nullptr));
//block_ops_head->send();
}
}
void HDCSCore::aio_read (char* data, uint64_t offset, uint64_t length, void* arg) {
std::shared_ptr<Request> req = std::make_shared<Request>(IO_TYPE_READ, data, offset, length, arg);
request_queue.enqueue(req);
//process_request(req);
}
void HDCSCore::aio_write (char* data, uint64_t offset, uint64_t length, void* arg) {
std::shared_ptr<Request> req = std::make_shared<Request>(IO_TYPE_WRITE, data, offset, length, arg);
//TODO: add TS;
request_queue.enqueue(req);
//process_request(req);
}
void HDCSCore::connect_to_replica (std::vector<std::string> replication_nodes) {
std::string addr;
std::string port;
int colon_pos, last_pos;
char c;
hdcs_ioctx_t* io_ctx;
for (auto &addr_port_str : replication_nodes) {
std::vector<std::string> ip_port;
boost::split(ip_port, addr_port_str, boost::is_any_of(":"));
addr = ip_port[0];
port = ip_port[1];
io_ctx = (hdcs_ioctx_t*)malloc(sizeof(hdcs_ioctx_t));
replication_core_map[addr_port_str] = (void*)io_ctx;
hdcs::networking::ClientOptions client_options;
client_options._session_num = 5;
client_options._io_service_num = 5;
client_options._thd_num_on_one_session = 3;
client_options._process_msg = ([](void* p, std::string s){request_handler(p, s);});
client_options._process_msg_arg = (void*)io_ctx;
io_ctx->conn = new hdcs::networking::Connection(client_options);
io_ctx->conn->connect(addr, port, (hdcs::networking::TCP_COMMUNICATION)); // TCP
//io_ctx->conn->connect(addr, port, (hdcs::networking::RDMA_COMMUNICATION)); //RDMA
hdcs::HDCS_REQUEST_CTX msg_content(HDCS_CONNECT, nullptr, nullptr, 0, name.length(), const_cast<char*>(name.c_str()));
io_ctx->conn->communicate(std::move(std::string(msg_content.data(), msg_content.size())));
}
}
}// core
}// hdcs
| 36.678899 | 183 | 0.697974 | [
"vector"
] |
f63a31c3dc855f146af5af528028f6e3f5cf60ee | 16,990 | cpp | C++ | drlvm/vm/vmcore/src/lil/ipf/m2n_ipf.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 8 | 2015-11-04T06:06:35.000Z | 2021-07-04T13:47:36.000Z | drlvm/vm/vmcore/src/lil/ipf/m2n_ipf.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 1 | 2021-10-17T13:07:28.000Z | 2021-10-17T13:07:28.000Z | drlvm/vm/vmcore/src/lil/ipf/m2n_ipf.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 13 | 2015-11-27T03:14:50.000Z | 2022-02-26T15:12:20.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "Code_Emitter.h"
#include "environment.h"
#include "m2n.h"
#include "m2n_ipf_internal.h"
#include "vm_ipf.h"
#include "vm_threads.h"
#include "open/types.h"
#include "open/vm_util.h"
#include "stub_code_utils.h"
#include "interpreter.h"
#include "exceptions.h"
//////////////////////////////////////////////////////////////////////////
// Utilities
extern "C" void *do_flushrs_asm();
extern "C" void *do_flushrs()
{
return do_flushrs_asm();
} //do_flushrs
// Given a bsp value for register 32 and a stacked register number
// return a pointer to where the stacked register is spilled
uint64* get_stacked_register_address(uint64* bsp, unsigned reg)
{
if (interpreter_enabled()) {
return interpreter.interpreter_get_stacked_register_address(bsp, reg);
}
assert(bsp && 32<=reg && reg<128);
unsigned r = (reg-32)<<3;
uint64 b = (uint64)bsp;
uint64 d4 = b+r;
uint64 d5 = (b&0x1f8)+r;
if (d5>=63*8)
if (d5>=126*8)
d4 += 16;
else
d4 += 8;
return (uint64*)d4;
}
// Get the bsp value for register 32 of the M2nFrame
uint64* m2n_get_bsp(M2nFrame* m2nf)
{
return (uint64*)m2nf;
}
uint64* m2n_get_extra_saved(M2nFrame* m2nf)
{
do_flushrs();
return (uint64*)*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_EXTRA_SAVED_PTR);
}
//////////////////////////////////////////////////////////////////////////
// M2nFrame Interface
//***** Generic Interface
// fill m2n frame as empty
void m2n_null_init(M2nFrame* m2n){
memset(m2n, 0, sizeof(M2nFrame));
}
VMEXPORT // temporary solution for interpreter unplug
M2nFrame* m2n_get_last_frame()
{
return (M2nFrame*)p_TLS_vmthread->last_m2n_frame;
}
VMEXPORT // temporary solution for interpreter unplug
M2nFrame* m2n_get_last_frame(VM_thread* thread)
{
return (M2nFrame*)thread->last_m2n_frame;
}
VMEXPORT // temporary solution for interpreter unplug
void m2n_set_last_frame(M2nFrame* lm2nf)
{
vm_thread_t vm_thread = jthread_self_vm_thread_unsafe();
vm_thread->last_m2n_frame = lm2nf;
}
VMEXPORT
void m2n_set_last_frame(VM_thread* thread, M2nFrame* lm2nf)
{
thread->last_m2n_frame = lm2nf;
}
VMEXPORT // temporary solution for interpreter unplug
M2nFrame* m2n_get_previous_frame(M2nFrame* m2nfl)
{
assert(m2nfl);
do_flushrs();
return (M2nFrame*)*get_stacked_register_address(m2n_get_bsp(m2nfl), M2N_SAVED_M2NFL);
}
ObjectHandles* m2n_get_local_handles(M2nFrame* m2nf)
{
assert(m2nf);
do_flushrs();
return (ObjectHandles*)*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_OBJECT_HANDLES);
}
void m2n_set_local_handles(M2nFrame* m2nf, ObjectHandles* handles)
{
assert(m2nf);
do_flushrs();
uint64* p_head = get_stacked_register_address(m2n_get_bsp(m2nf), M2N_OBJECT_HANDLES);
*p_head = (uint64)handles;
}
NativeCodePtr m2n_get_ip(M2nFrame* m2nf)
{
assert(m2nf);
do_flushrs();
uint64 * UNUSED bsp = (uint64 *)m2nf;
assert(bsp);
return (NativeCodePtr)*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_SAVED_RETURN_ADDRESS);
}
// 20040708 New function - needs proper implementation.
void m2n_set_ip(M2nFrame* lm2nf, NativeCodePtr ip)
{
assert(lm2nf);
LDIE(51, "Not implemented");
}
// sets pointer to the registers used for jvmti PopFrame
void set_pop_frame_registers(M2nFrame* m2nf, Registers* regs) {
// FIXME: not sure we want to support this function on IPF
LDIE(51, "Not implemented");
}
// returns pointer to the registers used for jvmti PopFrame
Registers* get_pop_frame_registers(M2nFrame* m2nf) {
// FIXME: not sure we want to support this function on IPF
LDIE(51, "Not implemented");
return 0;
}
Method_Handle m2n_get_method(M2nFrame* m2nf)
{
assert(m2nf);
do_flushrs();
uint64 * UNUSED bsp = (uint64 *)m2nf;
assert(bsp);
return (Method_Handle)*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_METHOD);
}
// Returns type of noted m2n frame
frame_type m2n_get_frame_type(M2nFrame* m2nf) {
assert(m2nf);
do_flushrs();
uint64 * UNUSED bsp = (uint64 *)m2nf;
assert(bsp);
return (frame_type)*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_FRAME_TYPE);
}
// Sets type of noted m2n frame
void m2n_set_frame_type(M2nFrame* m2nf, frame_type m2nf_type) {
assert(m2nf);
do_flushrs();
uint64 * UNUSED bsp = (uint64 *)m2nf;
assert(bsp);
*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_FRAME_TYPE) = m2nf_type;
}
size_t m2n_get_size() {
return sizeof(M2nFrame);
}
//***** Stub Interface
// Flushes register stack of the current thread into backing store and calls target procedure.
NativeCodePtr m2n_gen_flush_and_call() {
static NativeCodePtr addr = NULL;
if (addr != NULL) {
return addr;
}
tl::MemoryPool mem_pool;
Merced_Code_Emitter emitter(mem_pool, 2, 0);
emitter.disallow_instruction_exchange();
emitter.memory_type_is_unknown();
// We need to remember pfs & b0 here but there is no space to save them in.
// Register stack contains valid outputs and we don't know how many registers are used.
// Memory stack holds output values beyound those 8 which are on register stack.
// The only place is general caller-saves registers. It is save to use them with out preserving
// because they are alredy preserved by the corresponding M2N frame.
// r4 is used to keep a thread pointer...so let's use r5 & r6.
emitter.ipf_mfap(PRESERV_GENERAL_REG1, AR_pfs);
emitter.ipf_mfbr(PRESERV_GENERAL_REG2, BRANCH_RETURN_LINK_REG);
emitter.flush_buffer();
emitter.ipf_flushrs();
emitter.ipf_bricall(br_many, br_sptk, br_none, BRANCH_RETURN_LINK_REG, BRANCH_CALL_REG);
emitter.ipf_mtbr(BRANCH_RETURN_LINK_REG, PRESERV_GENERAL_REG2);
emitter.ipf_mtap(AR_pfs, PRESERV_GENERAL_REG1);
emitter.ipf_brret(br_few, br_sptk, br_none, BRANCH_RETURN_LINK_REG);
addr = finalize_stub(emitter, "");
return addr;
}
unsigned m2n_gen_push_m2n(Merced_Code_Emitter* emitter, Method_Handle method, frame_type current_frame_type, bool handles, unsigned num_on_stack, unsigned num_local, unsigned num_out, bool do_alloc)
{
// Allocate new frame
if (do_alloc) {
emitter->ipf_alloc(M2N_SAVED_PFS, 8, M2N_NUMBER_LOCALS+num_local, num_out, 0);
// The alloc instruction saves pfs, now save return address and GP
emitter->ipf_mfbr(M2N_SAVED_RETURN_ADDRESS, BRANCH_RETURN_LINK_REG);
emitter->ipf_mov (M2N_SAVED_GP, GP_REG);
}
// 20031205: The alloc writes the CFM and the mfpr reads it, so they must be separated by a stop bit, this is a brutal way of achieving this.
emitter->flush_buffer();
// Save predicates, SP, and callee saves general registers
emitter->ipf_adds(M2N_SAVED_SP, num_on_stack, SP_REG);
emitter->ipf_mfpr(M2N_SAVED_PR );
emitter->ipf_mfap(M2N_SAVED_UNAT, AR_unat);
emitter->ipf_mov (M2N_SAVED_R4, 4);
emitter->ipf_mov (M2N_SAVED_R5, 5);
emitter->ipf_mov (M2N_SAVED_R6, 6);
emitter->ipf_mov (M2N_SAVED_R7, 7);
// Set object handles to NULL and set method information
emitter->ipf_mov(M2N_OBJECT_HANDLES, 0);
emit_mov_imm_compactor(*emitter, M2N_METHOD, (uint64)method);
emit_mov_imm_compactor(*emitter, M2N_FRAME_TYPE, (uint64)current_frame_type);
const int P1 = SCRATCH_PRED_REG;
const int P2 = SCRATCH_PRED_REG2;
const int OLD_RSE_MODE = SCRATCH_GENERAL_REG2;
const int NEW_RSE_MODE = SCRATCH_GENERAL_REG3;
// SCRATCH_GENERAL_REG4 & SCRATCH_GENERAL_REG5 are reserved for std places.
const int BSP = SCRATCH_GENERAL_REG6;
const int IMM_8 = SCRATCH_GENERAL_REG7;
const int IMM_1F8 = SCRATCH_GENERAL_REG8;
const int TMP_REG = SCRATCH_GENERAL_REG9;
// Scratch branch register.
const int TMP_BRANCH_REG = 6;
// Switch RSE to "forced lazy" mode. This is required to access RNAT.
emitter->ipf_mfap(OLD_RSE_MODE, AR_rsc);
emitter->ipf_dep(NEW_RSE_MODE, 0, OLD_RSE_MODE, 0, 2);
emitter->ipf_mtap(AR_rsc, NEW_RSE_MODE);
// Flush must be the first instruction in the group.
emitter->flush_buffer();
// Spill parent frames so that corresponding RNAT bits become valid.
emitter->ipf_flushrs();
// Extract backing store pointer
emitter->ipf_mfap(BSP, AR_bsp);
// Remember parent RNAT collection.
emitter->ipf_mfap(M2N_EXTRA_RNAT, AR_rnat);
// TODO: This is not fully legal reset nat bits for the whole m2n frame because it
// contains r4-r7 general registers which may have corresponding unat bits up.
emitter->ipf_mov(M2N_EXTRA_UNAT, 0);
/* The following code spills M2N into backing store.
emitter->ipf_movl(IMM_1F8, 0, (uint64)0x1f8);
emitter->ipf_movl(IMM_8, 0, (uint64)0x8);
// Forcebly spill M2N frame into backing store.
for(int i = M2N_NUMBER_INPUTS; i < M2N_NUMBER_LOCALS; i++) {
emitter->ipf_and(TMP_REG, IMM_1F8, BSP);
emitter->ipf_cmp(icmp_eq, cmp_none, P1, P2, IMM_1F8, TMP_REG);
emitter->ipf_add(BSP, BSP, IMM_8, P1);
emitter->ipf_st_inc_imm(int_mem_size_8, mem_st_spill, mem_none, BSP, 32 + i, 8);
}
// Remember UNAT collection for the current frame.
emitter->ipf_sub(BSP, BSP, IMM_8);
emitter->ipf_mfap(M2N_EXTRA_UNAT, AR_unat);
emitter->ipf_st(int_mem_size_8, mem_st_none, mem_none, BSP, M2N_EXTRA_UNAT);
// Restore original UNAT.
emitter->ipf_mtap(AR_unat, M2N_SAVED_UNAT);
emitter->flush_buffer();
*/
// Switch RSE to the original mode.
emitter->ipf_mtap(AR_rsc, OLD_RSE_MODE);
// Link M2nFrame into list of current thread
size_t offset_lm2nf = (size_t)&((VM_thread*)0)->last_m2n_frame;
emitter->ipf_adds(SCRATCH_GENERAL_REG2, (int)offset_lm2nf, THREAD_PTR_REG);
emitter->ipf_ld(int_mem_size_8, mem_ld_none, mem_none, M2N_SAVED_M2NFL, SCRATCH_GENERAL_REG2);
emitter->ipf_mfap(SCRATCH_GENERAL_REG7, AR_bsp);
emitter->ipf_st(int_mem_size_8, mem_st_none, mem_none, SCRATCH_GENERAL_REG2, SCRATCH_GENERAL_REG7);
return 32+8+M2N_NUMBER_LOCALS;
}
void m2n_gen_set_local_handles(Merced_Code_Emitter* emitter, unsigned src_reg)
{
emitter->ipf_mov(M2N_OBJECT_HANDLES, src_reg);
}
void m2n_gen_set_local_handles_imm(Merced_Code_Emitter* emitter, uint64 imm_val)
{
int64 UNUSED imm = (int64)imm_val;
assert(imm>=-0x200000 && imm<-0x200000);
emitter->ipf_movi(M2N_OBJECT_HANDLES, (int)imm_val);
}
static void m2n_pop_local_handles() {
assert(!hythread_is_suspend_enabled());
exn_rethrow_if_pending();
M2nFrame *m2n = m2n_get_last_frame();
free_local_object_handles2(m2n_get_local_handles(m2n));
}
static void m2n_free_local_handles() {
assert(!hythread_is_suspend_enabled());
if (exn_raised()) {
exn_rethrow();
}
M2nFrame * m2n = m2n_get_last_frame();
// iche free_local_object_handles3(m2n->local_object_handles);
free_local_object_handles3(m2n_get_local_handles(m2n)); // iche
}
void m2n_gen_pop_m2n(Merced_Code_Emitter* emitter, bool handles, M2nPreserveRet preserve_ret, bool do_alloc, unsigned out_reg, int target)
{
unsigned free_target;
if (handles) {
assert(target != -1); // make sure a target has been provided
// Do we need to call free?
free_target = (unsigned) target;
emitter->ipf_cmp(icmp_eq, cmp_none, SCRATCH_PRED_REG, SCRATCH_PRED_REG2, M2N_OBJECT_HANDLES, 0);
emitter->ipf_br(br_cond, br_many, br_spnt, br_none, free_target, SCRATCH_PRED_REG);
}
// Yes, save return register
if (preserve_ret == MPR_Gr) {
emitter->ipf_add(6, RETURN_VALUE_REG, 0);
} else if (preserve_ret == MPR_Fr) {
emitter->ipf_stf_inc_imm(float_mem_size_e, mem_st_spill, mem_none, SP_REG, RETURN_VALUE_REG, unsigned(-16));
}
if (handles) {
emit_call_with_gp(*emitter, (void**)m2n_pop_local_handles, false);
} else {
emit_call_with_gp(*emitter, (void**)m2n_free_local_handles, false);
}
// Restore return register
if (preserve_ret == MPR_Gr) {
emitter->ipf_add(RETURN_VALUE_REG, 6, 0);
} else if (preserve_ret == MPR_Fr) {
emitter->ipf_adds(SP_REG, 16, SP_REG);
emitter->ipf_ldf(float_mem_size_e, mem_ld_fill, mem_none, RETURN_VALUE_REG, SP_REG);
}
if (handles) {
emitter->set_target(free_target);
}
// Unlink the M2nFrame from the list of the current thread
size_t offset_lm2nf = (size_t)&((VM_thread*)0)->last_m2n_frame;
emitter->ipf_adds(SCRATCH_GENERAL_REG2, (int)offset_lm2nf, THREAD_PTR_REG);
emitter->ipf_st(int_mem_size_8, mem_st_none, mem_none, SCRATCH_GENERAL_REG2, M2N_SAVED_M2NFL);
// Restore callee saved general registers, predicates, return address, and pfs
emitter->ipf_mov (7, M2N_SAVED_R7);
emitter->ipf_mov (6, M2N_SAVED_R6);
emitter->ipf_mov (5, M2N_SAVED_R5);
emitter->ipf_mov (4, M2N_SAVED_R4);
emitter->ipf_mtpr( M2N_SAVED_PR);
if (do_alloc) {
emitter->ipf_mov (GP_REG, M2N_SAVED_GP);
emitter->ipf_mtbr(BRANCH_RETURN_LINK_REG, M2N_SAVED_RETURN_ADDRESS);
emitter->ipf_mtap(AR_pfs, M2N_SAVED_PFS);
}
}
void m2n_gen_save_extra_preserved_registers(Merced_Code_Emitter* emitter)
{
unsigned reg;
// Save pointer to saves area
emitter->ipf_mov(M2N_EXTRA_SAVED_PTR, SP_REG);
// Save callee saves floating point registers
for (reg = 2; reg < 6; reg++)
emitter->ipf_stf_inc_imm(float_mem_size_e, mem_st_spill, mem_none, SP_REG, reg, unsigned(-16));
for (reg = 16; reg < 32; reg++)
emitter->ipf_stf_inc_imm(float_mem_size_e, mem_st_spill, mem_none, SP_REG, reg, unsigned(-16));
// Save callee saves branch registers
for (reg = 1; reg < 6; reg++) {
emitter->ipf_mfbr(SCRATCH_GENERAL_REG, reg);
emitter->ipf_st_inc_imm(int_mem_size_8, mem_st_none, mem_none, SP_REG, SCRATCH_GENERAL_REG, unsigned(-8));
}
// Save ar.fpsr, ar.unat, and ar.lc
emitter->ipf_st_inc_imm(int_mem_size_8, mem_st_none, mem_none, SP_REG, SCRATCH_GENERAL_REG, unsigned(-8));
emitter->ipf_mfap(SCRATCH_GENERAL_REG, AR_unat);
emitter->ipf_st_inc_imm(int_mem_size_8, mem_st_none, mem_none, SP_REG, SCRATCH_GENERAL_REG, unsigned(-8));
emitter->ipf_mfap(SCRATCH_GENERAL_REG, AR_lc);
emitter->ipf_st_inc_imm(int_mem_size_8, mem_st_none, mem_none, SP_REG, SCRATCH_GENERAL_REG, unsigned(-24));
// Note that the last postdec (postinc of -24) has created the required scratch area on the memory stack
}
unsigned m2n_get_last_m2n_reg() {
return M2N_SAVED_PFS + M2N_NUMBER_LOCALS - 1;
}
unsigned m2n_get_pfs_save_reg() {
return M2N_SAVED_PFS;
}
unsigned m2n_get_return_save_reg() {
return M2N_SAVED_RETURN_ADDRESS;
}
unsigned m2n_get_gp_save_reg() {
return M2N_SAVED_GP;
}
uint64* m2n_get_arg_word(M2nFrame* m2nf, unsigned n)
{
do_flushrs();
if (n<8)
return get_stacked_register_address(m2n_get_bsp(m2nf), n+32);
else
return ((uint64*)*get_stacked_register_address(m2n_get_bsp(m2nf), M2N_SAVED_SP))+(n-8+2); // +2 is for 16-bytes scratch on mem stack
}
void m2n_push_suspended_frame(M2nFrame* m2nf, Registers* regs)
{
LDIE(86, "check that it works"); // FIXME: check that it works
m2n_push_suspended_frame(p_TLS_vmthread, m2nf, regs);
}
void m2n_push_suspended_frame(VM_thread* thread, M2nFrame* m2nf, Registers* regs)
{
LDIE(51, "Not implemented");
}
M2nFrame* m2n_push_suspended_frame(Registers* regs)
{
LDIE(86, "check that it works"); // FIXME: check that it works
return m2n_push_suspended_frame(p_TLS_vmthread, regs);
}
M2nFrame* m2n_push_suspended_frame(VM_thread* thread, Registers* regs)
{
LDIE(86, "check that it works"); // FIXME: check that it works
M2nFrame* m2nf = (M2nFrame*)STD_MALLOC(sizeof(M2nFrame));
assert(m2nf);
m2n_push_suspended_frame(thread, m2nf, regs);
return m2nf;
}
bool m2n_is_suspended_frame(M2nFrame * m2nf) {
LDIE(51, "Not implemented");
return false;
}
| 33.98 | 198 | 0.703767 | [
"object"
] |
f648fdecc846fbbdc7b5e71fc941597c505ae341 | 14,800 | cpp | C++ | pyis/ops/linear_chain_crf/src/SparseLinearModel.cpp | microsoft/python-inference-script | cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7 | [
"MIT"
] | 5 | 2021-11-29T01:49:22.000Z | 2022-02-23T10:26:46.000Z | pyis/ops/linear_chain_crf/src/SparseLinearModel.cpp | microsoft/python-inference-script | cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7 | [
"MIT"
] | 1 | 2021-11-01T02:22:32.000Z | 2021-11-01T02:22:32.000Z | pyis/ops/linear_chain_crf/src/SparseLinearModel.cpp | microsoft/python-inference-script | cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "SparseLinearModel.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
#include "Common.h"
#include "Sentence.h"
namespace SparseLinearChainCRF {
using namespace std;
namespace {
std::unordered_map<uint16_t, size_t> defaultAttribute;
void PushIndex(unordered_map<uint32_t, size_t>& featureToUid, vector<unordered_map<uint16_t, size_t>>& weightIndex,
uint32_t featId, uint16_t labId, size_t paramId) {
if (featureToUid.find(featId) == featureToUid.end()) {
unordered_map<uint16_t, size_t> newLabelIndex;
weightIndex.push_back(newLabelIndex);
featureToUid.insert(make_pair(featId, weightIndex.size() - 1));
}
const auto& featureIndex = featureToUid.find(featId);
size_t uid = featureIndex->second;
const auto& labelIndex = weightIndex[uid].find(labId);
if (labelIndex == weightIndex[uid].end()) {
weightIndex[uid].insert(make_pair(labId, paramId));
}
}
const int HEADER_SIZE = 4096;
const char* V1_MAGIC_WORD = "__LCCRF__v1";
} // namespace
SparseLinearModel::SparseLinearModel() : m_MaxLabelState(0) {}
SparseLinearModel::SparseLinearModel(const string& filename) {
ifstream stream(filename, ios::in | ios::binary);
Deserialize(stream);
stream.close();
}
SparseLinearModel::SparseLinearModel(istream& stream) { Deserialize(stream); }
void SparseLinearModel::Reset() { memset(m_WeightVector.data(), 0, sizeof(float) * m_WeightVector.size()); }
void SparseLinearModel::Reset(const std::vector<float>& vec) {
LogAssert(vec.size() == m_WeightVector.size(), "Not able to copy vector that has different size");
memcpy(m_WeightVector.data(), vec.data(), sizeof(float) * vec.size());
RefreshCache();
}
bool SparseLinearModel::Serialize(ostream& stream) const {
size_t bytesToWrite = (m_FeatureToUid.size() + 1) * sizeof(uint32_t) * 2 +
m_WeightVector.size() * (sizeof(uint16_t) + sizeof(float)) + HEADER_SIZE;
for (const auto& featureIndex : m_FeatureToUid) {
bytesToWrite += featureIndex.size() * (sizeof(uint32_t) + sizeof(uint16_t));
}
stream.write((char*)&bytesToWrite, sizeof(uint32_t));
char header[HEADER_SIZE];
memset(header, 0, HEADER_SIZE);
strcpy(header, V1_MAGIC_WORD);
stream.write(header, HEADER_SIZE);
uint32_t featureSetSize = (uint32_t)m_FeatureToUid.size();
uint32_t m_MaxLabelState32 = (uint32_t)m_MaxLabelState;
stream.write((char*)&m_MaxLabelState32, sizeof(uint32_t));
stream.write((char*)&featureSetSize, sizeof(uint32_t));
size_t paramsWritten = 0;
for (uint32_t featureSetIter = 0; featureSetIter < featureSetSize; ++featureSetIter) {
const auto& featureIndex = m_FeatureToUid[featureSetIter];
uint32_t numFeatures = (uint32_t)featureIndex.size();
stream.write((char*)&featureSetIter, sizeof(uint32_t));
stream.write((char*)&numFeatures, sizeof(uint32_t));
map<uint32_t, size_t> orderedFeatureIndex(featureIndex.begin(), featureIndex.end());
for (const auto& featureIndexIter : orderedFeatureIndex) {
uint32_t featureId = featureIndexIter.first;
const auto& attributeList = m_WeightIndex[featureIndexIter.second];
uint16_t numAttribute = (uint16_t)attributeList.size();
stream.write((char*)&featureId, sizeof(uint32_t));
stream.write((char*)&numAttribute, sizeof(uint16_t));
map<uint16_t, size_t> orderedAttribute(attributeList.begin(), attributeList.end());
for (const auto& attribute : orderedAttribute) {
uint16_t labelId = attribute.first;
float weight = m_WeightVector[attribute.second];
stream.write((char*)&labelId, sizeof(uint16_t));
stream.write((char*)&weight, sizeof(float));
paramsWritten++;
}
}
}
LogAssert(paramsWritten == m_WeightVector.size(), "Something wrong in serializing the model.");
LogAssert(bytesToWrite + sizeof(uint32_t) == (size_t)stream.tellp(),
"Model file was not correctly written. Some parameters are missing.");
return true;
}
bool SparseLinearModel::Serialize(const std::string& txtModelFile) const {
size_t bytesToWrite = (m_FeatureToUid.size() + 1) * sizeof(uint32_t) * 2 +
m_WeightVector.size() * (sizeof(uint16_t) + sizeof(float)) + HEADER_SIZE;
for (const auto& featureIndex : m_FeatureToUid) {
bytesToWrite += featureIndex.size() * (sizeof(uint32_t) + sizeof(uint16_t));
}
std::ofstream txtModel(txtModelFile.c_str(), std::ofstream::out);
char header[HEADER_SIZE];
memset(header, 0, HEADER_SIZE);
strcpy(header, V1_MAGIC_WORD);
uint32_t featureSetSize = (uint32_t)m_FeatureToUid.size();
uint32_t m_MaxLabelState32 = (uint32_t)m_MaxLabelState;
txtModel << "MaxLabelState:" << m_MaxLabelState << " "
<< "FeatureSetSize:" << featureSetSize << std::endl;
txtModel << std::endl;
size_t paramsWritten = 0;
for (uint32_t featureSetIter = 0; featureSetIter < featureSetSize; ++featureSetIter) {
const auto& featureIndex = m_FeatureToUid[featureSetIter];
uint32_t numFeatures = (uint32_t)featureIndex.size();
txtModel << "FeatureSetIter:" << featureSetIter << " "
<< "NumFeatures:" << numFeatures << std::endl;
txtModel << std::endl;
map<uint32_t, size_t> orderedFeatureIndex(featureIndex.begin(), featureIndex.end());
for (const auto& featureIndexIter : orderedFeatureIndex) {
uint32_t featureId = featureIndexIter.first;
const auto& attributeList = m_WeightIndex[featureIndexIter.second];
uint16_t numAttribute = (uint16_t)attributeList.size();
txtModel << "featureId:" << featureId << " "
<< "numAttribute:" << numAttribute << std::endl;
map<uint16_t, size_t> orderedAttribute(attributeList.begin(), attributeList.end());
for (const auto& attribute : orderedAttribute) {
uint16_t labelId = attribute.first;
float weight = m_WeightVector[attribute.second];
txtModel << labelId << " " << weight << std::endl;
paramsWritten++;
}
txtModel << std::endl;
}
}
LogAssert(paramsWritten == m_WeightVector.size(), "Something wrong in serializing the model.");
txtModel.close();
return true;
}
bool SparseLinearModel::Deserialize(istream& stream) {
m_WeightVector.clear();
m_FeatureToUid.clear();
m_WeightIndex.clear();
uint32_t bytesToRead = 0;
stream.read((char*)&bytesToRead, sizeof(uint32_t));
char header[HEADER_SIZE];
stream.read(header, HEADER_SIZE);
if (strcmp(header, V1_MAGIC_WORD) != 0) {
LogAssert(false, "Model file doesn't match with LCCRF V1 format.");
}
stream.read((char*)&m_MaxLabelState, sizeof(uint32_t));
uint32_t nFeatureSets = 0;
stream.read((char*)&nFeatureSets, sizeof(uint32_t));
m_FeatureToUid.reserve(nFeatureSets);
for (uint32_t featureSetIter = 0; featureSetIter < nFeatureSets; ++featureSetIter) {
unordered_map<uint32_t, size_t> mlgFeatureIdToUid;
uint32_t featureSetId = UINT32_MAX;
uint32_t numFeatures = 0;
stream.read((char*)&featureSetId, sizeof(uint32_t));
stream.read((char*)&numFeatures, sizeof(uint32_t));
mlgFeatureIdToUid.reserve(numFeatures);
LogAssert(featureSetId == featureSetIter, "Model doesn't have all lists of feature sets. Please verify it.");
for (uint32_t featureIter = 0; featureIter < numFeatures; ++featureIter) {
uint32_t featureId = UINT32_MAX;
uint16_t numAttribute = 0;
stream.read((char*)&featureId, sizeof(uint32_t));
stream.read((char*)&numAttribute, sizeof(uint16_t));
unordered_map<uint16_t, size_t> attributes;
attributes.reserve(numAttribute);
for (uint16_t attributeIter = 0; attributeIter < numAttribute; ++attributeIter) {
uint16_t labelId = UINT16_MAX;
float weight = 0.0f;
stream.read((char*)&labelId, sizeof(uint16_t));
stream.read((char*)&weight, sizeof(float));
LogAssert(labelId != UINT16_MAX, "");
LogAssert(weight != 0.0f && !std::isnan(weight), "");
size_t paramId = m_WeightVector.size();
m_WeightVector.push_back(weight);
auto ret = attributes.insert(make_pair(labelId, paramId));
LogAssert(ret.second, "");
}
size_t uid = m_WeightIndex.size();
m_WeightIndex.push_back(std::move(attributes));
auto ret = mlgFeatureIdToUid.insert(make_pair(featureId, uid));
LogAssert(ret.second, "Found duplicate in feature Id. Maybe due to corrupted model file.");
}
m_FeatureToUid.push_back(std::move(mlgFeatureIdToUid));
}
uint32_t bytesRead = (uint32_t)stream.tellg();
LogAssert(bytesRead - sizeof(uint32_t) == bytesToRead, "Invalid model file.");
RefreshCache();
CreateParameterVectorIndex();
return true;
}
bool SparseLinearModel::Deserialize(const std::string& modelFile) {
ifstream stream(modelFile, ios::in | ios::binary);
return Deserialize(stream);
}
void SparseLinearModel::RefreshCache() {
// Create the state-state transition cache
m_TrainsitionCache.reset(new float[m_MaxLabelState * m_MaxLabelState]);
memset(m_TrainsitionCache.get(), 0, m_MaxLabelState * m_MaxLabelState * sizeof(float));
for (int i = 0; i < m_MaxLabelState; ++i) {
size_t id = FindFeautureIdMap(EDGE_FEATURE_SET, i);
if (id != INDEX_NOT_FOUND) {
for (const auto& iter : FindWeightIds(id)) {
m_TrainsitionCache[i * m_MaxLabelState + iter.first] = m_WeightVector[iter.second];
}
}
}
}
size_t SparseLinearModel::Shrink(float truncation) {
vector<unordered_map<uint32_t, size_t>> featureToUid;
vector<unordered_map<uint16_t, size_t>> weightIndex;
vector<float> weightVector;
featureToUid.reserve(m_FeatureToUid.size());
for (int idx = 0; idx < m_FeatureToUid.size(); ++idx) {
unordered_map<uint32_t, size_t> paramMap;
featureToUid.push_back(std::move(paramMap));
}
for (uint32_t setId = 0; setId < m_FeatureToUid.size(); ++setId) {
for (const auto& featureIndex : m_FeatureToUid[setId]) {
uint32_t featId = featureIndex.first;
size_t uid = featureIndex.second;
for (const auto& labelIndex : m_WeightIndex[uid]) {
uint16_t labId = labelIndex.first;
LogAssert(labelIndex.second < m_WeightVector.size(), "labelIndex.second < m_WeightVector.size()");
if (abs(m_WeightVector[labelIndex.second]) > truncation) { // active parameter
size_t newParamId = weightVector.size();
weightVector.push_back(m_WeightVector[labelIndex.second]);
PushIndex(featureToUid[setId], weightIndex, featId, labId, newParamId);
}
}
}
}
m_WeightVector = std::move(weightVector);
m_FeatureToUid = std::move(featureToUid);
m_WeightIndex = std::move(weightIndex);
return m_WeightVector.size();
}
void SparseLinearModel::InsertParameter(uint32_t setId, uint32_t featId, uint16_t labId) {
bool weightExists = false;
size_t uid = FindFeautureIdMap(setId, featId);
if (uid != INDEX_NOT_FOUND) {
const auto& iter = m_WeightIndex[uid].find(labId);
if (iter != m_WeightIndex[uid].end()) {
weightExists = true;
}
}
if (m_FeatureToUid.size() <= setId) {
for (size_t i = m_FeatureToUid.size(); i <= setId; ++i) {
unordered_map<uint32_t, size_t> newFeatureIndex;
m_FeatureToUid.push_back(std::move(newFeatureIndex));
}
}
if (!weightExists) {
size_t newParamId = m_WeightVector.size();
m_WeightVector.push_back(0.0f);
PushIndex(m_FeatureToUid[setId], m_WeightIndex, featId, labId, newParamId);
}
}
size_t SparseLinearModel::Expand(const std::vector<MLGFeatureSentence>& data) {
// Note: m_MaxLabelState is defined by max(label ids) + 1
uint16_t maxLabelId = m_MaxLabelState;
for (const MLGFeatureSentence& sentence : data) {
uint16_t prevLabId = 0;
for (int timeIdx = 0; timeIdx < sentence.Size(); ++timeIdx) {
const auto& word = sentence.GetWord(timeIdx);
uint16_t labId = word.GetLabel();
for (int featIdx = 0; featIdx < word.Size(); ++featIdx) {
const auto setId = std::get<0>(word.GetFeature(featIdx));
const auto featId = std::get<1>(word.GetFeature(featIdx));
InsertParameter(setId, featId, labId);
}
// state
if (timeIdx > 0) {
InsertParameter(EDGE_FEATURE_SET, prevLabId, labId);
}
prevLabId = labId;
if (maxLabelId < labId) {
maxLabelId = labId;
}
}
}
m_MaxLabelState = maxLabelId + 1;
RefreshCache();
CreateParameterVectorIndex();
return m_WeightVector.size();
}
void SparseLinearModel::CreateParameterVectorIndex() {
m_ParameterVectorIndex.clear();
for (const auto& paramIndex : m_WeightIndex) {
vector<pair<uint16_t, size_t>> index;
for (const auto& param : paramIndex) {
index.push_back(param);
}
m_ParameterVectorIndex.push_back(index);
}
}
size_t SparseLinearModel::FindFeautureIdMap(uint32_t setId, uint32_t featId) {
if (m_FeatureToUid.size() > setId) {
const auto& featureMap = m_FeatureToUid[setId];
const auto& iter = featureMap.find(featId);
if (iter != featureMap.end()) {
return iter->second;
}
}
return INDEX_NOT_FOUND;
}
void SparseLinearModel::BackPropagateTransitionWeight() {
size_t N = MaxLabel();
for (uint16_t outgoing = 0; outgoing < N; ++outgoing) {
float* trans = &m_TrainsitionCache[outgoing * N];
size_t uid = FindFeautureIdMap(EDGE_FEATURE_SET, outgoing);
if (uid == INDEX_NOT_FOUND) continue;
for (const auto& iter : FindWeightIds(uid)) {
m_WeightVector[iter.second] = trans[iter.first];
}
}
}
} // namespace SparseLinearChainCRF | 37.18593 | 117 | 0.643851 | [
"vector",
"model"
] |
f64a41d7eb7c9996d7ed232c915c3b281737834d | 2,380 | cc | C++ | ChiTech/ChiMesh/chi_mesh_utilities.cc | Jrgriss2/chi-tech | db75df761d5f25ca4b79ee19d36f886ef240c2b5 | [
"MIT"
] | 7 | 2019-09-10T12:16:08.000Z | 2021-05-06T16:01:59.000Z | ChiTech/ChiMesh/chi_mesh_utilities.cc | Jrgriss2/chi-tech | db75df761d5f25ca4b79ee19d36f886ef240c2b5 | [
"MIT"
] | 72 | 2019-09-04T15:00:25.000Z | 2021-12-02T20:47:29.000Z | ChiTech/ChiMesh/chi_mesh_utilities.cc | Jrgriss2/chi-tech | db75df761d5f25ca4b79ee19d36f886ef240c2b5 | [
"MIT"
] | 41 | 2019-09-02T15:33:31.000Z | 2022-02-10T13:26:49.000Z | #include "chi_mesh.h"
#include "chi_log.h"
extern ChiLog& chi_log;
//###################################################################
/**Tensor product of two vectors.
* \f$ \vec{\vec{T}} = \vec{x} \otimes \vec{y} \f$*/
chi_mesh::TensorRank2Dim3 chi_mesh::Vector3::OTimes(const Vector3& that) const
{
TensorRank2Dim3 new_t;
for (int i=0; i<3; ++i)
for (int j=0; j<3; ++j)
new_t[i](j) = this->operator[](i)*that[j];
return new_t;
}
//###################################################################
/**Dot product of vector and a rank-2 tensor.
* \f$ \vec{w} = \vec{x} \bullet \vec{\vec{T}} \f$*/
chi_mesh::Vector3 chi_mesh::Vector3::Dot(const chi_mesh::TensorRank2Dim3& that) const
{
chi_mesh::Vector3 new_vec;
for (int i=0; i<3; ++i)
new_vec(i) = this->Dot(that.t[i]);
return new_vec;
}
//###################################################################
/**Returns a 3D vector multiplied by the given scalar from the left.
* \f$ \vec{w} = \alpha \vec{x}\f$*/
chi_mesh::Vector3 operator*(const double value,const chi_mesh::Vector3& that)
{
chi_mesh::Vector3 newVector;
newVector.x = that.x*value;
newVector.y = that.y*value;
newVector.z = that.z*value;
return newVector;
}
//###################################################################
/**Dot product of rank-2 tensor with a vector.
* \f$ \vec{w} = \vec{\vec{T}} \bullet \vec{x} \f$*/
chi_mesh::Vector3 chi_mesh::TensorRank2Dim3::Dot(const chi_mesh::Vector3& v) const
{
chi_mesh::Vector3 newVector;
for (int i=0; i<3; ++i)
newVector(i) = t[i].Dot(v);
return newVector;
}
//###################################################################
/**Returns the diagonal of a rank-2 dim-3 tensor as a vector3.
* \f$ \vec{w} = \text{diag} \vec{\vec{T}} \f$*/
chi_mesh::Vector3 chi_mesh::TensorRank2Dim3::Diag() const
{
chi_mesh::Vector3 newVector;
for (int i=0; i<3; ++i)
newVector(i) = t[i][i];
return newVector;
}
//###################################################################
/**Rank-2 dim-3 tensor multiplied from the left with a scalar.
* \f$ \vec{\vec{W}} = \alpha \vec{\vec{T}} \f$*/
chi_mesh::TensorRank2Dim3
operator*(const double value, const chi_mesh::TensorRank2Dim3& that)
{
chi_mesh::TensorRank2Dim3 new_t = that;
for (int i=0; i<3; ++i)
{
for (int j=0; j<3; ++j)
new_t[i](j) *= value;
}
return new_t;
} | 29.02439 | 85 | 0.527311 | [
"vector",
"3d"
] |
f651d516d6948ca299526842ad9b264066dac465 | 1,146 | hpp | C++ | include/world/Core.hpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | include/world/Core.hpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | include/world/Core.hpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | #ifndef GAME_CORE_WORLD_CORE_HPP
#define GAME_CORE_WORLD_CORE_HPP
#include <memory>
#include <mutex>
#include <vector>
#include <SFML/Graphics/Drawable.hpp>
#include "PlayRho/Common/Math.hpp"
#include "PlayRho/Dynamics/StepConf.hpp"
#include "PlayRho/Dynamics/World.hpp"
#include "world/Camera.hpp"
#include "world/contact/ContactListener.hpp"
#include "world/entity/EntityId.hpp"
#include "world/entity/EntityManager.hpp"
#include "world/entity/Factory.hpp"
namespace World {
class Core : public sf::Drawable {
public:
Core(std::unique_ptr<Entity::Factory> entityFactory, const sf::FloatRect& viewRect);
void update();
void draw(sf::RenderTarget& target, sf::RenderStates) const override;
bool loadMap(const std::string& file);
bool addEntity(Entity::Id entityId, playrho::Length2D position, playrho::LinearVelocity2D velocity);
private:
std::shared_ptr<playrho::World> _world;
playrho::StepConf _stepConf;
std::unique_ptr<Entity::Factory> _entityFactory;
Contact::Listener _contactListener;
Camera _camera;
Entity::Manager _entityManager;
mutable std::mutex _entityMutex;
};
} /* namespace World */
#endif
| 24.913043 | 102 | 0.763525 | [
"vector"
] |
f6586ec0ac09c5500103aa2d93e0ab77980a391f | 3,935 | cpp | C++ | src/c++/lib/reference/Contig.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 13 | 2018-02-09T22:59:39.000Z | 2021-11-29T06:33:22.000Z | src/c++/lib/reference/Contig.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 17 | 2018-01-26T11:36:07.000Z | 2022-02-03T18:48:43.000Z | src/c++/lib/reference/Contig.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 4 | 2018-10-19T20:00:00.000Z | 2020-10-29T14:44:06.000Z | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file Contig.
**
** \brief See Contig.hh
**
** \author Come Raczy
**/
#include <algorithm>
#include <numeric>
#include <boost/bind.hpp>
#include "reference/Contig.hh"
namespace isaac
{
namespace reference
{
static const ContigId INVALID_CONTIG_ID = ContigId(0) - 1;
static std::size_t roundToPadding(const std::size_t size, const std::size_t padding)
{
return (((size + padding - 1) / padding) * padding);
}
static std::size_t genomeSize(
const isaac::reference::SortedReferenceMetadata::Contigs &contigList,
const std::size_t padding,
const std::size_t spacing)
{
return std::accumulate(
contigList.begin(), contigList.end(),
size_t(0), [padding, spacing](const std::size_t sum, const SortedReferenceMetadata::Contig &contig)
{ return sum + roundToPadding(contig.totalBases_ + spacing, padding);}) + spacing;
}
/**
* \brief construct a reference memory block with contigs placed so that there is at least
* spacing number of bytes between them and spacing number of bytes after the last contig
*
* @param spacing The minimum number of bytes allocated in front of each contig and after the last contig that are not part of any contig.
* This allows for fast and simple mismatch counting that does not need to consider the edge cases
* @param padding No two contigs will produce collision when any of their absolute positions is divided by padding. This way
* the memory offsets can be unambiguously mapped back to contig index with a simple division and a lookup.
*/
template <typename AllocatorT>
BasicContigList<AllocatorT>::BasicContigList(
const isaac::reference::SortedReferenceMetadata::Contigs &contigMetadataList,
const std::size_t spacing):
contigIdFromScaledOffset_(TRANSLATION_TABLE_SIZE, INVALID_CONTIG_ID),
referenceSequence_(genomeSize(contigMetadataList, ISAAC_CONTIG_LENGTH_MIN, spacing))
{
this->reserve(contigMetadataList.size() + 1);
ReferenceSequenceIterator b = referenceSequence_.begin();
std::transform(
contigMetadataList.begin(), contigMetadataList.end(), std::back_inserter(base()),
[this, &b, spacing](const isaac::reference::SortedReferenceMetadata::Contig &contigMetadata)
{
Contig ret(contigMetadata.index_, contigMetadata.name_, contigMetadata.decoy_, b + spacing, b + spacing + contigMetadata.totalBases_);
b += roundToPadding(contigMetadata.totalBases_ + spacing, ISAAC_CONTIG_LENGTH_MIN);
ISAAC_ASSERT_MSG(referenceSequence_.end() >= b, "Overrun");
return ret;
});
// the fake one which is there just to provide spacing for the last real one
this->push_back(Contig(-1, "", false, b + spacing, b + spacing));
for (ContigId contigId = 0; contigId < size() - 1; ++contigId)
{
for (std::size_t offset = contigBeginOffset(contigId); offset < contigBeginOffset(contigId + 1); offset += ISAAC_CONTIG_LENGTH_MIN)
{
contigIdFromScaledOffset_[offset / ISAAC_CONTIG_LENGTH_MIN] = contigId;
}
}
// remove fake one to avoid messing up end();
this->pop_back();
const std::size_t decoys =
std::count_if(begin(), end(), [](const Contig &contig){return contig.isDecoy();});
ISAAC_THREAD_CERR << "Generated " << size() << " contigs of which " << decoys << " are decoys" << std::endl;
}
template class BasicContigList<common::NumaAllocator<char, 0> >;
} // namespace reference
} // namespace isaac
| 39.747475 | 146 | 0.695299 | [
"transform"
] |
2cf9da2ace6512ee76237b48998b814824930f16 | 957 | cpp | C++ | src/MenusAndToolbars/StatusBar/StatusBar.cpp | ericfont/Examples_wxWidgets | 5cd123eff9a5f9971413ec2f8effc15b76622987 | [
"MIT"
] | 70 | 2019-11-18T15:04:23.000Z | 2022-03-28T22:42:16.000Z | src/MenusAndToolbars/StatusBar/StatusBar.cpp | gammasoft71/Examples.wxWidgets | c710f31c29d502fee699f044014a5eae4ce6ef22 | [
"MIT"
] | 10 | 2020-11-18T02:37:11.000Z | 2021-09-16T17:05:29.000Z | src/MenusAndToolbars/StatusBar/StatusBar.cpp | gammasoft71/Examples.wxWidgets | c710f31c29d502fee699f044014a5eae4ce6ef22 | [
"MIT"
] | 10 | 2021-05-14T11:41:42.000Z | 2022-03-20T00:38:17.000Z | #include <vector>
#include <wx/wx.h>
#include <wx/artprov.h>
namespace Examples {
class Frame : public wxFrame {
public:
Frame() : wxFrame(nullptr, wxID_ANY, "Statusbar example") {
SetStatusBar(statusBar);
std::vector statusWidths = {80, 80, -1};
std::vector statusStyles = {wxSB_SUNKEN, wxSB_SUNKEN, wxSB_SUNKEN};
statusBar->SetFieldsCount(statusWidths.size());
statusBar->SetStatusWidths(statusWidths.size(), statusWidths.data());
statusBar->SetStatusStyles(statusStyles.size(), statusStyles.data());
statusBar->SetStatusText("Status One");
statusBar->SetStatusText("Status Two", 1);
statusBar->SetStatusText("Status Three", 2);
}
private:
wxStatusBar* statusBar = new wxStatusBar(this);
};
class Application : public wxApp {
bool OnInit() override {
(new Frame())->Show();
return true;
}
};
}
wxIMPLEMENT_APP(Examples::Application);
| 26.583333 | 75 | 0.654127 | [
"vector"
] |
2cfaf4da1f680611c6fa4fb71616c442e537274f | 325 | cpp | C++ | DMCpp/GottschlingRepo/c++03/ref_pair.cpp | tzaffi/cpp | 43d99e70d8fa712f90ea0f6147774e4e0f2b11da | [
"MIT"
] | 27 | 2017-12-27T14:35:02.000Z | 2021-01-31T14:28:17.000Z | DMCpp/GottschlingRepo/c++03/ref_pair.cpp | tzaffi/cpp | 43d99e70d8fa712f90ea0f6147774e4e0f2b11da | [
"MIT"
] | 52 | 2017-12-07T14:54:33.000Z | 2018-06-28T02:14:07.000Z | DMCpp/GottschlingRepo/c++03/ref_pair.cpp | tzaffi/cpp | 43d99e70d8fa712f90ea0f6147774e4e0f2b11da | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | #include <iostream>
#include <vector>
#include <functional>
#include <iterator>
using namespace std;
int main (int argc, char* argv[])
{
vector<int> v1(3);
pair<vector<int>&, int> p(v1, 8), p2(p);
copy(p2.first.begin(), p2.first.end(), ostream_iterator<int>(cout, ", ")); cout << endl;
return 0 ;
}
| 18.055556 | 92 | 0.609231 | [
"vector"
] |
2cfcc95ddaa44ace455479d7ed32763b6e05de98 | 5,254 | cpp | C++ | higan/gb/cartridge/cartridge.cpp | defparam/higan-verilog | 25fe4d87f8ac31888e816c9c29498f41ad869e1e | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | higan/gb/cartridge/cartridge.cpp | defparam/higan-verilog | 25fe4d87f8ac31888e816c9c29498f41ad869e1e | [
"Intel",
"ISC"
] | null | null | null | higan/gb/cartridge/cartridge.cpp | defparam/higan-verilog | 25fe4d87f8ac31888e816c9c29498f41ad869e1e | [
"Intel",
"ISC"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | #include <gb/gb.hpp>
namespace GameBoy {
Cartridge cartridge;
#include "mbc0/mbc0.cpp"
#include "mbc1/mbc1.cpp"
#include "mbc1m/mbc1m.cpp"
#include "mbc2/mbc2.cpp"
#include "mbc3/mbc3.cpp"
#include "mbc5/mbc5.cpp"
#include "mbc6/mbc6.cpp"
#include "mbc7/mbc7.cpp"
#include "mmm01/mmm01.cpp"
#include "huc1/huc1.cpp"
#include "huc3/huc3.cpp"
#include "tama/tama.cpp"
#include "serialization.cpp"
auto Cartridge::load() -> bool {
information = {};
rom = {};
ram = {};
rtc = {};
mapper = &mbc0;
accelerometer = false;
rumble = false;
if(Model::GameBoy()) {
if(auto loaded = platform->load(ID::GameBoy, "Game Boy", "gb")) {
information.pathID = loaded.pathID();
} else return false;
}
if(Model::GameBoyColor()) {
if(auto loaded = platform->load(ID::GameBoyColor, "Game Boy Color", "gbc")) {
information.pathID = loaded.pathID();
} else return false;
}
if(Model::SuperGameBoy()) {
if(auto loaded = platform->load(ID::SuperGameBoy, "Game Boy", "gb")) {
information.pathID = loaded.pathID();
} else return false;
}
if(auto fp = platform->open(pathID(), "manifest.bml", File::Read, File::Required)) {
information.manifest = fp->reads();
} else return false;
//todo: temporary hack so (type=) node lookup works; replace with a proper game/memory parser
auto document = BML::unserialize(string{information.manifest}.replace("type: ", "type:"));
information.title = document["game/label"].text();
auto mapperID = document["game/board"].text();
if(mapperID == "MBC0" ) mapper = &mbc0;
if(mapperID == "MBC1" ) mapper = &mbc1;
if(mapperID == "MBC1M") mapper = &mbc1m;
if(mapperID == "MBC2" ) mapper = &mbc2;
if(mapperID == "MBC3" ) mapper = &mbc3;
if(mapperID == "MBC5" ) mapper = &mbc5;
if(mapperID == "MBC6" ) mapper = &mbc6;
if(mapperID == "MBC7" ) mapper = &mbc7;
if(mapperID == "MMM01") mapper = &mmm01;
if(mapperID == "HuC1" ) mapper = &huc1;
if(mapperID == "HuC3" ) mapper = &huc3;
if(mapperID == "TAMA" ) mapper = &tama;
accelerometer = (bool)document["game/board/accelerometer"];
rumble = (bool)document["game/board/rumble"];
if(auto node = document["game/memory(type=ROM)"]) {
rom.size = max(0x4000, node["size"].natural());
rom.data = (uint8*)memory::allocate(rom.size, 0xff);
if(auto name = node["name"].text()) {
if(auto fp = platform->open(pathID(), name, File::Read, File::Required)) {
fp->read(rom.data, min(rom.size, fp->size()));
}
}
}
if(auto node = document["game/memory(type=NVRAM)"]) {
ram.size = node["size"].natural();
ram.data = (uint8*)memory::allocate(ram.size, 0xff);
if(auto name = node["name"].text()) {
if(auto fp = platform->open(pathID(), name, File::Read, File::Optional)) {
fp->read(ram.data, min(ram.size, fp->size()));
}
}
}
if(auto node = document["game/memory(type=RTC)"]) {
rtc.size = node["size"].natural();
rtc.data = (uint8*)memory::allocate(rtc.size, 0xff);
if(auto name = node["name"].text()) {
if(auto fp = platform->open(pathID(), name, File::Read, File::Optional)) {
fp->read(rtc.data, min(rtc.size, fp->size()));
}
}
}
information.sha256 = Hash::SHA256(rom.data, rom.size).digest();
return true;
}
auto Cartridge::save() -> void {
auto document = BML::unserialize(string{information.manifest}.replace("type: ", "type:"));
if(auto node = document["game/memory(type=NVRAM)"]) {
if(auto name = node["name"].text()) {
if(auto fp = platform->open(pathID(), name, File::Write)) {
fp->write(ram.data, ram.size);
}
}
}
if(auto node = document["game/memory(type=RTC)"]) {
if(auto name = node["name"].text()) {
if(auto fp = platform->open(pathID(), name, File::Write)) {
fp->write(rtc.data, rtc.size);
}
}
}
}
auto Cartridge::unload() -> void {
delete[] rom.data;
delete[] ram.data;
delete[] rtc.data;
rom = {};
ram = {};
rtc = {};
}
auto Cartridge::readIO(uint16 addr) -> uint8 {
if(addr == 0xff50) return 0xff;
if(bootromEnable) {
const uint8* data = nullptr;
if(Model::GameBoy()) data = system.bootROM.dmg;
if(Model::GameBoyColor()) data = system.bootROM.cgb;
if(Model::SuperGameBoy()) data = system.bootROM.sgb;
if(addr >= 0x0000 && addr <= 0x00ff) return data[addr];
if(addr >= 0x0200 && addr <= 0x08ff && Model::GameBoyColor()) return data[addr - 0x100];
}
return mapper->read(addr);
}
auto Cartridge::writeIO(uint16 addr, uint8 data) -> void {
if(bootromEnable && addr == 0xff50) {
bootromEnable = false;
return;
}
mapper->write(addr, data);
}
auto Cartridge::power() -> void {
for(uint n = 0x0000; n <= 0x7fff; n++) bus.mmio[n] = this;
for(uint n = 0xa000; n <= 0xbfff; n++) bus.mmio[n] = this;
bus.mmio[0xff50] = this;
bootromEnable = true;
mapper->power();
}
auto Cartridge::second() -> void {
mapper->second();
}
auto Cartridge::Memory::read(uint address) const -> uint8 {
if(!size) return 0xff;
if(address >= size) address %= size;
return data[address];
}
auto Cartridge::Memory::write(uint address, uint8 byte) -> void {
if(!size) return;
if(address >= size) address %= size;
data[address] = byte;
}
}
| 28.247312 | 95 | 0.613057 | [
"model"
] |
2cfd016cbe830d6df66f4ddc8dea3de8e8d63229 | 135 | cpp | C++ | Source/EditorLib/Controls/ISignificantControl.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 35 | 2017-04-07T22:49:41.000Z | 2021-08-03T13:59:20.000Z | Source/EditorLib/Controls/ISignificantControl.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 1 | 2017-04-13T17:43:54.000Z | 2017-04-15T04:17:37.000Z | Source/EditorLib/Controls/ISignificantControl.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 7 | 2019-03-11T19:26:53.000Z | 2021-03-04T07:17:10.000Z | #include "ISignificantControl.h"
std::vector<ISignificantControl*> ISignificantControl::list_ = std::vector<ISignificantControl*>(); | 45 | 99 | 0.792593 | [
"vector"
] |
2cfd878fbf9ec21bbd1158206fae5053b8bdefc7 | 5,324 | cpp | C++ | jerome/npc/detail/evaluation.cpp | leuski-ict/jerome | 6141a21c50903e98a04c79899164e7d0e82fe1c2 | [
"Apache-2.0"
] | 3 | 2018-06-11T10:48:54.000Z | 2021-05-30T07:10:15.000Z | jerome/npc/detail/evaluation.cpp | leuski-ict/jerome | 6141a21c50903e98a04c79899164e7d0e82fe1c2 | [
"Apache-2.0"
] | null | null | null | jerome/npc/detail/evaluation.cpp | leuski-ict/jerome | 6141a21c50903e98a04c79899164e7d0e82fe1c2 | [
"Apache-2.0"
] | null | null | null | //
// evaluation.cpp
//
// Created by Anton Leuski on 9/16/15.
// Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved.
//
// This file is part of Jerome.
//
// 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 "evaluation.hpp"
#include <jerome/types.hpp>
#include <jerome/ir/training/Data.hpp>
#include <jerome/ir/evaluation/accumulators/statistics_fwd.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/f_measure.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/accuracy.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/average_precision.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/function.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/average.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/vector.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/query.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/micro_average.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/macro_average.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/p_false_alarm.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/p_miss.hpp>
#include <jerome/ir/evaluation/accumulators/statistics/non_relevant_count.hpp>
#include <jerome/npc/model.hpp>
#include <jerome/npc/detail/Ranker_impl.hpp>
#include <jerome/npc/factories/ReporterFactory.hpp>
// the accumultor-based experiment report, while flexible, slows compilation down
// significantly. Introduce this lflag while developing to speed up the compilation.
// should be off in release code
// Note : Android NDK has problem building the whole reports. Thus needs to switch on this flag to build.
#ifdef __ANDROID__
#define JEROME_INTERNAL_BASIC_REPORT
#endif
#ifndef JEROME_INTERNAL_BASIC_REPORT
//#define JEROME_INTERNAL_BASIC_REPORT
#endif
#ifdef JEROME_INTERNAL_BASIC_REPORT
//#undef JEROME_INTERNAL_BASIC_REPORT
#endif
namespace jerome {
namespace npc {
namespace detail {
using namespace jerome::ir::evaluation::accumulators;
Result<double> evaluate(const Record& inReporterModel,
std::ostream& os,
const Data& inTestData,
const Ranker& inRanker)
{
typedef ir::evaluation::RankedListCollector<
Data::answer_type,
boost::accumulators::features<
tag::average_precision
, tag::accuracy
#ifndef JEROME_INTERNAL_BASIC_REPORT
, tag::fmeasure
, tag::precision
, tag::recall
, tag::pfalsealarm
, tag::pmiss
, tag::total_size
, tag::retrieved_count
, tag::relevant_count
, tag::non_relevant_count
, tag::relevant_size
#endif
, tag::vector
, tag::map_of<tag::is_relevant>
, tag::query<Data::question_type>
>
> ranked_list_collector_type;
// struct echo
// {
// void operator () (
// typename ranked_list_collector_type::result_type const& x) const
// {
// log::info() << fmeasure(x) << " " << retrieved_count(x) << " "
// << relevant_count(x) << " " << precision(x) << " "
// << recall(x) << " " << relevant_size(x);
// }
//
// };
typedef ir::evaluation::DataSetCollector<
typename ranked_list_collector_type::result_type,
boost::accumulators::features<
tag::sample_count
#ifndef JEROME_INTERNAL_BASIC_REPORT
, tag::average_of<tag::retrieved_count>
, tag::average_of<tag::relevant_count>
, tag::average_of<tag::non_relevant_count>
, tag::average_of<tag::relevant_size>
, tag::average_of<tag::total_size>
, tag::micro_average_of<tag::fmeasure>
, tag::micro_average_of<tag::precision>
, tag::micro_average_of<tag::recall>
, tag::micro_average_of<tag::pmiss>
, tag::micro_average_of<tag::pfalsealarm>
, tag::macro_average_of<tag::average_precision>
#endif
, tag::macro_average_of<tag::accuracy>
#ifndef JEROME_INTERNAL_BASIC_REPORT
, tag::macro_average_of<tag::fmeasure>
, tag::macro_average_of<tag::precision>
, tag::macro_average_of<tag::recall>
, tag::macro_average_of<tag::pmiss>
, tag::macro_average_of<tag::pfalsealarm>
#endif
, tag::vector
>
> data_set_collector_type;
auto testSet = inRanker.testSetWithData(inTestData);
typedef jerome::ir::evaluation::DataSetEvaluator<
Ranker,
decltype(testSet),
data_set_collector_type,
ranked_list_collector_type
> evaluator_type;
evaluator_type eval(inRanker, testSet);
auto y = eval(inRanker.values());
auto r = ReporterFactory<decltype(y)>::sharedInstance().make(inReporterModel, os);
if (!r) return r.error();
r.value().report(inRanker, y);
return macro_average_of<tag::accuracy>(y);
}
}
}
}
| 32.864198 | 105 | 0.700789 | [
"vector",
"model"
] |
fa05f8fa32ffdc6bdb42ada35eb8e4f42f873243 | 1,452 | cpp | C++ | Implementations/11 - Math (4)/Polynomials (6)/Linear Recurrence.cpp | Senpat/USACO | 7f65e083e70c10b43224c6e1acbab79af249b942 | [
"MIT"
] | null | null | null | Implementations/11 - Math (4)/Polynomials (6)/Linear Recurrence.cpp | Senpat/USACO | 7f65e083e70c10b43224c6e1acbab79af249b942 | [
"MIT"
] | null | null | null | Implementations/11 - Math (4)/Polynomials (6)/Linear Recurrence.cpp | Senpat/USACO | 7f65e083e70c10b43224c6e1acbab79af249b942 | [
"MIT"
] | null | null | null | /**
* Description: Berlekamp-Massey Algo
* Source: http://codeforces.com/blog/entry/61306
* Verification: http://codeforces.com/contest/506/problem/E
*/
using namespace vecOp;
struct linRec {
vector<vi> seq;
vi x, fail, delta, des;
linRec (vi _x) {
x = _x; seq.pb({}); int best = 0;
F0R(i,sz(x)) {
delta.pb(mul(-1,x[i]));
F0R(j,sz(seq.back())) AD(delta[i],mul(x[i-j-1],seq.back()[j]));
if (delta[i] == 0) continue;
fail.pb(i); if (sz(seq) == 1) { seq.pb(vi(i+1)); continue; }
int k = mul(mul(-1,delta[i]),inv(delta[fail[best]]));
vi cur(i-fail[best]-1); cur.pb(mul(-1,k));
for (auto a: seq[best]) cur.pb(mul(a,k));
cur += seq.back();
if (i-fail[best]+sz(seq[best]) >= sz(seq.back())) best = sz(seq)-1;
// take fail vector with smallest size
seq.pb(cur);
}
F0Rd(i,sz(seq.back())) des.pb(mul(-1,seq.back()[i]));
des.pb(1);
}
vi getPo(int n) {
if (n == 0) return {1};
vi x = getPo(n/2); x = rem(x*x,des);
if (n&1) {
vi v = {0,1};
x = rem(x*v,des);
}
return x;
}
int get(int n) {
vi t = getPo(n);
int ANS = 0;
F0R(i,sz(t)) AD(ANS,mul(t[i],x[i]));
return ANS;
}
}; | 26.888889 | 80 | 0.433196 | [
"vector"
] |
fa0706bc94316fdf406594babbd2b327d57d831f | 4,998 | cpp | C++ | marchingCubes/obsolete/mpi/Implementations/MpiAlgo.cpp | sandialabs/miniIsosurface | be51bb54e553e357a50cd95fce2fe9a5798993e4 | [
"BSD-3-Clause"
] | 5 | 2019-07-14T02:12:28.000Z | 2022-01-20T06:29:30.000Z | marchingCubes/obsolete/mpi/Implementations/MpiAlgo.cpp | sandialabs/miniIsosurface | be51bb54e553e357a50cd95fce2fe9a5798993e4 | [
"BSD-3-Clause"
] | null | null | null | marchingCubes/obsolete/mpi/Implementations/MpiAlgo.cpp | sandialabs/miniIsosurface | be51bb54e553e357a50cd95fce2fe9a5798993e4 | [
"BSD-3-Clause"
] | 3 | 2019-12-19T16:31:53.000Z | 2020-07-24T13:02:20.000Z | /*
* MpiAlgo.cpp
*
* Created on: Aug 17, 2015
* Author: sjmunn
*/
#include "MpiAlgo.h"
template<typename T>
MpiAlgo<T>::MpiAlgo(LoadImage3DMPI<T> & inFileHeader, int inPid, int inProcesses, Timer * inProcessTimer) : MarchAlgorithm<T>(),fileHeader(inFileHeader) {
pID = inPid;
processes=inProcesses;
unsigned maxDim=inFileHeader.getMaxVoumeDimension();
float cubeRootProc = static_cast<float>(inProcesses);
cubeRootProc=cbrt(cubeRootProc);
int nCbrtProcesses=static_cast<int>(cubeRootProc);
if (nCbrtProcesses<2) nCbrtProcesses=2;
grainDim=maxDim/nCbrtProcesses;
processTimer = inProcessTimer;
}
template<typename T>
MpiAlgo<T>::~MpiAlgo() {
// TODO Auto-generated destructor stub
}
template<typename T>
unsigned MpiAlgo<T>::numBlocks(const Range oneDRange) {
unsigned numberOfBlocks = (oneDRange.end() - oneDRange.begin() + oneDRange.grain() - 1)
/ oneDRange.grain();
return numberOfBlocks;
}
template<typename T>
bool MpiAlgo<T>::testZeroExtent(unsigned * extent) {
/*
* True if zero extent
* False if extent non-zero
*/
unsigned pseudoVolume=0;
for (int i=0;i<6;++i) {
pseudoVolume+=extent[i];
}
if (pseudoVolume == 0) {
return true;
}
else {
return false;
}
}
template<typename T>
void MpiAlgo<T>::march(GeneralContext<T> &data) {
// // DEBUGGER
// int i = 0;
// char hostname[256];
// gethostname(hostname, sizeof(hostname));
// printf("PID %d on %s ready for attach\n", getpid(), hostname);
// fflush(stdout);
// while (0==i) {
// sleep(5);
// }
const unsigned *dims = fileHeader.getVolumeDimensions();
CLOG(logYAML) << "Marching cubes algorithm: MPI without OpenMP";
data.doc.add("Marching cubes algorithm", "MPI without OpenMP");
/*
* fullRange is the entire image volume
*/
Range3D fullRange(0, dims[2] - 1, grainDim, 0, dims[1] - 1, grainDim, 0,
dims[0] - 1, grainDim);
fullRange.extent(data.ext);
unsigned numBlockPages = numBlocks(fullRange.pages());
unsigned numBlockRows = numBlocks(fullRange.rows());
unsigned numBlockCols = numBlocks(fullRange.cols());
unsigned nblocks = numBlockPages * numBlockRows * numBlockCols;
unsigned nblocksPerPage = numBlockRows * numBlockCols;
CLOG(logDEBUG1) << "Number of OpenMP Blocks " << nblocks;
this->setGlobalVariables(data);
TriangleMesh_t processMesh;
PointMap_t processPointMap;
DuplicateRemover processDuplicateRemover;
// Distributing jobs
unsigned blocksPerProcess;
unsigned startBlockNum;
unsigned endBlockNum;
if (nblocks>processes) {
blocksPerProcess=nblocks/processes;
startBlockNum=pID*blocksPerProcess;
// The last process picks up the extra blocks..
if (pID==processes-1) {
endBlockNum=nblocks;
}
else {
endBlockNum=startBlockNum+blocksPerProcess;
}
}
else {
if (pID<nblocks) {
startBlockNum=pID;
endBlockNum=pID+1;
}
else {
startBlockNum = endBlockNum = 0;
}
}
unsigned progressCount=0;
for (unsigned blockNum=startBlockNum;blockNum<endBlockNum;++blockNum) {
CLOG(logINFO) << "Process number " << pID << " has completed " << progressCount << " blocks of " << endBlockNum - startBlockNum;
LoadImage3DMPI<float_t> fileData(fileHeader); // We will need multiple data loaders in MPI
unsigned blockPageIdx = blockNum / nblocksPerPage;
unsigned blockRowIdx = (blockNum % nblocksPerPage) / numBlockCols;
unsigned blockColIdx = (blockNum % nblocksPerPage) % numBlockCols;
unsigned pfrom = blockPageIdx * fullRange.pages().grain();
unsigned pto = std::min(pfrom + fullRange.pages().grain(),
fullRange.pages().end());
unsigned rfrom = blockRowIdx * fullRange.rows().grain();
unsigned rto = std::min(rfrom + fullRange.rows().grain(),
fullRange.rows().end());
unsigned cfrom = blockColIdx * fullRange.cols().grain();
unsigned cto = std::min(cfrom + fullRange.cols().grain(),
fullRange.cols().end());
Range3D blockRange(pfrom, pto, rfrom, rto, cfrom, cto);
unsigned blockExtent[6];
blockRange.extent(blockExtent);
fileData.setBlockExtent(blockExtent);
processTimer->pause();
fileData.readBlockData(data.imageIn);
processTimer->resume();
data.imageIn.setToMPIdataBlock();
data.imageIn.setMPIorigin(blockExtent[0],blockExtent[2],blockExtent[4]);
//unsigned approxNumberOfEdges = 3*(pto-pfrom)*(rto-rfrom)*(cto-cfrom);
//unsigned mapSize = approxNumberOfEdges / 8 + 6; // Approx # of edges in map
MarchAlgorithm<T>::extractIsosurfaceFromBlock(data.imageIn, blockExtent,
data.isoval, processPointMap, *(this->globalEdgeIndices), processMesh);
processDuplicateRemover.setArrays(processPointMap);
progressCount++;
}
if (processDuplicateRemover.getSize() > 3) {
processDuplicateRemover.sortYourSelf();
processDuplicateRemover.getNewIndices();
buildMesh(data.mesh,processMesh,processDuplicateRemover);
}
CLOG(logDEBUG1) << "Mesh verts: " << data.mesh.numberOfVertices();
CLOG(logDEBUG1) << "Mesh tris: " << data.mesh.numberOfTriangles();
}
// Must instantiate class for separate compilation
template class MpiAlgo<float_t> ;
| 28.078652 | 154 | 0.720688 | [
"mesh"
] |
fa0899e505efa0f764083efe2ac24a7b8d0fedba | 150 | hpp | C++ | dbscan.hpp | drdanz/dbscan | 4e40a2287ac2b85c5759865ef1aecb77150a30e9 | [
"MIT"
] | 6 | 2021-04-18T08:07:44.000Z | 2022-03-16T05:24:23.000Z | dbscan.hpp | drdanz/dbscan | 4e40a2287ac2b85c5759865ef1aecb77150a30e9 | [
"MIT"
] | null | null | null | dbscan.hpp | drdanz/dbscan | 4e40a2287ac2b85c5759865ef1aecb77150a30e9 | [
"MIT"
] | 3 | 2020-11-28T05:02:49.000Z | 2021-09-17T15:54:23.000Z | #include <vector>
auto dbscan(const std::vector<std::pair<float, float>>& data, float eps, int min_pts)
-> std::vector<std::vector<size_t>>; | 37.5 | 86 | 0.666667 | [
"vector"
] |
fa0941394bb378ce332ca5a5c9a80e1aac42aa05 | 2,571 | cpp | C++ | Day10/Day10.cpp | Zhoroaan/adventofcode2021 | 099b6ae8d58032045dfa4c2edc2d7b2f9f0fdab9 | [
"MIT"
] | null | null | null | Day10/Day10.cpp | Zhoroaan/adventofcode2021 | 099b6ae8d58032045dfa4c2edc2d7b2f9f0fdab9 | [
"MIT"
] | null | null | null | Day10/Day10.cpp | Zhoroaan/adventofcode2021 | 099b6ae8d58032045dfa4c2edc2d7b2f9f0fdab9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <stack>
#include <string>
#include <unordered_map>
#include "../Lib/CommonLib.h"
//const char* InputData = "TestInputData.txt";
const char* InputData = "MyInput.txt";
int64_t CalculateScoreOfLine(const std::string& InBuffer, std::unordered_map<char, std::pair<char, int32_t>>& InTags)
{
std::stack<char> stack;
stack.push(InBuffer[0]);
int64_t score = 0;
for (int charIndex = 1; charIndex < InBuffer.length(); ++charIndex)
{
switch (InBuffer[charIndex])
{
case '(':
case '[':
case '{':
case '<':
{
stack.push(InBuffer[charIndex]);
break;
}
case ')':
case ']':
case '}':
case '>':
{
if (stack.top() != InTags[InBuffer[charIndex]].first) // This is an invalid line
return 0;
stack.pop();
break;
}
}
}
while (!stack.empty())
{
auto firstMatch = std::ranges::find_if(InTags, [character = stack.top()](const std::pair<char, std::pair<char, int32_t>>& InElement)
{
return InElement.second.first == character;
});
if (firstMatch == InTags.end())
continue;
//std::cout << firstMatch->first;
int32_t pointForChar = firstMatch->second.second;
score = (score * 5) + pointForChar;
stack.pop();
}
//std::cout << " - " << score << " total points." << std::endl;
return score;
}
int main(int argc, char* argv[])
{
Timer fullTime("Day10 full time");
std::ifstream inputDataStream;
inputDataStream.open(InputData);
if (!inputDataStream.is_open())
{
std::cerr << "Incorrect path to input data" << std::endl;
return 1;
}
std::string buffer;
std::unordered_map<char, std::pair<char, int32_t>> matchingCloseTags;
matchingCloseTags[')'] = std::pair('(', 1);
matchingCloseTags[']'] = std::pair('[', 2);
matchingCloseTags['}'] = std::pair('{', 3);
matchingCloseTags['>'] = std::pair('<', 4);
std::vector<int64_t> scores;
while (std::getline(inputDataStream, buffer))
{
const int64_t score = CalculateScoreOfLine(buffer, matchingCloseTags);
// A score of 0 is an invalid line
if (score != 0)
scores.push_back(score);
}
std::ranges::sort(scores);
std::cout << "Middle score: " << scores[scores.size() / 2] << std::endl;
return 0;
}
| 27.063158 | 140 | 0.543368 | [
"vector"
] |
fa09720fc90d0b98d770f3c7cfaa6c20b3e7fa9a | 7,314 | cc | C++ | src/runtime/registry.cc | BaldLee/tvm | b53472c7b6afa34260afeffc5f088591352c58c3 | [
"Apache-2.0"
] | 10 | 2019-03-09T07:51:56.000Z | 2021-09-14T03:06:20.000Z | src/runtime/registry.cc | BaldLee/tvm | b53472c7b6afa34260afeffc5f088591352c58c3 | [
"Apache-2.0"
] | 9 | 2021-10-20T13:48:52.000Z | 2021-12-09T07:14:24.000Z | src/runtime/registry.cc | BaldLee/tvm | b53472c7b6afa34260afeffc5f088591352c58c3 | [
"Apache-2.0"
] | 7 | 2021-08-03T14:24:00.000Z | 2021-11-11T04:34:37.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* \file registry.cc
* \brief The global registry of packed function.
*/
#include <dmlc/thread_local.h>
#include <tvm/runtime/c_backend_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/registry.h>
#include <array>
#include <memory>
#include <mutex>
#include <unordered_map>
#include "runtime_base.h"
namespace tvm {
namespace runtime {
struct Registry::Manager {
// map storing the functions.
// We deliberately used raw pointer.
// This is because PackedFunc can contain callbacks into the host language (Python) and the
// resource can become invalid because of indeterministic order of destruction and forking.
// The resources will only be recycled during program exit.
std::unordered_map<std::string, Registry*> fmap;
// mutex
std::mutex mutex;
Manager() {}
static Manager* Global() {
// We deliberately leak the Manager instance, to avoid leak sanitizers
// complaining about the entries in Manager::fmap being leaked at program
// exit.
static Manager* inst = new Manager();
return inst;
}
};
Registry& Registry::set_body(PackedFunc f) { // NOLINT(*)
func_ = f;
return *this;
}
Registry& Registry::Register(const std::string& name, bool can_override) { // NOLINT(*)
Manager* m = Manager::Global();
std::lock_guard<std::mutex> lock(m->mutex);
if (m->fmap.count(name)) {
ICHECK(can_override) << "Global PackedFunc " << name << " is already registered";
}
Registry* r = new Registry();
r->name_ = name;
m->fmap[name] = r;
return *r;
}
bool Registry::Remove(const std::string& name) {
Manager* m = Manager::Global();
std::lock_guard<std::mutex> lock(m->mutex);
auto it = m->fmap.find(name);
if (it == m->fmap.end()) return false;
m->fmap.erase(it);
return true;
}
const PackedFunc* Registry::Get(const std::string& name) {
Manager* m = Manager::Global();
std::lock_guard<std::mutex> lock(m->mutex);
auto it = m->fmap.find(name);
if (it == m->fmap.end()) return nullptr;
return &(it->second->func_);
}
std::vector<std::string> Registry::ListNames() {
Manager* m = Manager::Global();
std::lock_guard<std::mutex> lock(m->mutex);
std::vector<std::string> keys;
keys.reserve(m->fmap.size());
for (const auto& kv : m->fmap) {
keys.push_back(kv.first);
}
return keys;
}
/*!
* \brief Execution environment specific API registry.
*
* This registry stores C API function pointers about
* execution environment(e.g. python) specific API function that
* we need for specific low-level handling(e.g. signal checking).
*
* We only stores the C API function when absolutely necessary (e.g. when signal handler
* cannot trap back into python). Always consider use the PackedFunc FFI when possible
* in other cases.
*/
class EnvCAPIRegistry {
public:
/*!
* \brief Callback to check if signals have been sent to the process and
* if so invoke the registered signal handler in the frontend environment.
*
* When runnning TVM in another langugage(python), the signal handler
* may not be immediately executed, but instead the signal is marked
* in the interpreter state(to ensure non-blocking of the signal handler).
*
* \return 0 if no error happens, -1 if error happens.
*/
typedef int (*F_PyErr_CheckSignals)();
// NOTE: the following function are only registered
// in a python environment.
/*!
* \brief PyErr_CheckSignal function
*/
F_PyErr_CheckSignals pyerr_check_signals = nullptr;
static EnvCAPIRegistry* Global() {
static EnvCAPIRegistry* inst = new EnvCAPIRegistry();
return inst;
}
// register environment(e.g. python) specific api functions
void Register(const std::string& symbol_name, void* fptr) {
if (symbol_name == "PyErr_CheckSignals") {
Update(symbol_name, &pyerr_check_signals, fptr);
} else {
LOG(FATAL) << "Unknown env API " << symbol_name;
}
}
// implementation of tvm::runtime::EnvCheckSignals
void CheckSignals() {
// check python signal to see if there are exception raised
if (pyerr_check_signals != nullptr && (*pyerr_check_signals)() != 0) {
// The error will let FFI know that the frontend environment
// already set an error.
throw EnvErrorAlreadySet("");
}
}
private:
// update the internal API table
template <typename FType>
void Update(const std::string& symbol_name, FType* target, void* ptr) {
FType ptr_casted = reinterpret_cast<FType>(ptr);
if (target[0] != nullptr && target[0] != ptr_casted) {
LOG(WARNING) << "tvm.runtime.RegisterEnvCAPI overrides an existing function " << symbol_name;
}
target[0] = ptr_casted;
}
};
void EnvCheckSignals() { EnvCAPIRegistry::Global()->CheckSignals(); }
} // namespace runtime
} // namespace tvm
/*! \brief entry to to easily hold returning information */
struct TVMFuncThreadLocalEntry {
/*! \brief result holder for returning strings */
std::vector<std::string> ret_vec_str;
/*! \brief result holder for returning string pointers */
std::vector<const char*> ret_vec_charp;
};
/*! \brief Thread local store that can be used to hold return values. */
typedef dmlc::ThreadLocalStore<TVMFuncThreadLocalEntry> TVMFuncThreadLocalStore;
int TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) {
API_BEGIN();
tvm::runtime::Registry::Register(name, override != 0)
.set_body(*static_cast<tvm::runtime::PackedFunc*>(f));
API_END();
}
int TVMFuncGetGlobal(const char* name, TVMFunctionHandle* out) {
API_BEGIN();
const tvm::runtime::PackedFunc* fp = tvm::runtime::Registry::Get(name);
if (fp != nullptr) {
*out = new tvm::runtime::PackedFunc(*fp); // NOLINT(*)
} else {
*out = nullptr;
}
API_END();
}
int TVMFuncListGlobalNames(int* out_size, const char*** out_array) {
API_BEGIN();
TVMFuncThreadLocalEntry* ret = TVMFuncThreadLocalStore::Get();
ret->ret_vec_str = tvm::runtime::Registry::ListNames();
ret->ret_vec_charp.clear();
for (size_t i = 0; i < ret->ret_vec_str.size(); ++i) {
ret->ret_vec_charp.push_back(ret->ret_vec_str[i].c_str());
}
*out_array = dmlc::BeginPtr(ret->ret_vec_charp);
*out_size = static_cast<int>(ret->ret_vec_str.size());
API_END();
}
int TVMFuncRemoveGlobal(const char* name) {
API_BEGIN();
tvm::runtime::Registry::Remove(name);
API_END();
}
int TVMBackendRegisterEnvCAPI(const char* name, void* ptr) {
API_BEGIN();
tvm::runtime::EnvCAPIRegistry::Global()->Register(name, ptr);
API_END();
}
| 31.525862 | 99 | 0.694285 | [
"vector"
] |
fa1df54025e4d19929f269cd1c0cdda5f2c12bda | 4,563 | cpp | C++ | oi/Contest/self/HNOI2017-Virtual-Test/split/brute.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/Contest/self/HNOI2017-Virtual-Test/split/brute.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/Contest/self/HNOI2017-Virtual-Test/split/brute.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <cassert>
#include <cstdio>
#include <cstring>
#include <climits>
#include <set>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#define WMAX 30
#define NMAX 900
#define EMAX 2000
class NetworkFlow {
public:
NetworkFlow(int _n) : n(_n) {}
void link(int u, int v, int c, int w) {
Edge *e = new Edge(v, c, 0, w);
Edge *re = new Edge(u, c, w, w);
e->reverse_edge = re;
re->reverse_edge = e;
G[u].push_back(e);
G[v].push_back(re);
}
void reset() {
for (int u = 1; u <= n; u++) {
for (size_t i = 0; i < G[u].size(); i++) {
G[u][i]->reset();
}
}
}
int dinic(int _s, int _t, int _limit) {
int ret = 0;
s = _s;
t = _t;
limit = _limit;
while (true) {
bfs();
if (!level[t])
break;
memset(cur, 0, sizeof(cur));
ret += dfs(s, INT_MAX);
}
return ret;
}
private:
struct Edge {
Edge(int _to, int _cost, int _flow, int _capacity)
: to(_to), cost(_cost),
initial(_flow), flow(_flow), capacity(_capacity) {}
int to;
int cost;
int initial;
int flow;
int capacity;
Edge *reverse_edge;
void reset() {
flow = initial;
}
bool full() {
return flow == capacity;
}
int remain() {
return capacity - flow;
}
};
int n, s, t, limit;
vector<Edge *> G[NMAX + 10];
int level[NMAX + 10];
size_t cur[NMAX + 10];
void bfs() {
memset(level, 0, sizeof(level));
level[s] = 1;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
for (size_t i = 0; i < G[u].size(); i++) {
Edge *e = G[u][i];
int v = e->to;
if (level[v] || e->full() || e->cost > limit)
continue;
level[v] = level[u] + 1;
q.push(v);
}
}
}
int dfs(int x, int maxflow) {
if (x == t)
return maxflow;
int current = 0;
for (size_t &i = cur[x]; i < G[x].size(); i++) {
Edge *e = G[x][i];
int v = e->to;
if (level[v] != level[x] + 1 || e->full() || e->cost > limit)
continue;
int flow = min(maxflow - current, e->remain());
flow = dfs(v, flow);
e->flow += flow;
e->reverse_edge->flow -= flow;
current += flow;
if (current == maxflow)
break;
}
return current;
}
};
static int n, m, money;
static NetworkFlow *network;
static int tail;
static int sorted[EMAX + 10];
inline int id(int i, int j) {
return (i - 1) * m + j;
}
void initialize() {
scanf("%d%d%d", &n, &m, &money);
network = new NetworkFlow(id(n, m));
tail = 2;
sorted[1] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < m; j++) {
int c, w;
scanf("%d%d", &c, &w);
sorted[tail++] = c;
network->link(id(i, j), id(i, j + 1), c, w);
network->link(id(i, j + 1), id(i, j), c, w);
}
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= m; j++) {
int c, w;
scanf("%d%d", &c, &w);
sorted[tail++] = c;
network->link(id(i, j), id(i + 1, j), c, w);
network->link(id(i + 1, j), id(i, j), c, w);
}
}
sort(sorted + 1, sorted + tail);
tail = unique(sorted + 1, sorted + tail) - sorted;
n = id(n, m);
}
static int limit;
int mincut() {
int ret = INT_MAX;
for (int s = 1; s <= n; s++) {
for (int t = s + 1; t <= n; t++) {
network->reset();
ret = min(ret, network->dinic(s, t, limit));
}
}
return ret;
}
bool test(int w) {
limit = w;
return mincut() > money;
}
int main() {
initialize();
int left = 1, right = tail - 1;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (test(sorted[mid]))
right = mid;
else
left = mid + 1;
}
if (left != right && !test(sorted[left]))
left = right;
if (!test(sorted[left]))
puts("-1");
else
printf("%d\n", sorted[left]);
return 0;
}
| 20.554054 | 73 | 0.419461 | [
"vector"
] |
fa1f9cd7fe6d3a008e21f92dcca2457d019466d5 | 7,150 | cc | C++ | ecclesia/magent/sysmodel/x86/fru.cc | pefoley2/ecclesia-machine-management | e795faafd9d43233a67765daff43bff887c27549 | [
"Apache-2.0"
] | null | null | null | ecclesia/magent/sysmodel/x86/fru.cc | pefoley2/ecclesia-machine-management | e795faafd9d43233a67765daff43bff887c27549 | [
"Apache-2.0"
] | null | null | null | ecclesia/magent/sysmodel/x86/fru.cc | pefoley2/ecclesia-machine-management | e795faafd9d43233a67765daff43bff887c27549 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Google LLC
*
* 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 "ecclesia/magent/sysmodel/x86/fru.h"
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "ecclesia/magent/lib/eeprom/smbus_eeprom.h"
#include "ecclesia/magent/lib/fru/fru.h"
#include "ecclesia/magent/lib/ipmi/ipmi.h"
namespace ecclesia {
namespace {
constexpr int kFruCommonHeaderSize = 8;
constexpr int kFruBoardInfoAreaSizeIndex = 9;
// Given an input string, returns a new string that contains only the portion
// of the string up to (but not including) the first NUL character. If the
// input string contains no NUL characters than the returned value will be
// equal to the input.
//
// The implementation is intended to be equivalent to:
// return s.c_str();
// but we want to avoid this because many linting tools will (correctly) flag
// string -> char* -> string conversions as possible bugs.
std::string StringUpToNul(std::string s) { return s.substr(0, s.find('\0')); }
absl::Status ValidateFruCommonHeader(
absl::Span<const unsigned char> common_header) {
uint8_t sum = 0;
for (size_t i = 0; i < common_header.size(); i++) {
sum += common_header[i];
}
if (sum != 0) {
return absl::InternalError(absl::StrFormat(
"Fru common header has invalid checksum(should be 0, is %u).", sum));
}
return absl::OkStatus();
}
absl::Status GetBoardInfoAreaSize(const SmbusEeprom &eeprom, size_t *size) {
std::vector<unsigned char> value(1);
absl::Status status;
if (1 != eeprom.ReadBytes(kFruBoardInfoAreaSizeIndex,
absl::MakeSpan(value.data(), 1))) {
return absl::InternalError("Failed to read fru BoardInfoArea size.");
}
// size is in multple of 8 bytes
*size = value[0] << 3;
return status;
}
// Processes fru_data into info if the fru_data is valid.
absl::Status ProcessBoardFromFruImage(absl::Span<unsigned char> fru_data,
FruInfo &info) {
absl::Status status = ValidateFruCommonHeader(
absl::MakeSpan(fru_data.data(), kFruCommonHeaderSize));
if (!status.ok()) {
return status;
}
VectorFruImageSource fru_image(fru_data);
BoardInfoArea board_info;
// BoardInfoArea is right after common header,
// starts from offset: 0 + kFruCommonHeaderSize
board_info.FillFromImage(fru_image, 0 + kFruCommonHeaderSize);
info = {
.product_name =
StringUpToNul(board_info.product_name().GetDataAsString()),
.manufacturer =
StringUpToNul(board_info.manufacturer().GetDataAsString()),
.serial_number =
StringUpToNul(board_info.serial_number().GetDataAsString()),
.part_number = StringUpToNul(board_info.part_number().GetDataAsString())};
return absl::OkStatus();
}
absl::Status SmbusGetBoardInfo(const SmbusEeprom &eeprom, FruInfo &info) {
absl::Status status;
size_t board_info_area_size;
status = GetBoardInfoAreaSize(eeprom, &board_info_area_size);
if (!status.ok()) {
return status;
}
// We will read the common header(8 bytes) and BoardInfoArea
std::vector<unsigned char> fru_data(
board_info_area_size + kFruCommonHeaderSize, 0);
// We read from offset 0, this will have common header
eeprom.ReadBytes(0, absl::MakeSpan(fru_data.data(), fru_data.size()));
return ProcessBoardFromFruImage(absl::MakeSpan(fru_data), info);
}
} // namespace
SysmodelFru::SysmodelFru(FruInfo fru_info) : fru_info_(std::move(fru_info)) {}
absl::string_view SysmodelFru::GetManufacturer() const {
return fru_info_.manufacturer;
}
absl::string_view SysmodelFru::GetSerialNumber() const {
return fru_info_.serial_number;
}
absl::string_view SysmodelFru::GetPartNumber() const {
return fru_info_.part_number;
}
absl::optional<SysmodelFru> IpmiSysmodelFruReader::Read() {
if (cached_fru_.has_value()) return cached_fru_;
// 8 bytes header followed by 64 bytes boardinfo.
std::vector<uint8_t> data(72);
absl::Status status = ipmi_intf_->ReadFru(fru_id_, 0, absl::MakeSpan(data));
if (!status.ok()) {
return absl::nullopt;
}
VectorFruImageSource fru_image(absl::MakeSpan(data));
BoardInfoArea bia;
if (bia.FillFromImage(fru_image, 8) == 0) {
return absl::nullopt;
}
FruInfo fru_info;
fru_info.manufacturer = bia.manufacturer().GetDataAsString();
fru_info.product_name = bia.product_name().GetDataAsString();
fru_info.part_number = bia.part_number().GetDataAsString();
fru_info.serial_number = bia.serial_number().GetDataAsString();
cached_fru_.emplace(fru_info);
return cached_fru_;
}
absl::optional<SysmodelFru> SmbusEepromFruReader::Read() {
// If we have something valid in the cache, return it.
if (cached_fru_.has_value()) return cached_fru_;
// Otherwise try to read it into the cache for the first time.
if (!eeprom_) return absl::nullopt;
FruInfo info;
absl::Status status = SmbusGetBoardInfo(*eeprom_, info);
if (!status.ok()) return absl::nullopt;
cached_fru_.emplace(info);
return cached_fru_;
}
absl::optional<SysmodelFru> FileSysmodelFruReader::Read() {
// If we have something valid in the cache, return it.
if (cached_fru_.has_value()) return cached_fru_;
// Otherwise try to read it into the cache for the first time.
std::ifstream file(filepath_, std::ios::binary);
if (!file.is_open()) return absl::nullopt;
// Do not skip newlines in binary mode.
file.unsetf(std::ios::skipws);
std::vector<unsigned char> fru_data;
fru_data.reserve(file.tellg());
fru_data.insert(fru_data.begin(), std::istream_iterator<unsigned char>(file),
std::istream_iterator<unsigned char>());
// Return if we failed to read anything
if (fru_data.empty()) return absl::nullopt;
FruInfo info;
absl::Status status =
ProcessBoardFromFruImage(absl::MakeSpan(fru_data), info);
if (!status.ok()) return absl::nullopt;
cached_fru_.emplace(info);
return cached_fru_;
}
absl::flat_hash_map<std::string, std::unique_ptr<SysmodelFruReaderIntf>>
CreateFruReaders(absl::Span<const SysmodelFruReaderFactory> fru_factories) {
absl::flat_hash_map<std::string, std::unique_ptr<SysmodelFruReaderIntf>>
frus_map;
for (const SysmodelFruReaderFactory &factory : fru_factories) {
frus_map.emplace(factory.Name(), factory.Construct());
}
return frus_map;
}
} // namespace ecclesia
| 32.207207 | 80 | 0.719161 | [
"vector"
] |
fa2012f4670208b31afbf1fab96f71660142ab4f | 4,025 | hpp | C++ | src/color/cmy/get/magenta.hpp | ehtec/color | aa6d8c796303d1f3cfd7361978bfa58eac808b6e | [
"Apache-2.0"
] | 120 | 2015-12-31T22:30:14.000Z | 2022-03-29T15:08:01.000Z | src/color/cmy/get/magenta.hpp | ehtec/color | aa6d8c796303d1f3cfd7361978bfa58eac808b6e | [
"Apache-2.0"
] | 6 | 2016-08-22T02:14:56.000Z | 2021-11-06T22:39:52.000Z | src/color/cmy/get/magenta.hpp | ehtec/color | aa6d8c796303d1f3cfd7361978bfa58eac808b6e | [
"Apache-2.0"
] | 23 | 2016-02-03T01:56:26.000Z | 2021-09-28T16:36:27.000Z | #ifndef color_cmy_get_magenta
#define color_cmy_get_magenta
// ::color::get::magenta( c )
#include "../category.hpp"
#include "../place/place.hpp"
#include "../../generic/get/magenta.hpp"
namespace color
{
namespace get
{
namespace constant
{
namespace cmy { namespace magenta
{
enum formula_enum
{
channel_entity
,hsl_star_entity
// TODO ,hsl_angle_entity
};
}}
}
namespace _internal { namespace cmy
{
namespace magenta
{
template
<
typename category_name
,enum ::color::get::constant::cmy::magenta::formula_enum formula_number = ::color::get::constant::cmy::magenta::channel_entity
>
struct usher
{
typedef category_name category_type;
typedef ::color::model<category_type> model_type;
typedef typename ::color::trait::component< category_name >::return_type return_type;
enum
{
magenta_p = ::color::place::_internal::magenta<category_type>::position_enum
};
static return_type process( model_type const& color_parameter)
{
return color_parameter.template get<magenta_p>();
}
};
template< typename tag_name >
struct usher< ::color::category::cmy< tag_name >, ::color::get::constant::cmy::magenta::hsl_star_entity >
{
typedef ::color::category::cmy< tag_name> category_type;
typedef ::color::model< category_type > model_type;
typedef typename ::color::trait::scalar<category_type>::instance_type scalar_type;
typedef typename ::color::trait::component< category_type >::return_type return_type;
typedef ::color::_internal::diverse< category_type > diverse_type;
typedef ::color::_internal::normalize< category_type > normalize_type;
enum
{
cyan_p = ::color::place::_internal::cyan<category_type>::position_enum
,magenta_p = ::color::place::_internal::magenta<category_type>::position_enum
,yellow_p = ::color::place::_internal::yellow<category_type>::position_enum
};
static return_type process( model_type const& color_parameter )
{
scalar_type c = normalize_type::template process<cyan_p >( color_parameter.template get<cyan_p >( ) );
scalar_type m = normalize_type::template process<magenta_p>( color_parameter.template get<magenta_p>( ) );
scalar_type y = normalize_type::template process<yellow_p >( color_parameter.template get<yellow_p >( ) );
scalar_type result;
while( true )
{
if( m < c ) { result = 0; break; }
if( m < y ) { result = 0; break; }
if( c < y )
{
result = ( m - y ) * ( scalar_type(1) - ( y - c ) );
break;
}
{
result = ( m - c ) * ( scalar_type(1) - ( c - y ) );
break;
}
}
return diverse_type::template process<cyan_p >( result );
}
};
}
}}
template
<
enum ::color::get::constant::cmy::magenta::formula_enum formula_number = ::color::get::constant::cmy::magenta::channel_entity
,typename tag_name
>
inline
typename ::color::model< ::color::category::cmy< tag_name> >::component_const_type
magenta
(
::color::model< ::color::category::cmy< tag_name> > const& color_parameter
)
{
return ::color::get::_internal::cmy::magenta::usher< ::color::category::cmy< tag_name >, formula_number >::process( color_parameter );
}
}
}
#endif
| 30.263158 | 143 | 0.541366 | [
"model"
] |
fa22bf2c632be784785c913bc995809684a8c22b | 12,241 | cpp | C++ | released_plugins/v3d_plugins/terastitcher/src/core/stitcher/TPAlgoMST.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/terastitcher/src/core/stitcher/TPAlgoMST.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/terastitcher/src/core/stitcher/TPAlgoMST.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------------------------
// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome).
// All rights reserved.
//------------------------------------------------------------------------------------------------
/*******************************************************************************************************************************************************************************************
* LICENSE NOTICE
********************************************************************************************************************************************************************************************
* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change
* this code.
********************************************************************************************************************************************************************************************
* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at
* g.iannello@unicampus.it for further details.
* 2. You agree to appropriately cite this work in your related studies and publications.
*
* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316.
*
* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war-
* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the
* copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused and on any theory of liabil-
* ity, 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.
* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without
* specific prior written permission.
********************************************************************************************************************************************************************************************/
#include <limits>
#include "TPAlgoMST.h"
#include "S_config.h"
#include "volumemanager.config.h"
#include "vmStackedVolume.h"
#include "vmVirtualStack.h"
#include "Displacement.h"
using namespace volumemanager;
using namespace iomanager;
//triplet data type definition
typedef struct
{
float V;
float H;
float D;
}triplet;
TPAlgoMST::TPAlgoMST(VirtualVolume * _volume) : TPAlgo(S_FATPM_SP_TREE, _volume)
{
#if S_VERBOSE>4
printf("........in TPAlgoMST::TPAlgoMST(VirtualVolume * _volume)");
#endif
}
/*************************************************************************************************************
* Finds the optimal tile placement on the <volume> object member via Minimum Spanning Tree.
* Stacks matrix is considered as a graph where displacements are edges a nd stacks are nodes. The inverse of
* displacements reliability factors are edge weights, so that a totally unreliable displacement has a weight
* 1/0.0 = +inf and a totally reliable displacement has a weight 1/1.0 = 1. Thus, weights will be in [1, +inf].
* After computing the MST, the absolute tile positions are obtained from a stitchable source stack by means of
* navigating the MST and using the selected displacements.
* PROs: very general method; it ignores bad displacements since they have +inf weight.
* CONs: the best path between two adjacent stacks can pass through many stacks even if the rejected displacem-
* ent is quite reliable, with a very little reliability gain. This implies possible bad absolute posi-
* tions estimations when the path is too long.
**************************************************************************************************************/
void TPAlgoMST::execute() throw (iom::exception)
{
#if S_VERBOSE > 2
printf("....in TPAlgoMST::execute()");
#endif
float ***D; //distances matrix for VHD directions
std::pair<int*,int*> **predecessors; //predecessor matrix for VHD directions
int src_row=0, src_col=0; //source vertex
//0) fixing the source as the stitchable VirtualStack nearest to the top-left corner
float min_distance = std::numeric_limits<float>::infinity();
for(int row=0; row<volume->getN_ROWS(); row++)
for(int col=0; col<volume->getN_COLS(); col++)
if(volume->getSTACKS()[row][col]->isStitchable() && sqrt((float)(row*row+col*col)) < min_distance )
{
src_row = row;
src_col = col;
min_distance = sqrt((float)(row*row+col*col));
}
#if S_VERBOSE > 4
printf("....in TPAlgoMST::execute(): SOURCE is [%d,%d]\n",src_row,src_col);
#endif
//1) initializing distance and predecessor matrix
D = new float **[volume->getN_ROWS()];
predecessors = new std::pair<int*,int*> *[volume->getN_ROWS()];
for(int row=0; row<volume->getN_ROWS(); row++)
{
D[row] = new float*[volume->getN_COLS()];
predecessors[row] = new std::pair<int*,int*>[volume->getN_COLS()];
for(int col=0; col<volume->getN_COLS(); col++)
{
D[row][col] = new float[3];
predecessors[row][col].first = new int[3];
predecessors[row][col].second = new int[3];
for(int k=0; k<3; k++)
{
D[row][col][k] = std::numeric_limits<float>::infinity();
predecessors[row][col].first[k] = predecessors[row][col].second[k] = -1;
}
}
}
D[src_row][src_col][0] = D[src_row][src_col][1] = D[src_row][src_col][2] = 0.0F;
//2) processing edges in order to obtain distance matrix
for(int vertices=1; vertices <= volume->getN_ROWS()*volume->getN_COLS(); vertices++)
for(int E_row = 0; E_row<volume->getN_ROWS(); E_row++)
for(int E_col = 0; E_col<volume->getN_COLS(); E_col++)
for(int k=0; k<3; k++)
{
if(E_row != volume->getN_ROWS() -1 ) //NORTH-SOUTH displacements
{
float weight = SAFE_DIVIDE(1, volume->getSTACKS()[E_row ][E_col]->getSOUTH()[0]->getReliability(direction(k)), S_UNRELIABLE_WEIGHT);
if(D[E_row][E_col][k] + weight < D[E_row+1][E_col][k])
{
D[E_row+1][E_col][k] = D[E_row][E_col][k] + weight;
predecessors[E_row+1][E_col].first[k] = E_row;
predecessors[E_row+1][E_col].second[k] = E_col;
}
if(D[E_row+1][E_col][k] + weight < D[E_row][E_col][k])
{
D[E_row][E_col][k] = D[E_row+1][E_col][k] + weight;
predecessors[E_row][E_col].first[k] = E_row+1;
predecessors[E_row][E_col].second[k]= E_col;
}
}
if(E_col != volume->getN_COLS() -1 ) //EAST-WEST displacements
{
float weight = SAFE_DIVIDE(1, volume->getSTACKS()[E_row ][E_col]->getEAST()[0]->getReliability(direction(k)), S_UNRELIABLE_WEIGHT);
if(D[E_row][E_col][k] + weight < D[E_row][E_col+1][k])
{
D[E_row][E_col+1][k] = D[E_row][E_col][k] + weight;
predecessors[E_row][E_col+1].first[k] = E_row;
predecessors[E_row][E_col+1].second[k]= E_col;
}
if(D[E_row][E_col+1][k] + weight < D[E_row][E_col][k])
{
D[E_row][E_col][k] = D[E_row][E_col+1][k] + weight;
predecessors[E_row][E_col].first[k] = E_row;
predecessors[E_row][E_col].second[k] = E_col+1;
}
}
}
#if S_VERBOSE > 4
for(int k=0; k<3; k++)
{
printf("\n\n....in TPAlgoMST::execute(): %d DIRECTION:\n", k);
printf("\n\t");
for(int col=0; col < volume->getN_COLS(); col++)
printf("[%d]\t\t", col);
printf("\n\n\n");
for(int row = 0; row < volume->getN_ROWS(); row++)
{
printf("[%d]\t",row);
for(int col= 0; col < volume->getN_COLS(); col++)
printf("(%d,%d)\t", predecessors[row][col].first[k], predecessors[row][col].second[k]);
printf("\n\n\n");
}
printf("\n");
printf("\n\t");
for(int col=0; col < volume->getN_COLS(); col++)
printf("[%d]\t\t", col);
printf("\n\n\n");
for(int row = 0; row < volume->getN_ROWS(); row++)
{
printf("[%d]\t",row);
for(int col= 0; col < volume->getN_COLS(); col++)
printf("%8.3f\t", D[row][col][k]);
printf("\n\n\n");
}
printf("\n");
}
#endif
//3) resetting to 0 all stacks absolute coordinates
for(int row = 0; row<volume->getN_ROWS(); row++)
for(int col = 0; col<volume->getN_COLS(); col++)
{
volume->getSTACKS()[row][col]->setABS_V(0);
volume->getSTACKS()[row][col]->setABS_H(0);
volume->getSTACKS()[row][col]->setABS_D(0);
}
//4) assigning absolute coordinates using predecessors matrix
for(int row = 0; row<volume->getN_ROWS(); row++)
{
for(int col = 0; col<volume->getN_COLS(); col++)
{
if(!(row == src_row && col == src_col))
{
for(int k=0; k<3; k++)
{
VirtualStack *source, *dest, *v, *u;
source = volume->getSTACKS()[src_row][src_col];
dest = volume->getSTACKS()[row][col];
v = dest;
#if S_VERBOSE > 4
printf("S[%d,%d] [%d]_path:\n", k, row, col);
#endif
while (v != source)
{
int u_row, u_col;
u_row = predecessors[v->getROW_INDEX()][v->getCOL_INDEX()].first[k];
if(u_row>= volume->getN_ROWS() || u_row < 0)
throw iom::exception("...in TPAlgoMST::execute(): error in the predecessor matrix");
u_col = (int) predecessors[v->getROW_INDEX()][v->getCOL_INDEX()].second[k];
if(u_col>= volume->getN_COLS() || u_col < 0)
throw iom::exception("...in TPAlgoMST::execute(): error in the predecessor matrix");
u = volume->getSTACKS()[u_row][u_col ];
#if S_VERBOSE > 4
printf("\t[%d,%d] (ABS_[%d] = %d %+d)\n",u->getROW_INDEX(), u->getCOL_INDEX(), k, dest->getABS(k), u->getDisplacement(v)->getDisplacement(direction(k)));
#endif
dest->setABS(dest->getABS(k) + u->getDisplacement(v)->getDisplacement(direction(k)), k);
v = u;
if(dest->isStitchable() && !(v->isStitchable()))
printf("\nWARNING! in TPAlgoMST::execute(): direction %d: VirtualStack [%d,%d] is passing through VirtualStack [%d,%d], that is NOT STITCHABLE\n", k, row, col, v->getROW_INDEX(), v->getCOL_INDEX());
}
#if S_VERBOSE > 4
printf("\n");
#endif
}
#if S_VERBOSE > 4
system("PAUSE");
#endif
}
}
}
//5) translating stacks absolute coordinates by choosing VirtualStack[0][0] as the new source
int trasl_X = volume->getSTACKS()[0][0]->getABS_V();
int trasl_Y = volume->getSTACKS()[0][0]->getABS_H();
int trasl_Z = volume->getSTACKS()[0][0]->getABS_D();
for(int row = 0; row<volume->getN_ROWS(); row++)
{
for(int V_col = 0; V_col<volume->getN_COLS(); V_col++)
{
volume->getSTACKS()[row][V_col]->setABS_V(volume->getSTACKS()[row][V_col]->getABS_V()-trasl_X);
volume->getSTACKS()[row][V_col]->setABS_H(volume->getSTACKS()[row][V_col]->getABS_H()-trasl_Y);
volume->getSTACKS()[row][V_col]->setABS_D(volume->getSTACKS()[row][V_col]->getABS_D()-trasl_Z);
}
}
//deallocating distance matrix and predecessor matrix
for(int row=0; row<volume->getN_ROWS(); row++)
{
for(int col=0; col<volume->getN_COLS(); col++)
{
delete[] D[row][col];
delete[] predecessors[row][col].first;
delete[] predecessors[row][col].second;
}
delete[] D[row];
delete[] predecessors[row];
}
delete[] D;
delete[] predecessors;
}
| 45.505576 | 206 | 0.575443 | [
"object",
"3d"
] |
fa2485e971066862918e2858fbc863747e5d4b00 | 726 | cpp | C++ | Dataset/Leetcode/valid/56/688.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/56/688.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/56/688.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
static bool cmp(const vector<int>& a,const vector<int>& b){return a[0]<b[0];}
vector<vector<int>> XXX(vector<vector<int>>& intervals) {
vector<vector<int>> ans;
if (intervals.size()==0) return ans;
sort(intervals.begin(),intervals.end(),cmp);
int l=intervals[0][0],r=intervals[0][1];
for (int i=1;i<intervals.size();i++)
{
if (r>=intervals[i][0]&&r<intervals[i][1]) r=intervals[i][1];
else
if (r<intervals[i][0]) {
ans.push_back({l,r});
l=intervals[i][0];
r=intervals[i][1];
}
}
ans.push_back({l,r});
return ans;
}
};
| 30.25 | 81 | 0.491736 | [
"vector"
] |
fa28d4162af13c8936489ada96aaed841d2ccb9e | 91,883 | cpp | C++ | WebKit/Source/ThirdParty/ANGLE/src/compiler/glslang_lex.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/ThirdParty/ANGLE/src/compiler/glslang_lex.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/ThirdParty/ANGLE/src/compiler/glslang_lex.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | #line 17 "compiler/glslang.l"
//
// Copyright (c) 2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is auto-generated by generate_glslang_lexer.sh. DO NOT EDIT!
#line 13 "compiler/glslang_lex.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
/* For convenience, these vars (plus the bison vars far below)
are macros in the reentrant scanner. */
#define yyin yyg->yyin_r
#define yyout yyg->yyout_r
#define yyextra yyg->yyextra_r
#define yyleng yyg->yyleng_r
#define yytext yyg->yytext_r
#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno)
#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
#define yy_flex_debug yyg->yy_flex_debug_r
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin ,yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
/* Note: We specifically omit the test for yy_rule_can_match_eol because it requires
* access to the local variable yy_act. Since yyless() is a macro, it would break
* existing scanners that call yyless() from OUTSIDE yylex.
* One obvious solution it to make yy_act a global. I tried that, and saw
* a 5% performance hit in a non-yylineno scanner, because yy_act is
* normally declared as a register variable-- so it is not worth it.
*/
#define YY_LESS_LINENO(n) \
do { \
int yyl;\
for ( yyl = n; yyl < yyleng; ++yyl )\
if ( yytext[yyl] == '\n' )\
--yylineno;\
}while(0)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = yyg->yy_hold_char; \
YY_RESTORE_YY_MORE_OFFSET \
yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
void yyrestart (FILE *input_file ,yyscan_t yyscanner );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
void yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
void yypop_buffer_state (yyscan_t yyscanner );
static void yyensure_buffer_stack (yyscan_t yyscanner );
static void yy_load_buffer_state (yyscan_t yyscanner );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
void *yyalloc (yy_size_t ,yyscan_t yyscanner );
void *yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
void yyfree (void * ,yyscan_t yyscanner );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define yywrap(n) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
static int yy_get_next_buffer (yyscan_t yyscanner );
static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
yyg->yytext_ptr = yy_bp; \
yyleng = (size_t) (yy_cp - yy_bp); \
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
#define YY_NUM_RULES 145
#define YY_END_OF_BUFFER 146
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[411] =
{ 0,
0, 0, 0, 0, 0, 0, 146, 144, 143, 143,
128, 134, 139, 123, 124, 132, 131, 120, 129, 127,
133, 92, 92, 121, 117, 135, 122, 136, 140, 88,
125, 126, 138, 88, 88, 88, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
88, 88, 88, 118, 137, 119, 130, 3, 4, 3,
142, 145, 141, 114, 100, 119, 108, 103, 98, 106,
96, 107, 97, 95, 2, 1, 99, 94, 90, 91,
0, 0, 92, 126, 118, 125, 115, 111, 113, 112,
116, 88, 104, 110, 88, 88, 88, 88, 88, 88,
88, 88, 88, 88, 17, 88, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 20, 22,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 105, 109, 5, 141,
0, 1, 94, 0, 0, 93, 89, 101, 102, 48,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 18, 88, 88,
88, 88, 88, 88, 88, 88, 26, 88, 88, 88,
88, 88, 88, 88, 88, 23, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 0, 95,
0, 94, 88, 28, 88, 88, 85, 88, 88, 88,
88, 88, 88, 88, 21, 51, 88, 88, 88, 88,
88, 56, 70, 88, 88, 88, 88, 88, 88, 88,
88, 67, 9, 33, 34, 35, 88, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
88, 54, 29, 88, 88, 88, 88, 88, 88, 36,
37, 38, 27, 88, 88, 88, 15, 42, 43, 44,
49, 12, 88, 88, 88, 88, 81, 82, 83, 88,
30, 71, 25, 78, 79, 80, 7, 75, 76, 77,
88, 24, 73, 88, 88, 39, 40, 41, 88, 88,
88, 88, 88, 88, 88, 88, 88, 68, 88, 88,
88, 88, 88, 88, 88, 50, 88, 87, 88, 88,
19, 88, 88, 88, 88, 69, 64, 59, 88, 88,
88, 88, 88, 74, 55, 88, 62, 32, 88, 84,
63, 47, 57, 88, 88, 88, 88, 88, 88, 88,
88, 58, 31, 88, 88, 88, 8, 88, 88, 88,
88, 88, 52, 13, 88, 14, 88, 88, 16, 65,
88, 88, 88, 60, 88, 88, 88, 53, 72, 61,
11, 66, 6, 86, 10, 45, 88, 88, 46, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 1, 1, 1, 5, 6, 1, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 16, 16, 16, 20, 20, 21, 22, 23,
24, 25, 26, 1, 27, 27, 28, 29, 30, 27,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 32, 31, 31,
33, 1, 34, 35, 31, 1, 36, 37, 38, 39,
40, 41, 42, 43, 44, 31, 45, 46, 47, 48,
49, 50, 31, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[64] =
{ 0,
1, 1, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 3, 3, 3, 3, 3,
1, 1, 1, 1, 1, 1, 3, 3, 3, 3,
4, 4, 1, 1, 1, 3, 3, 3, 3, 3,
3, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 1,
1, 1, 1
} ;
static yyconst flex_int16_t yy_base[416] =
{ 0,
0, 0, 61, 62, 71, 0, 606, 607, 607, 607,
581, 42, 129, 607, 607, 580, 126, 607, 125, 123,
137, 149, 157, 578, 607, 175, 578, 44, 607, 0,
607, 607, 120, 95, 103, 142, 146, 136, 156, 552,
168, 162, 551, 120, 158, 545, 173, 558, 172, 178,
111, 186, 554, 607, 159, 607, 607, 607, 607, 582,
607, 607, 0, 607, 607, 607, 607, 607, 607, 607,
607, 607, 607, 222, 607, 0, 607, 228, 254, 262,
281, 0, 290, 607, 607, 607, 571, 607, 607, 607,
570, 0, 607, 607, 546, 539, 542, 550, 549, 536,
551, 538, 544, 532, 529, 542, 529, 526, 526, 532,
520, 527, 524, 534, 520, 526, 529, 530, 0, 204,
529, 207, 515, 528, 519, 521, 511, 525, 522, 524,
507, 512, 509, 498, 183, 512, 508, 510, 499, 502,
212, 507, 499, 511, 186, 504, 607, 607, 607, 0,
306, 0, 316, 332, 270, 342, 0, 607, 607, 0,
496, 500, 509, 506, 490, 490, 161, 505, 502, 502,
500, 497, 489, 495, 482, 493, 496, 0, 493, 481,
488, 485, 489, 482, 471, 470, 483, 486, 483, 478,
469, 294, 474, 477, 468, 465, 469, 475, 466, 457,
460, 458, 468, 454, 452, 452, 454, 451, 462, 461,
278, 456, 451, 440, 320, 458, 460, 449, 348, 354,
360, 366, 450, 0, 448, 336, 0, 440, 438, 446,
435, 452, 441, 370, 0, 0, 435, 445, 445, 430,
373, 0, 0, 432, 376, 433, 427, 426, 427, 426,
379, 0, 0, 0, 0, 0, 422, 423, 428, 419,
432, 427, 426, 418, 422, 414, 417, 421, 426, 425,
416, 0, 0, 422, 411, 411, 416, 415, 412, 0,
0, 0, 0, 402, 414, 416, 0, 0, 0, 0,
0, 0, 404, 405, 399, 409, 0, 0, 0, 400,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
407, 0, 0, 405, 401, 0, 0, 0, 397, 393,
398, 388, 401, 387, 400, 389, 396, 0, 394, 396,
380, 389, 395, 390, 378, 0, 380, 0, 379, 382,
0, 371, 370, 370, 383, 0, 385, 0, 384, 383,
368, 381, 368, 0, 0, 371, 0, 0, 363, 0,
0, 0, 0, 360, 371, 364, 368, 303, 297, 288,
300, 0, 0, 283, 290, 269, 0, 277, 274, 255,
232, 255, 0, 0, 244, 0, 236, 226, 0, 0,
225, 208, 211, 0, 185, 202, 131, 0, 0, 0,
0, 0, 0, 0, 0, 0, 134, 117, 0, 607,
398, 400, 402, 406, 142
} ;
static yyconst flex_int16_t yy_def[416] =
{ 0,
410, 1, 411, 411, 410, 5, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 412,
410, 410, 410, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 410, 410, 410, 410, 410, 410, 410,
410, 410, 413, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 414, 410, 410, 410, 410,
410, 415, 410, 410, 410, 410, 410, 410, 410, 410,
410, 412, 410, 410, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 410, 410, 410, 413,
410, 414, 410, 410, 410, 410, 415, 410, 410, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 410, 410,
410, 410, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
412, 412, 412, 412, 412, 412, 412, 412, 412, 0,
410, 410, 410, 410, 410
} ;
static yyconst flex_int16_t yy_nxt[671] =
{ 0,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 23, 23, 23, 23,
24, 25, 26, 27, 28, 29, 30, 30, 30, 30,
30, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 30, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 30, 30, 30, 54,
55, 56, 57, 59, 59, 65, 66, 90, 91, 60,
60, 8, 61, 62, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 63, 63, 63,
63, 63, 63, 8, 8, 8, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
8, 8, 8, 8, 67, 70, 72, 74, 74, 74,
74, 74, 74, 93, 157, 75, 95, 96, 73, 71,
76, 97, 68, 98, 94, 123, 409, 99, 141, 124,
77, 78, 142, 79, 79, 79, 79, 79, 80, 78,
408, 83, 83, 83, 83, 83, 83, 100, 81, 85,
82, 107, 147, 108, 407, 103, 81, 101, 81, 104,
102, 110, 109, 125, 105, 86, 81, 87, 88, 111,
106, 112, 119, 116, 113, 82, 126, 132, 128, 120,
114, 117, 229, 230, 133, 134, 121, 137, 204, 148,
138, 143, 118, 129, 135, 144, 130, 136, 139, 216,
406, 217, 405, 205, 145, 140, 74, 74, 74, 74,
74, 74, 153, 153, 153, 153, 153, 153, 396, 184,
404, 151, 185, 186, 190, 211, 187, 154, 188, 397,
403, 151, 191, 212, 402, 401, 78, 154, 79, 79,
79, 79, 79, 80, 78, 400, 80, 80, 80, 80,
80, 80, 399, 81, 156, 156, 156, 156, 156, 156,
155, 81, 155, 81, 398, 156, 156, 156, 156, 156,
156, 81, 78, 395, 83, 83, 83, 83, 83, 83,
254, 255, 256, 394, 393, 219, 392, 219, 275, 81,
220, 220, 220, 220, 220, 220, 276, 391, 390, 81,
153, 153, 153, 153, 153, 153, 280, 281, 282, 389,
388, 221, 387, 221, 386, 154, 222, 222, 222, 222,
222, 222, 288, 289, 290, 154, 156, 156, 156, 156,
156, 156, 220, 220, 220, 220, 220, 220, 220, 220,
220, 220, 220, 220, 222, 222, 222, 222, 222, 222,
222, 222, 222, 222, 222, 222, 297, 298, 299, 304,
305, 306, 308, 309, 310, 316, 317, 318, 58, 58,
58, 58, 92, 92, 150, 150, 152, 385, 152, 152,
384, 383, 382, 381, 380, 379, 378, 377, 376, 375,
374, 373, 372, 371, 370, 369, 368, 367, 366, 365,
364, 363, 362, 361, 360, 359, 358, 357, 356, 355,
354, 353, 352, 351, 350, 349, 348, 347, 346, 345,
344, 343, 342, 341, 340, 339, 338, 337, 336, 335,
334, 333, 332, 331, 330, 329, 328, 327, 326, 325,
324, 323, 322, 321, 320, 319, 315, 314, 313, 312,
311, 307, 303, 302, 301, 300, 296, 295, 294, 293,
292, 291, 287, 286, 285, 284, 283, 279, 278, 277,
274, 273, 272, 271, 270, 269, 268, 267, 266, 265,
264, 263, 262, 261, 260, 259, 258, 257, 253, 252,
251, 250, 249, 248, 247, 246, 245, 244, 243, 242,
241, 240, 239, 238, 237, 236, 235, 234, 233, 232,
231, 228, 227, 226, 225, 224, 223, 218, 215, 214,
213, 210, 209, 208, 207, 206, 203, 202, 201, 200,
199, 198, 197, 196, 195, 194, 193, 192, 189, 183,
182, 181, 180, 179, 178, 177, 176, 175, 174, 173,
172, 171, 170, 169, 168, 167, 166, 165, 164, 163,
162, 161, 160, 159, 158, 149, 146, 131, 127, 122,
115, 89, 84, 69, 64, 410, 7, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410
} ;
static yyconst flex_int16_t yy_chk[671] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 3, 4, 12, 12, 28, 28, 3,
4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 13, 17, 19, 20, 20, 20,
20, 20, 20, 33, 415, 21, 34, 34, 19, 17,
21, 35, 13, 35, 33, 44, 408, 35, 51, 44,
21, 22, 51, 22, 22, 22, 22, 22, 22, 23,
407, 23, 23, 23, 23, 23, 23, 36, 22, 26,
22, 38, 55, 38, 397, 37, 23, 36, 22, 37,
36, 39, 38, 45, 37, 26, 23, 26, 26, 39,
37, 39, 42, 41, 39, 22, 45, 49, 47, 42,
39, 41, 167, 167, 49, 49, 42, 50, 135, 55,
50, 52, 41, 47, 49, 52, 47, 49, 50, 145,
396, 145, 395, 135, 52, 50, 74, 74, 74, 74,
74, 74, 78, 78, 78, 78, 78, 78, 381, 120,
393, 74, 120, 120, 122, 141, 120, 78, 120, 381,
392, 74, 122, 141, 391, 388, 79, 78, 79, 79,
79, 79, 79, 79, 80, 387, 80, 80, 80, 80,
80, 80, 385, 79, 155, 155, 155, 155, 155, 155,
81, 80, 81, 79, 382, 81, 81, 81, 81, 81,
81, 80, 83, 380, 83, 83, 83, 83, 83, 83,
192, 192, 192, 379, 378, 151, 376, 151, 211, 83,
151, 151, 151, 151, 151, 151, 211, 375, 374, 83,
153, 153, 153, 153, 153, 153, 215, 215, 215, 371,
370, 154, 369, 154, 368, 153, 154, 154, 154, 154,
154, 154, 226, 226, 226, 153, 156, 156, 156, 156,
156, 156, 219, 219, 219, 219, 219, 219, 220, 220,
220, 220, 220, 220, 221, 221, 221, 221, 221, 221,
222, 222, 222, 222, 222, 222, 234, 234, 234, 241,
241, 241, 245, 245, 245, 251, 251, 251, 411, 411,
411, 411, 412, 412, 413, 413, 414, 367, 414, 414,
366, 365, 364, 359, 356, 353, 352, 351, 350, 349,
347, 345, 344, 343, 342, 340, 339, 337, 335, 334,
333, 332, 331, 330, 329, 327, 326, 325, 324, 323,
322, 321, 320, 319, 315, 314, 311, 300, 296, 295,
294, 293, 286, 285, 284, 279, 278, 277, 276, 275,
274, 271, 270, 269, 268, 267, 266, 265, 264, 263,
262, 261, 260, 259, 258, 257, 250, 249, 248, 247,
246, 244, 240, 239, 238, 237, 233, 232, 231, 230,
229, 228, 225, 223, 218, 217, 216, 214, 213, 212,
210, 209, 208, 207, 206, 205, 204, 203, 202, 201,
200, 199, 198, 197, 196, 195, 194, 193, 191, 190,
189, 188, 187, 186, 185, 184, 183, 182, 181, 180,
179, 177, 176, 175, 174, 173, 172, 171, 170, 169,
168, 166, 165, 164, 163, 162, 161, 146, 144, 143,
142, 140, 139, 138, 137, 136, 134, 133, 132, 131,
130, 129, 128, 127, 126, 125, 124, 123, 121, 118,
117, 116, 115, 114, 113, 112, 111, 110, 109, 108,
107, 106, 105, 104, 103, 102, 101, 100, 99, 98,
97, 96, 95, 91, 87, 60, 53, 48, 46, 43,
40, 27, 24, 16, 11, 7, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410,
410, 410, 410, 410, 410, 410, 410, 410, 410, 410
} ;
/* Table of booleans, true if rule could match eol. */
static yyconst flex_int32_t yy_rule_can_match_eol[146] =
{ 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, };
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
/*
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
This file contains the Lex specification for GLSL ES.
Based on ANSI C grammar, Lex specification:
http://www.lysator.liu.se/c/ANSI-C-grammar-l.html
IF YOU MODIFY THIS FILE YOU ALSO NEED TO RUN generate_glslang_lexer.sh,
WHICH GENERATES THE GLSL ES LEXER (glslang_lex.cpp).
*/
#include "compiler/glslang.h"
#include "compiler/ParseHelper.h"
#include "compiler/util.h"
#include "glslang_tab.h"
/* windows only pragma */
#ifdef _MSC_VER
#pragma warning(disable : 4102)
#endif
#define YY_USER_ACTION yylval->lex.line = yylineno;
#define YY_INPUT(buf, result, max_size) \
result = string_input(buf, max_size, yyscanner);
static int string_input(char* buf, int max_size, yyscan_t yyscanner);
static int check_type(yyscan_t yyscanner);
static int reserved_word(yyscan_t yyscanner);
#define INITIAL 0
#define COMMENT 1
#define FIELDS 2
#define YY_EXTRA_TYPE TParseContext*
/* Holds the entire state of the reentrant scanner. */
struct yyguts_t
{
/* User-defined. Not touched by flex. */
YY_EXTRA_TYPE yyextra_r;
/* The rest are the same as the globals declared in the non-reentrant scanner. */
FILE *yyin_r, *yyout_r;
size_t yy_buffer_stack_top; /**< index of top of stack. */
size_t yy_buffer_stack_max; /**< capacity of stack. */
YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
char yy_hold_char;
int yy_n_chars;
int yyleng_r;
char *yy_c_buf_p;
int yy_init;
int yy_start;
int yy_did_buffer_switch_on_eof;
int yy_start_stack_ptr;
int yy_start_stack_depth;
int *yy_start_stack;
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
int yylineno_r;
int yy_flex_debug_r;
char *yytext_r;
int yy_more_flag;
int yy_more_len;
YYSTYPE * yylval_r;
}; /* end struct yyguts_t */
static int yy_init_globals (yyscan_t yyscanner );
/* This must go here because YYSTYPE and YYLTYPE are included
* from bison output in section 1.*/
# define yylval yyg->yylval_r
int yylex_init (yyscan_t* scanner);
int yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (yyscan_t yyscanner );
int yyget_debug (yyscan_t yyscanner );
void yyset_debug (int debug_flag ,yyscan_t yyscanner );
YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner );
void yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
FILE *yyget_in (yyscan_t yyscanner );
void yyset_in (FILE * in_str ,yyscan_t yyscanner );
FILE *yyget_out (yyscan_t yyscanner );
void yyset_out (FILE * out_str ,yyscan_t yyscanner );
int yyget_leng (yyscan_t yyscanner );
char *yyget_text (yyscan_t yyscanner );
int yyget_lineno (yyscan_t yyscanner );
void yyset_lineno (int line_number ,yyscan_t yyscanner );
int yyget_column (yyscan_t yyscanner );
void yyset_column (int column_no ,yyscan_t yyscanner );
YYSTYPE * yyget_lval (yyscan_t yyscanner );
void yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (yyscan_t yyscanner );
#else
extern int yywrap (yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner );
#else
static int input (yyscan_t yyscanner );
#endif
#endif
static void yy_push_state (int new_state ,yyscan_t yyscanner);
static void yy_pop_state (yyscan_t yyscanner );
static int yy_top_state (yyscan_t yyscanner );
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
unsigned n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner)
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex \
(YYSTYPE * yylval_param ,yyscan_t yyscanner);
#define YY_DECL int yylex \
(YYSTYPE * yylval_param , yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
TParseContext* context = yyextra;
/* Single-line comments */
yylval = yylval_param;
if ( !yyg->yy_init )
{
yyg->yy_init = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! yyg->yy_start )
yyg->yy_start = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
}
yy_load_buffer_state(yyscanner );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = yyg->yy_c_buf_p;
/* Support of yytext. */
*yy_cp = yyg->yy_hold_char;
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = yyg->yy_start;
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 411 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_current_state != 410 );
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] )
{
int yyl;
for ( yyl = 0; yyl < yyleng; ++yyl )
if ( yytext[yyl] == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
}
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = yyg->yy_hold_char;
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
case 1:
YY_RULE_SETUP
;
YY_BREAK
/* Multi-line comments */
case 2:
YY_RULE_SETUP
{ yy_push_state(COMMENT, yyscanner); }
YY_BREAK
case 3:
case 4:
/* rule 4 can match eol */
YY_RULE_SETUP
;
YY_BREAK
case 5:
YY_RULE_SETUP
{ yy_pop_state(yyscanner); }
YY_BREAK
case 6:
YY_RULE_SETUP
{ return(INVARIANT); }
YY_BREAK
case 7:
YY_RULE_SETUP
{ return(HIGH_PRECISION); }
YY_BREAK
case 8:
YY_RULE_SETUP
{ return(MEDIUM_PRECISION); }
YY_BREAK
case 9:
YY_RULE_SETUP
{ return(LOW_PRECISION); }
YY_BREAK
case 10:
YY_RULE_SETUP
{ return(PRECISION); }
YY_BREAK
case 11:
YY_RULE_SETUP
{ return(ATTRIBUTE); }
YY_BREAK
case 12:
YY_RULE_SETUP
{ return(CONST_QUAL); }
YY_BREAK
case 13:
YY_RULE_SETUP
{ return(UNIFORM); }
YY_BREAK
case 14:
YY_RULE_SETUP
{ return(VARYING); }
YY_BREAK
case 15:
YY_RULE_SETUP
{ return(BREAK); }
YY_BREAK
case 16:
YY_RULE_SETUP
{ return(CONTINUE); }
YY_BREAK
case 17:
YY_RULE_SETUP
{ return(DO); }
YY_BREAK
case 18:
YY_RULE_SETUP
{ return(FOR); }
YY_BREAK
case 19:
YY_RULE_SETUP
{ return(WHILE); }
YY_BREAK
case 20:
YY_RULE_SETUP
{ return(IF); }
YY_BREAK
case 21:
YY_RULE_SETUP
{ return(ELSE); }
YY_BREAK
case 22:
YY_RULE_SETUP
{ return(IN_QUAL); }
YY_BREAK
case 23:
YY_RULE_SETUP
{ return(OUT_QUAL); }
YY_BREAK
case 24:
YY_RULE_SETUP
{ return(INOUT_QUAL); }
YY_BREAK
case 25:
YY_RULE_SETUP
{ context->lexAfterType = true; return(FLOAT_TYPE); }
YY_BREAK
case 26:
YY_RULE_SETUP
{ context->lexAfterType = true; return(INT_TYPE); }
YY_BREAK
case 27:
YY_RULE_SETUP
{ context->lexAfterType = true; return(VOID_TYPE); }
YY_BREAK
case 28:
YY_RULE_SETUP
{ context->lexAfterType = true; return(BOOL_TYPE); }
YY_BREAK
case 29:
YY_RULE_SETUP
{ yylval->lex.b = true; return(BOOLCONSTANT); }
YY_BREAK
case 30:
YY_RULE_SETUP
{ yylval->lex.b = false; return(BOOLCONSTANT); }
YY_BREAK
case 31:
YY_RULE_SETUP
{ return(DISCARD); }
YY_BREAK
case 32:
YY_RULE_SETUP
{ return(RETURN); }
YY_BREAK
case 33:
YY_RULE_SETUP
{ context->lexAfterType = true; return(MATRIX2); }
YY_BREAK
case 34:
YY_RULE_SETUP
{ context->lexAfterType = true; return(MATRIX3); }
YY_BREAK
case 35:
YY_RULE_SETUP
{ context->lexAfterType = true; return(MATRIX4); }
YY_BREAK
case 36:
YY_RULE_SETUP
{ context->lexAfterType = true; return (VEC2); }
YY_BREAK
case 37:
YY_RULE_SETUP
{ context->lexAfterType = true; return (VEC3); }
YY_BREAK
case 38:
YY_RULE_SETUP
{ context->lexAfterType = true; return (VEC4); }
YY_BREAK
case 39:
YY_RULE_SETUP
{ context->lexAfterType = true; return (IVEC2); }
YY_BREAK
case 40:
YY_RULE_SETUP
{ context->lexAfterType = true; return (IVEC3); }
YY_BREAK
case 41:
YY_RULE_SETUP
{ context->lexAfterType = true; return (IVEC4); }
YY_BREAK
case 42:
YY_RULE_SETUP
{ context->lexAfterType = true; return (BVEC2); }
YY_BREAK
case 43:
YY_RULE_SETUP
{ context->lexAfterType = true; return (BVEC3); }
YY_BREAK
case 44:
YY_RULE_SETUP
{ context->lexAfterType = true; return (BVEC4); }
YY_BREAK
case 45:
YY_RULE_SETUP
{ context->lexAfterType = true; return SAMPLER2D; }
YY_BREAK
case 46:
YY_RULE_SETUP
{ context->lexAfterType = true; return SAMPLERCUBE; }
YY_BREAK
case 47:
YY_RULE_SETUP
{ context->lexAfterType = true; return(STRUCT); }
YY_BREAK
case 48:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 49:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 50:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 51:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 52:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 53:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 54:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 55:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 56:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 57:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 58:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 59:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 60:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 61:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 62:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 63:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 64:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 65:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 66:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 67:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 68:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 69:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 70:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 71:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 72:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 73:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 74:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 75:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 76:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 77:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 78:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 79:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 80:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 81:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 82:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 83:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 84:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 85:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 86:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 87:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 88:
YY_RULE_SETUP
{
yylval->lex.string = NewPoolTString(yytext);
return check_type(yyscanner);
}
YY_BREAK
case 89:
YY_RULE_SETUP
{ yylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
YY_BREAK
case 90:
YY_RULE_SETUP
{ yylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
YY_BREAK
case 91:
YY_RULE_SETUP
{ context->error(yylineno, "Invalid Octal number.", yytext, "", ""); context->recover(); return 0;}
YY_BREAK
case 92:
YY_RULE_SETUP
{ yylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
YY_BREAK
case 93:
YY_RULE_SETUP
{ yylval->lex.f = static_cast<float>(atof_dot(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 94:
YY_RULE_SETUP
{ yylval->lex.f = static_cast<float>(atof_dot(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 95:
YY_RULE_SETUP
{ yylval->lex.f = static_cast<float>(atof_dot(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 96:
YY_RULE_SETUP
{ return(ADD_ASSIGN); }
YY_BREAK
case 97:
YY_RULE_SETUP
{ return(SUB_ASSIGN); }
YY_BREAK
case 98:
YY_RULE_SETUP
{ return(MUL_ASSIGN); }
YY_BREAK
case 99:
YY_RULE_SETUP
{ return(DIV_ASSIGN); }
YY_BREAK
case 100:
YY_RULE_SETUP
{ return(MOD_ASSIGN); }
YY_BREAK
case 101:
YY_RULE_SETUP
{ return(LEFT_ASSIGN); }
YY_BREAK
case 102:
YY_RULE_SETUP
{ return(RIGHT_ASSIGN); }
YY_BREAK
case 103:
YY_RULE_SETUP
{ return(AND_ASSIGN); }
YY_BREAK
case 104:
YY_RULE_SETUP
{ return(XOR_ASSIGN); }
YY_BREAK
case 105:
YY_RULE_SETUP
{ return(OR_ASSIGN); }
YY_BREAK
case 106:
YY_RULE_SETUP
{ return(INC_OP); }
YY_BREAK
case 107:
YY_RULE_SETUP
{ return(DEC_OP); }
YY_BREAK
case 108:
YY_RULE_SETUP
{ return(AND_OP); }
YY_BREAK
case 109:
YY_RULE_SETUP
{ return(OR_OP); }
YY_BREAK
case 110:
YY_RULE_SETUP
{ return(XOR_OP); }
YY_BREAK
case 111:
YY_RULE_SETUP
{ return(LE_OP); }
YY_BREAK
case 112:
YY_RULE_SETUP
{ return(GE_OP); }
YY_BREAK
case 113:
YY_RULE_SETUP
{ return(EQ_OP); }
YY_BREAK
case 114:
YY_RULE_SETUP
{ return(NE_OP); }
YY_BREAK
case 115:
YY_RULE_SETUP
{ return(LEFT_OP); }
YY_BREAK
case 116:
YY_RULE_SETUP
{ return(RIGHT_OP); }
YY_BREAK
case 117:
YY_RULE_SETUP
{ context->lexAfterType = false; return(SEMICOLON); }
YY_BREAK
case 118:
YY_RULE_SETUP
{ context->lexAfterType = false; return(LEFT_BRACE); }
YY_BREAK
case 119:
YY_RULE_SETUP
{ return(RIGHT_BRACE); }
YY_BREAK
case 120:
YY_RULE_SETUP
{ if (context->inTypeParen) context->lexAfterType = false; return(COMMA); }
YY_BREAK
case 121:
YY_RULE_SETUP
{ return(COLON); }
YY_BREAK
case 122:
YY_RULE_SETUP
{ context->lexAfterType = false; return(EQUAL); }
YY_BREAK
case 123:
YY_RULE_SETUP
{ context->lexAfterType = false; context->inTypeParen = true; return(LEFT_PAREN); }
YY_BREAK
case 124:
YY_RULE_SETUP
{ context->inTypeParen = false; return(RIGHT_PAREN); }
YY_BREAK
case 125:
YY_RULE_SETUP
{ return(LEFT_BRACKET); }
YY_BREAK
case 126:
YY_RULE_SETUP
{ return(RIGHT_BRACKET); }
YY_BREAK
case 127:
YY_RULE_SETUP
{ BEGIN(FIELDS); return(DOT); }
YY_BREAK
case 128:
YY_RULE_SETUP
{ return(BANG); }
YY_BREAK
case 129:
YY_RULE_SETUP
{ return(DASH); }
YY_BREAK
case 130:
YY_RULE_SETUP
{ return(TILDE); }
YY_BREAK
case 131:
YY_RULE_SETUP
{ return(PLUS); }
YY_BREAK
case 132:
YY_RULE_SETUP
{ return(STAR); }
YY_BREAK
case 133:
YY_RULE_SETUP
{ return(SLASH); }
YY_BREAK
case 134:
YY_RULE_SETUP
{ return(PERCENT); }
YY_BREAK
case 135:
YY_RULE_SETUP
{ return(LEFT_ANGLE); }
YY_BREAK
case 136:
YY_RULE_SETUP
{ return(RIGHT_ANGLE); }
YY_BREAK
case 137:
YY_RULE_SETUP
{ return(VERTICAL_BAR); }
YY_BREAK
case 138:
YY_RULE_SETUP
{ return(CARET); }
YY_BREAK
case 139:
YY_RULE_SETUP
{ return(AMPERSAND); }
YY_BREAK
case 140:
YY_RULE_SETUP
{ return(QUESTION); }
YY_BREAK
case 141:
YY_RULE_SETUP
{
BEGIN(INITIAL);
yylval->lex.string = NewPoolTString(yytext);
return FIELD_SELECTION;
}
YY_BREAK
case 142:
YY_RULE_SETUP
{}
YY_BREAK
case 143:
/* rule 143 can match eol */
YY_RULE_SETUP
{ }
YY_BREAK
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(COMMENT):
case YY_STATE_EOF(FIELDS):
{ context->AfterEOF = true; yyterminate(); }
YY_BREAK
case 144:
YY_RULE_SETUP
{ context->warning(yylineno, "Unknown char", yytext, ""); return 0; }
YY_BREAK
case 145:
YY_RULE_SETUP
ECHO;
YY_BREAK
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = yyg->yy_hold_char;
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++yyg->yy_c_buf_p;
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_END_OF_FILE:
{
yyg->yy_did_buffer_switch_on_eof = 0;
if ( yywrap(yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p =
yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
yyg->yy_c_buf_p =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = yyg->yytext_ptr;
register int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
yyg->yy_n_chars, (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
if ( yyg->yy_n_chars == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin ,yyscanner);
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
yyg->yy_n_chars += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
{
register yy_state_type yy_current_state;
register char *yy_cp;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_current_state = yyg->yy_start;
for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 411 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner)
{
register int yy_is_jam;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
register char *yy_cp = yyg->yy_c_buf_p;
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 411 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 410);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner)
#else
static int input (yyscan_t yyscanner)
#endif
{
int c;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
*yyg->yy_c_buf_p = yyg->yy_hold_char;
if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
/* This was really a NUL. */
*yyg->yy_c_buf_p = '\0';
else
{ /* need more input */
int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin ,yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap(yyscanner ) )
return EOF;
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput(yyscanner);
#else
return input(yyscanner);
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
*yyg->yy_c_buf_p = '\0'; /* preserve yytext */
yyg->yy_hold_char = *++yyg->yy_c_buf_p;
if ( c == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
yy_load_buffer_state(yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state(yyscanner );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
yyg->yy_hold_char = *yyg->yy_c_buf_p;
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ,yyscanner );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file ,yyscanner);
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf ,yyscanner );
yyfree((void *) b ,yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flush_buffer(b ,yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state(yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
yyensure_buffer_stack(yyscanner);
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state(yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state(yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (yyscan_t yyscanner)
{
int num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b ,yyscanner );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
{
return yy_scan_bytes(yystr,strlen(yystr) ,yyscanner);
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n ,yyscanner );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n ,yyscanner);
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
static void yy_push_state (int new_state , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( yyg->yy_start_stack_ptr >= yyg->yy_start_stack_depth )
{
yy_size_t new_size;
yyg->yy_start_stack_depth += YY_START_STACK_INCR;
new_size = yyg->yy_start_stack_depth * sizeof( int );
if ( ! yyg->yy_start_stack )
yyg->yy_start_stack = (int *) yyalloc(new_size ,yyscanner );
else
yyg->yy_start_stack = (int *) yyrealloc((void *) yyg->yy_start_stack,new_size ,yyscanner );
if ( ! yyg->yy_start_stack )
YY_FATAL_ERROR( "out of memory expanding start-condition stack" );
}
yyg->yy_start_stack[yyg->yy_start_stack_ptr++] = YY_START;
BEGIN(new_state);
}
static void yy_pop_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( --yyg->yy_start_stack_ptr < 0 )
YY_FATAL_ERROR( "start-condition stack underflow" );
BEGIN(yyg->yy_start_stack[yyg->yy_start_stack_ptr]);
}
static int yy_top_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyg->yy_start_stack[yyg->yy_start_stack_ptr - 1];
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = yyg->yy_hold_char; \
yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
yyg->yy_hold_char = *yyg->yy_c_buf_p; \
*yyg->yy_c_buf_p = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
}
/** Get the current line number.
* @param yyscanner The scanner object.
*/
int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
/** Get the current column number.
* @param yyscanner The scanner object.
*/
int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
/** Get the input stream.
* @param yyscanner The scanner object.
*/
FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
}
/** Get the output stream.
* @param yyscanner The scanner object.
*/
FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
}
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
}
/** Get the current token.
* @param yyscanner The scanner object.
*/
char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
}
/** Set the user-defined data. This data is never touched by the scanner.
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
}
/** Set the current line number.
* @param line_number
* @param yyscanner The scanner object.
*/
void yyset_lineno (int line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
yy_fatal_error( "yyset_lineno called with no buffer" , yyscanner);
yylineno = line_number;
}
/** Set the current column.
* @param line_number
* @param yyscanner The scanner object.
*/
void yyset_column (int column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
yy_fatal_error( "yyset_column called with no buffer" , yyscanner);
yycolumn = column_no;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
* @param yyscanner The scanner object.
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = in_str ;
}
void yyset_out (FILE * out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = out_str ;
}
int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
void yyset_debug (int bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = bdebug ;
}
/* Accessor methods for yylval and yylloc */
YYSTYPE * yyget_lval (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yylval;
}
void yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
}
/* User-visible API */
/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
return yy_init_globals ( *ptr_yy_globals );
}
/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
* The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
int yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = 0;
yyg->yy_buffer_stack_top = 0;
yyg->yy_buffer_stack_max = 0;
yyg->yy_c_buf_p = (char *) 0;
yyg->yy_init = 0;
yyg->yy_start = 0;
yyg->yy_start_stack_ptr = 0;
yyg->yy_start_stack_depth = 0;
yyg->yy_start_stack = NULL;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
yyfree(yyg->yy_buffer_stack ,yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
yyfree(yyg->yy_start_stack ,yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr , yyscan_t yyscanner)
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
extern "C" {
// Preprocessor interface.
#include "compiler/preprocessor/preprocess.h"
#define SETUP_CONTEXT(pp) \
TParseContext* context = (TParseContext*) pp->pC; \
struct yyguts_t* yyg = (struct yyguts_t*) context->scanner;
// Preprocessor callbacks.
void CPPDebugLogMsg(const char *msg)
{
SETUP_CONTEXT(cpp);
context->infoSink.debug.message(EPrefixNone, msg);
}
void CPPWarningToInfoLog(const char *msg)
{
SETUP_CONTEXT(cpp);
context->warning(yylineno, msg, "", "");
}
void CPPShInfoLogMsg(const char *msg)
{
SETUP_CONTEXT(cpp);
context->error(yylineno, msg, "", "");
context->recover();
}
void CPPErrorToInfoLog(char *msg)
{
SETUP_CONTEXT(cpp);
context->error(yylineno, msg, "", "");
context->recover();
}
void SetLineNumber(int line)
{
SETUP_CONTEXT(cpp);
int string = 0;
DecodeSourceLoc(yylineno, &string, NULL);
yylineno = EncodeSourceLoc(string, line);
}
void SetStringNumber(int string)
{
SETUP_CONTEXT(cpp);
int line = 0;
DecodeSourceLoc(yylineno, NULL, &line);
yylineno = EncodeSourceLoc(string, line);
}
int GetStringNumber()
{
SETUP_CONTEXT(cpp);
int string = 0;
DecodeSourceLoc(yylineno, &string, NULL);
return string;
}
int GetLineNumber()
{
SETUP_CONTEXT(cpp);
int line = 0;
DecodeSourceLoc(yylineno, NULL, &line);
return line;
}
void IncLineNumber()
{
SETUP_CONTEXT(cpp);
int string = 0, line = 0;
DecodeSourceLoc(yylineno, &string, &line);
yylineno = EncodeSourceLoc(string, ++line);
}
void DecLineNumber()
{
SETUP_CONTEXT(cpp);
int string = 0, line = 0;
DecodeSourceLoc(yylineno, &string, &line);
yylineno = EncodeSourceLoc(string, --line);
}
void HandlePragma(const char **tokens, int numTokens)
{
SETUP_CONTEXT(cpp);
if (!strcmp(tokens[0], "optimize")) {
if (numTokens != 4) {
CPPShInfoLogMsg("optimize pragma syntax is incorrect");
return;
}
if (strcmp(tokens[1], "(")) {
CPPShInfoLogMsg("\"(\" expected after 'optimize' keyword");
return;
}
if (!strcmp(tokens[2], "on"))
context->contextPragma.optimize = true;
else if (!strcmp(tokens[2], "off"))
context->contextPragma.optimize = false;
else {
CPPShInfoLogMsg("\"on\" or \"off\" expected after '(' for 'optimize' pragma");
return;
}
if (strcmp(tokens[3], ")")) {
CPPShInfoLogMsg("\")\" expected to end 'optimize' pragma");
return;
}
} else if (!strcmp(tokens[0], "debug")) {
if (numTokens != 4) {
CPPShInfoLogMsg("debug pragma syntax is incorrect");
return;
}
if (strcmp(tokens[1], "(")) {
CPPShInfoLogMsg("\"(\" expected after 'debug' keyword");
return;
}
if (!strcmp(tokens[2], "on"))
context->contextPragma.debug = true;
else if (!strcmp(tokens[2], "off"))
context->contextPragma.debug = false;
else {
CPPShInfoLogMsg("\"on\" or \"off\" expected after '(' for 'debug' pragma");
return;
}
if (strcmp(tokens[3], ")")) {
CPPShInfoLogMsg("\")\" expected to end 'debug' pragma");
return;
}
} else {
#ifdef PRAGMA_TABLE
//
// implementation specific pragma
// use ((TParseContext *)cpp->pC)->contextPragma.pragmaTable to store the information about pragma
// For now, just ignore the pragma that the implementation cannot recognize
// An Example of one such implementation for a pragma that has a syntax like
// #pragma pragmaname(pragmavalue)
// This implementation stores the current pragmavalue against the pragma name in pragmaTable.
//
if (numTokens == 4 && !strcmp(tokens[1], "(") && !strcmp(tokens[3], ")")) {
TPragmaTable& pragmaTable = ((TParseContext *)cpp->pC)->contextPragma.pragmaTable;
TPragmaTable::iterator iter;
iter = pragmaTable.find(TString(tokens[0]));
if (iter != pragmaTable.end()) {
iter->second = tokens[2];
} else {
pragmaTable[ tokens[0] ] = tokens[2];
}
} else if (numTokens >= 2) {
TPragmaTable& pragmaTable = ((TParseContext *)cpp->pC)->contextPragma.pragmaTable;
TPragmaTable::iterator iter;
iter = pragmaTable.find(TString(tokens[0]));
if (iter != pragmaTable.end()) {
iter->second = tokens[1];
} else {
pragmaTable[ tokens[0] ] = tokens[1];
}
}
#endif // PRAGMA_TABLE
}
}
void StoreStr(char *string)
{
SETUP_CONTEXT(cpp);
TString strSrc;
strSrc = TString(string);
context->HashErrMsg = context->HashErrMsg + " " + strSrc;
}
const char* GetStrfromTStr(void)
{
SETUP_CONTEXT(cpp);
cpp->ErrMsg = context->HashErrMsg.c_str();
return cpp->ErrMsg;
}
void ResetTString(void)
{
SETUP_CONTEXT(cpp);
context->HashErrMsg = "";
}
TBehavior GetBehavior(const char* behavior)
{
if (!strcmp("require", behavior))
return EBhRequire;
else if (!strcmp("enable", behavior))
return EBhEnable;
else if (!strcmp("disable", behavior))
return EBhDisable;
else if (!strcmp("warn", behavior))
return EBhWarn;
else {
CPPShInfoLogMsg((TString("behavior '") + behavior + "' is not supported").c_str());
return EBhDisable;
}
}
void updateExtensionBehavior(const char* extName, const char* behavior)
{
SETUP_CONTEXT(cpp);
TBehavior behaviorVal = GetBehavior(behavior);
TMap<TString, TBehavior>:: iterator iter;
TString msg;
// special cased for all extension
if (!strcmp(extName, "all")) {
if (behaviorVal == EBhRequire || behaviorVal == EBhEnable) {
CPPShInfoLogMsg("extension 'all' cannot have 'require' or 'enable' behavior");
return;
} else {
for (iter = context->extensionBehavior.begin(); iter != context->extensionBehavior.end(); ++iter)
iter->second = behaviorVal;
}
} else {
iter = context->extensionBehavior.find(TString(extName));
if (iter == context->extensionBehavior.end()) {
switch (behaviorVal) {
case EBhRequire:
CPPShInfoLogMsg((TString("extension '") + extName + "' is not supported").c_str());
break;
case EBhEnable:
case EBhWarn:
case EBhDisable:
msg = TString("extension '") + extName + "' is not supported";
context->infoSink.info.message(EPrefixWarning, msg.c_str(), yylineno);
break;
}
return;
} else
iter->second = behaviorVal;
}
}
} // extern "C"
int string_input(char* buf, int max_size, yyscan_t yyscanner) {
int len;
if ((len = yylex_CPP(buf, max_size)) == 0)
return 0;
if (len >= max_size)
YY_FATAL_ERROR("input buffer overflow, can't enlarge buffer because scanner uses REJECT");
buf[len] = ' ';
return len+1;
}
int check_type(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*) yyscanner;
int token = IDENTIFIER;
TSymbol* symbol = yyextra->symbolTable.find(yytext);
if (yyextra->lexAfterType == false && symbol && symbol->isVariable()) {
TVariable* variable = static_cast<TVariable*>(symbol);
if (variable->isUserType()) {
yyextra->lexAfterType = true;
token = TYPE_NAME;
}
}
yylval->lex.symbol = symbol;
return token;
}
int reserved_word(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*) yyscanner;
yyextra->error(yylineno, "Illegal use of reserved word", yytext, "");
yyextra->recover();
return 0;
}
void yyerror(TParseContext* context, const char* reason) {
struct yyguts_t* yyg = (struct yyguts_t*) context->scanner;
if (context->AfterEOF) {
context->error(yylineno, reason, "unexpected EOF", "");
} else {
context->error(yylineno, reason, yytext, "");
}
context->recover();
}
int glslang_initialize(TParseContext* context) {
yyscan_t scanner = NULL;
if (yylex_init_extra(context,&scanner))
return 1;
context->scanner = scanner;
return 0;
}
int glslang_finalize(TParseContext* context) {
yyscan_t scanner = context->scanner;
if (scanner == NULL) return 0;
context->scanner = NULL;
return yylex_destroy(scanner);
}
void glslang_scan(int count, const char* const string[], const int length[],
TParseContext* context) {
yyrestart(NULL,context->scanner);
yyset_lineno(EncodeSourceLoc(0, 1),context->scanner);
context->AfterEOF = false;
// Init preprocessor.
cpp->pC = context;
cpp->PaWhichStr = 0;
cpp->PaArgv = string;
cpp->PaArgc = count;
cpp->PaStrLen = length;
cpp->pastFirstStatement = 0;
ScanFromString(string[0]);
}
| 28.794422 | 126 | 0.621442 | [
"object"
] |
fa2a33a0877a5e4b9c5525c14b6362caac624303 | 666 | cpp | C++ | LeetCode/Problems/Algorithms/#22_GenerateParentheses_sol2_closure_number.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#22_GenerateParentheses_sol2_closure_number.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#22_GenerateParentheses_sol2_closure_number.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> solutions;
if(n == 0){
solutions.push_back("");
}else{
for(int c = 0; c < n; ++c){
vector<string> leftSeqAll = generateParenthesis(c);
for(string leftSeq: leftSeqAll){
vector<string> rightSeqAll = generateParenthesis(n - 1 - c);
for(string rightSeq: rightSeqAll){
solutions.push_back("(" + leftSeq + ")" + rightSeq);
}
}
}
}
return solutions;
}
}; | 33.3 | 81 | 0.451952 | [
"vector"
] |
fa2db10d22f2a2531e098351c71046e0cdc125c8 | 2,873 | cpp | C++ | compiler/errors.cpp | basilTeam/basil | 3e88de0c33f4db814b63fdcbdfd473d378b6ec6b | [
"BSD-3-Clause"
] | 87 | 2020-08-13T16:40:22.000Z | 2022-03-20T13:26:10.000Z | compiler/errors.cpp | basilTeam/basil | 3e88de0c33f4db814b63fdcbdfd473d378b6ec6b | [
"BSD-3-Clause"
] | 33 | 2020-10-14T16:44:59.000Z | 2022-02-17T10:43:11.000Z | compiler/errors.cpp | basilTeam/basil | 3e88de0c33f4db814b63fdcbdfd473d378b6ec6b | [
"BSD-3-Clause"
] | 8 | 2020-10-22T08:59:34.000Z | 2022-03-22T04:34:04.000Z | /*
* Copyright (c) 2021, the Basil authors
* All rights reserved.
*
* This source code is licensed under the 3-Clause BSD License, the full text
* of which can be found in the LICENSE file in the root directory
* of this project.
*/
#include "errors.h"
#include "eval.h"
#include "util/vec.h"
#include "util/utf8.h"
namespace basil {
struct Note {
Source::Pos pos;
ustring msg;
};
struct Error {
Source::Pos pos;
ustring msg;
vector<Note> notes;
vector<Value> trace;
};
static vector<Error> errors;
vector<Value> get_stacktrace() {
vector<Value> trace;
const auto& info = get_perf_info();
for (i64 i = i64(info.counts.size()) - 1; i >= 0; i --) {
trace.push(info.counts[i].call_term);
}
return trace;
}
void err(Source::Pos pos, const ustring& msg) {
errors.push({ pos, msg, {}, get_stacktrace() });
}
void note(Source::Pos pos, const ustring& msg) {
if (errors.size() == 0) panic("Tried to add note to error, but no errors have been reported!");
errors.back().notes.push({ pos, msg });
}
u32 error_count() {
return errors.size();
}
void print_source(stream& io, const char* color, Source::Pos pos, const Source& src) {
if (pos == Source::Pos()) return;
const auto& line = src[pos.line_start];
u32 first = pos.col_start, last = pos.line_end == pos.line_start ? pos.col_end : line.size();
write(io, color, "│", RESET, " ");
auto it = line.begin();
for (u32 i = 0; i < line.size(); i ++) {
if (i == first) write(io, BOLD, ITALIC, color);
if (i == last) write(io, RESET);
write(io, *it ++);
}
if (line.back() != '\n') write(io, '\n');
u32 i = 0;
write(io, color, "└───────");
for (; i < first; i ++) write(io, "─");
write(io, BOLD, color);
for (; i < last; i ++) write(io, '^');
write(io, RESET);
writeln(io, "");
}
void print_error(stream& io, const Error& e, rc<Source> src) {
writeln(io, e.pos, BOLDRED, " Error", RESET, ": ", e.msg);
if (src) print_source(io, RED, e.pos, *src);
for (const auto& pos : e.trace) {
writeln(io, pos.pos, "\t", "in call to '", BOLDYELLOW, v_head(pos), RESET, "'");
if (src) print_source(io, YELLOW, pos.pos, *src);
}
for (const Note& n : e.notes) {
writeln(io, ITALICRED, "Note", RESET, ": ", n.msg);
if (src) print_source(io, RED, n.pos, *src);
}
writeln(io, "");
}
void print_errors(stream& io, rc<Source> src) {
for (const Error& e : errors) print_error(io, e, src);
}
void discard_errors() {
errors.clear();
}
} | 30.56383 | 103 | 0.524887 | [
"vector"
] |
fa2fd5c338c92f577b4eeb21159bd5e54b9cc76e | 5,246 | cpp | C++ | Signal_Calculator.cpp | AliNemat/EpiScale_Signal | 8799440b830a00554229f44ea1bbc368abce8af5 | [
"MIT"
] | null | null | null | Signal_Calculator.cpp | AliNemat/EpiScale_Signal | 8799440b830a00554229f44ea1bbc368abce8af5 | [
"MIT"
] | 5 | 2018-10-11T23:43:01.000Z | 2020-05-08T13:37:07.000Z | Signal_Calculator.cpp | arame002/EpiScale_Signal | 5215fd35ae60ad47b23fd36d94e68b4cf463f8f4 | [
"MIT"
] | 7 | 2018-06-14T23:42:28.000Z | 2019-12-13T22:04:07.000Z |
#include "MeshTissue.hpp"
#include "Signal_Calculator.h"
#include <chrono>
//---------------------------------------------------------------------------------------------
/*
vector<vector<double> > Signal_Calculator(vector< vector<double> > locX , vector< vector<double> > locY , vector<double > centX , vector<double > centY ,vector< vector<double> > oldConcentrations ,int index)
{
vector<vector<double > > a ;
return a ;
}
int main ()
{
vector< vector<double> > locX ;
vector< vector<double> > locY ;
vector<double > centX ;
vector<double > centY ;
int index = 100 ;
vector<vector<double> > oldConcentrations ;
*/
vector< vector<double> > Signal_Calculator ( vector< vector<double> > locX , vector< vector<double> > locY , vector<double > centX , vector<double > centY,vector< vector<double> > oldConcentrations , int index ){
ofstream nanIndex ("NanIndex.txt", ofstream::app) ; //everything will be written at the end of the existing file
ofstream sgnlCalculator ("sgnlCalculator.txt", ofstream::app) ; //everything will be written at the end of the existing file
auto start = std::chrono::high_resolution_clock::now() ;
MeshTissue tissue ;
tissue.cellType = wingDisc ;
tissue.equationsType = fullModel ;
tissue.readFileStatus = false ;
tissue.frameIndex = index ;
cout<<"current index in Signal_Calculator function is "<<index<<endl ;
sgnlCalculator<<"current index in Signal_Calculator function is "<<index<<endl ;
if (tissue.readFileStatus)
{
if (tissue.cellType == plant)
{
tissue.cells = tissue.ReadFile( ) ; //for old files
// tissue.cells = tissue.ReadFile2( ) ; // for new files
}
else if (tissue.cellType == wingDisc)
{
tissue.cells = tissue.ReadFile3( ) ; // for Wing Disc files
}
tissue.Cal_AllCellCenters () ;
}
else
{
tissue.Coupling(locX , locY ) ;
tissue.Cal_AllCellCenters () ;
}
cout<<"number of the cells is "<<tissue.cells.size()<<endl ;
sgnlCalculator<<"number of the cells is "<<tissue.cells.size()<<endl ;
// // // // // tissue.ParaViewInitialConfiguration() ; // Bug when I run this early in the code!!!! intx.size()= 0 !!!!!!
tissue.Cal_AllCellCntrToCntr();
tissue.Find_AllCellNeighborCandidates() ;
tissue.Find_AllCellNeighbors () ;
tissue.FindInterfaceWithNeighbor() ;
tissue.Cal_AllCellNewEdge() ;
tissue.Find_CommonNeighbors() ;
tissue.Cal_Intersect() ;
tissue.Cal_AllCellVertices() ;
tissue.Find_boundaries() ;
tissue.Refine_VerticesInBoundaryCells() ;
tissue.AllCell_RefineNoBoundary() ;
// tissue.ParaViewBoundary() ;
tissue.Add_NewVerticesToBoundaryEdges() ;
// tissue.Refine_CurvedInterface() ;
tissue.Find_Cyclic4() ;
tissue.Cyclic4Correction() ;
tissue.SortVertices() ;
tissue.Cal_AllCellConnections() ;
// tissue.Print_VeritcesSize() ;
tissue.ParaViewVertices() ;
tissue.ParaViewTissue () ;
tissue.ParaViewInitialConfiguration() ;
//Genetating meshes
tissue.Find_AllMeshes () ;
tissue.Find_IntercellularMeshConnection () ;
tissue.Cal_AreaOfTissue() ;
// Equations part
if (tissue.equationsType == simpleODE)
{
tissue.Find_SecretingCell() ;
tissue.EulerMethod () ;
}
else
{
if (tissue.readFileStatus)
{
tissue.ReadConcentrations() ;
tissue.WriteConcentrations("old") ;
}
else if (oldConcentrations.size()== tissue.cells.size() )
{
tissue.Initialize_Concentrations( oldConcentrations ) ;
tissue.tissueLevelConcentration = oldConcentrations ;
tissue.WriteConcentrations("old") ;
}
else
{
nanIndex <<"frame index is "<<tissue.frameIndex<<'\t' <<"tissue size is "<<tissue.cells.size()<<'t'
<<"oldConcentration size is "<<oldConcentrations.size()<<endl ;
}
tissue.FullModel_AllCellProductions() ; //Initialize production values
tissue.FullModelEulerMethod () ;
}
tissue.Cal_AllCellConcentration() ; // output depends on the cellType and equationType
// tissue.Cal_ReturnSignal() ; // returning Dpp level as U
tissue.WriteConcentrations("new") ;
tissue.UpdateNanStatus() ;
if (tissue.frameIsNan)
{
nanIndex <<"This is a Nan frame :" <<tissue.frameIndex<<endl ;
}
nanIndex.close() ;
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "Time taken by Singnal_Calculator is : " << duration.count() << " seconds" << endl;
sgnlCalculator << "Time taken by Singnal_Calculator is : " << duration.count() << " seconds" << endl;
sgnlCalculator.close() ;
// return tissue.tissueLevelU ;
return tissue.tissueLevelConcentration ;
// return 0 ;
}
// Adjust index and other global variables
// be carefull about dt
//free diffusion in the cell
| 35.687075 | 213 | 0.615707 | [
"vector"
] |
fa3955ffcc3a0c58414ee5a2beb1919204dc7ebc | 835 | cpp | C++ | test/ForEachTest.cpp | TheOsch2/boolinq | 5464cf801b046026e8d32cb37d9985fd672a34ec | [
"MIT"
] | 473 | 2015-01-03T03:58:48.000Z | 2022-03-18T19:27:09.000Z | test/ForEachTest.cpp | TheOsch2/boolinq | 5464cf801b046026e8d32cb37d9985fd672a34ec | [
"MIT"
] | 58 | 2015-01-13T14:43:35.000Z | 2022-03-02T16:48:55.000Z | test/ForEachTest.cpp | TheOsch2/boolinq | 5464cf801b046026e8d32cb37d9985fd672a34ec | [
"MIT"
] | 71 | 2015-02-17T20:30:50.000Z | 2022-03-21T00:56:54.000Z | #include <list>
#include <vector>
#include <string>
#include <gtest/gtest.h>
#include "boolinq.h"
using namespace boolinq;
TEST(ForEach, ThreeCharsSum)
{
std::vector<char> src;
src.push_back('a');
src.push_back('b');
src.push_back('c');
std::string str = "";
from(src).for_each([&](char a){str += a;});
EXPECT_EQ("abc", str);
}
TEST(ForEach, ThreeCharsUpperSum)
{
std::vector<char> src;
src.push_back('a');
src.push_back('b');
src.push_back('c');
std::string str = "";
from(src).for_each([&](char a){str += a + ('A' - 'a');});
EXPECT_EQ("ABC", str);
}
TEST(ForEach, ThreeIntsSum)
{
std::vector<int> src;
src.push_back(10);
src.push_back(20);
src.push_back(30);
int sum = 0;
from(src).for_each([&](int a){sum += a;});
EXPECT_EQ(60, sum);
}
| 17.040816 | 61 | 0.577246 | [
"vector"
] |
fa4dc9cf0be45990960e4b27746abed666abee87 | 5,300 | cpp | C++ | FutureExecutor/FutureExecutorsThen.cpp | google/cpp-from-the-sky-down | 10c8d16e877796f2906bedbd3a66fb6469b3a211 | [
"Apache-2.0"
] | 219 | 2018-08-15T22:01:07.000Z | 2022-03-23T11:46:54.000Z | FutureExecutor/FutureExecutorsThen.cpp | sthagen/cpp-from-the-sky-down | 72114a17a659e5919b4cbe3363e35c04f833d9d9 | [
"Apache-2.0"
] | 5 | 2018-09-11T06:15:28.000Z | 2022-01-05T15:27:31.000Z | FutureExecutor/FutureExecutorsThen.cpp | sthagen/cpp-from-the-sky-down | 72114a17a659e5919b4cbe3363e35c04f833d9d9 | [
"Apache-2.0"
] | 27 | 2018-09-11T06:14:40.000Z | 2022-03-20T09:46:14.000Z |
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <optional>
#include <queue>
#include <sstream>
#include <thread>
template <typename T>
class mtq {
public:
mtq(std::size_t max_size) : max_size_(max_size) {}
void push(T t) {
std::unique_lock<std::mutex> lock{mut_};
for (;;) {
if (q_.size() < max_size_) {
q_.push(std::move(t));
cvar_.notify_all();
return;
} else {
cvar_.wait(lock);
}
}
}
std::optional<T> pop() {
std::unique_lock<std::mutex> lock{mut_};
for (;;) {
if (!q_.empty()) {
T t = q_.front();
q_.pop();
cvar_.notify_all();
return t;
} else {
if (done_) return std::nullopt;
cvar_.wait(lock);
}
}
}
bool done() const {
std::unique_lock<std::mutex> lock{mut_};
return done_;
}
void set_done() {
std::unique_lock<std::mutex> lock{mut_};
done_ = true;
cvar_.notify_all();
}
private:
std::size_t max_size_ = 0;
bool done_ = false;
std::queue<T> q_;
mutable std::mutex mut_;
mutable std::condition_variable cvar_;
};
#include <functional>
class thread_pool {
public:
thread_pool() : q_(std::numeric_limits<int>::max() - 1) { add_thread(); }
~thread_pool() {
q_.set_done();
for (auto& thread : threads_) {
if (thread.joinable()) {
thread.join();
}
}
}
void add(std::function<void()> f) { q_.push(std::move(f)); }
void add_thread() {
std::unique_lock lock{mut_};
threads_.emplace_back([this]() mutable {
while (true) {
auto f = q_.pop();
if (f) {
(*f)();
} else {
if (q_.done()) return;
}
}
});
}
private:
mtq<std::function<void()>> q_;
std::mutex mut_;
std::vector<std::thread> threads_;
};
template <typename T>
struct shared {
T value;
std::exception_ptr eptr = nullptr;
std::mutex mutex;
std::condition_variable cvar;
bool done = false;
std::function<void()> then;
std::shared_ptr<thread_pool> pool;
};
template <typename T>
class future {
public:
void wait() {
std::unique_lock<std::mutex> lock{shared_->mutex};
while (!shared_->done) {
shared_->cvar.wait(lock);
}
}
template <typename F>
auto then(F f) -> future<decltype(f(*this))>;
T& get() {
wait();
if (shared_->eptr) {
std::rethrow_exception(shared_->eptr);
}
return shared_->value;
}
explicit future(const std::shared_ptr<shared<T>>& shared) : shared_(shared) {}
private:
std::shared_ptr<shared<T>> shared_;
};
template <typename T>
void run_then(std::unique_lock<std::mutex> lock,
std::shared_ptr<shared<T>>& s) {
std::function<void()> f;
if (s->done) {
std::swap(f, s->then);
}
lock.unlock();
if (f) f();
}
template <typename T>
class promise {
public:
promise() : shared_(std::make_shared<shared<T>>()) {}
template <typename V>
void set_value(V&& v) {
std::unique_lock<std::mutex> lock{shared_->mutex};
shared_->value = std::forward<V>(v);
shared_->done = true;
run_then(std::move(lock), shared_);
shared_->cvar.notify_one();
shared_ = nullptr;
}
void set_exception(std::exception_ptr eptr) {
std::unique_lock<std::mutex> lock{shared_->mutex};
shared_->eptr = eptr;
shared_->done = true;
run_then(std::move(lock), shared_);
shared_->cvar.notify_one();
shared_ = nullptr;
}
future<T> get_future() { return future<T>{shared_}; }
explicit promise(const std::shared_ptr<shared<T>>& shared)
: shared_(shared) {}
private:
std::shared_ptr<shared<T>> shared_;
};
template <typename T>
template <typename F>
auto future<T>::then(F f) -> future<decltype(f(*this))> {
std::unique_lock<std::mutex> lock{shared_->mutex};
using type = decltype(f(*this));
auto then_shared = std::make_shared<shared<type>>();
then_shared->pool = shared_->pool;
shared_->then = [shared = shared_, then_shared, f = std::move(f),
pool = shared_->pool]() mutable {
pool->add([shared, then_shared, f = std::move(f),
p = promise<type>(then_shared)]() mutable {
future<T> fut(shared);
try {
p.set_value(f(fut));
} catch (...) {
p.set_exception(std::current_exception());
}
});
};
run_then(std::move(lock), shared_);
return future<type>(then_shared);
}
template <typename F, typename... Args>
auto async(std::shared_ptr<thread_pool> pool, F f, Args... args)
-> future<decltype(f(args...))> {
using T = decltype(f(args...));
auto state = std::make_shared<shared<T>>();
state->pool = pool;
promise<T> p(state);
auto fut = p.get_future();
auto future_func = [p = std::move(p), f = std::move(f), args...]() mutable {
try {
p.set_value(f(args...));
} catch (...) {
p.set_exception(std::current_exception());
}
};
pool->add(std::move(future_func));
return fut;
}
#include <iostream>
int main() {
auto pool = std::make_shared<thread_pool>();
pool->add([]() { std::cout << "Hi from thread pool\n"; });
auto f = async(pool, []() {
std::cout << "Hello\n";
return 1;
});
auto f2 = f.then([](auto& f) {
std::cout << f.get() << " World\n";
return 2.0;
});
f2.get();
}
| 22.746781 | 80 | 0.583019 | [
"vector"
] |
fa54f4a017cb25d32e6d59051189c25f07ed93e2 | 1,235 | cpp | C++ | llvm/lib/Target/AMDGPU/AMDGPUHSATargetObjectFile.cpp | zard49/kokkos-clang | c519a032853e6507075de1807c5730b8239ab936 | [
"Unlicense"
] | 4 | 2019-04-18T03:54:09.000Z | 2021-03-22T02:27:31.000Z | llvm/lib/Target/AMDGPU/AMDGPUHSATargetObjectFile.cpp | losalamos/kokkos-clang | d68d9c63cea3dbaad33454e4ebc9df829bca24fe | [
"Unlicense"
] | null | null | null | llvm/lib/Target/AMDGPU/AMDGPUHSATargetObjectFile.cpp | losalamos/kokkos-clang | d68d9c63cea3dbaad33454e4ebc9df829bca24fe | [
"Unlicense"
] | 2 | 2019-11-16T19:03:05.000Z | 2020-03-19T08:32:37.000Z | //===-- AMDGPUHSATargetObjectFile.cpp - AMDGPU Object Files ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AMDGPUHSATargetObjectFile.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/Support/ELF.h"
using namespace llvm;
void AMDGPUHSATargetObjectFile::Initialize(MCContext &Ctx,
const TargetMachine &TM){
TargetLoweringObjectFileELF::Initialize(Ctx, TM);
InitializeELF(TM.Options.UseInitArray);
TextSection = AMDGPU::getHSATextSection(Ctx);
}
MCSection *AMDGPUHSATargetObjectFile::SelectSectionForGlobal(
const GlobalValue *GV, SectionKind Kind,
Mangler &Mang,
const TargetMachine &TM) const {
if (Kind.isText() && !GV->hasComdat())
return getTextSection();
return TargetLoweringObjectFileELF::SelectSectionForGlobal(GV, Kind, Mang, TM);
}
| 34.305556 | 81 | 0.591903 | [
"object"
] |
fa5be29ea46ea2f6c75a161469477b7ca9bfded2 | 7,702 | cpp | C++ | unittest/test_binaryivf.cpp | ChunelFeng/knowhere | 4c6ff55b5a23a9a38b12db40cbb5cd847cae1408 | [
"Apache-2.0"
] | null | null | null | unittest/test_binaryivf.cpp | ChunelFeng/knowhere | 4c6ff55b5a23a9a38b12db40cbb5cd847cae1408 | [
"Apache-2.0"
] | null | null | null | unittest/test_binaryivf.cpp | ChunelFeng/knowhere | 4c6ff55b5a23a9a38b12db40cbb5cd847cae1408 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019-2020 Zilliz. 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 <gtest/gtest.h>
#include <thread>
#include "knowhere/common/Exception.h"
#include "knowhere/index/vector_index/ConfAdapterMgr.h"
#include "knowhere/index/vector_index/IndexBinaryIVF.h"
#include "knowhere/index/vector_index/adapter/VectorAdapter.h"
#include "unittest/range_utils.h"
#include "unittest/utils.h"
using ::testing::Combine;
using ::testing::TestWithParam;
using ::testing::Values;
class BinaryIVFTest : public DataGen,
public TestWithParam<knowhere::IndexMode> {
protected:
void
SetUp() override {
Init_with_default(true);
conf_ = knowhere::Config{
{knowhere::meta::METRIC_TYPE, knowhere::metric::HAMMING},
{knowhere::meta::DIM, dim},
{knowhere::meta::TOPK, k},
{knowhere::meta::RADIUS, radius},
{knowhere::indexparam::NLIST, 16},
{knowhere::indexparam::NPROBE, 8},
};
index_mode_ = GetParam();
index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IVFFLAT;
index_ = std::make_shared<knowhere::BinaryIVF>();
}
void
TearDown() override {
}
protected:
knowhere::Config conf_;
knowhere::IndexMode index_mode_;
knowhere::IndexType index_type_;
knowhere::BinaryIVFIndexPtr index_ = nullptr;
};
INSTANTIATE_TEST_CASE_P(
METRICParameters,
BinaryIVFTest,
Values(knowhere::IndexMode::MODE_CPU));
TEST_P(BinaryIVFTest, binaryivf_basic) {
assert(!xb_bin.empty());
// null faiss index
{
ASSERT_ANY_THROW(index_->Serialize(conf_));
ASSERT_ANY_THROW(index_->Query(query_dataset, conf_, nullptr));
ASSERT_ANY_THROW(index_->AddWithoutIds(nullptr, conf_));
}
index_->BuildAll(base_dataset, conf_);
EXPECT_EQ(index_->Count(), nb);
EXPECT_EQ(index_->Dim(), dim);
ASSERT_GT(index_->Size(), 0);
auto adapter = knowhere::AdapterMgr::GetInstance().GetAdapter(index_type_);
ASSERT_TRUE(adapter->CheckSearch(conf_, index_type_, index_mode_));
auto result = index_->Query(query_dataset, conf_, nullptr);
AssertAnns(result, nq, knowhere::GetMetaTopk(conf_));
// PrintResult(result, nq, k);
auto result2 = index_->Query(query_dataset, conf_, *bitset);
AssertAnns(result2, nq, k, CheckMode::CHECK_NOT_EQUAL);
}
TEST_P(BinaryIVFTest, binaryivf_serialize) {
auto serialize = [](const std::string& filename, knowhere::BinaryPtr& bin, uint8_t* ret) {
{
FileIOWriter writer(filename);
writer(static_cast<void*>(bin->data.get()), bin->size);
}
FileIOReader reader(filename);
reader(ret, bin->size);
};
// serialize index
index_->BuildAll(base_dataset, conf_);
auto binaryset = index_->Serialize(conf_);
auto bin = binaryset.GetByName("BinaryIVF");
std::string filename = temp_path("/tmp/binaryivf_test_serialize.bin");
auto load_data = new uint8_t[bin->size];
serialize(filename, bin, load_data);
binaryset.clear();
std::shared_ptr<uint8_t[]> data(load_data);
binaryset.Append("BinaryIVF", data, bin->size);
index_->Load(binaryset);
EXPECT_EQ(index_->Count(), nb);
EXPECT_EQ(index_->Dim(), dim);
auto result = index_->Query(query_dataset, conf_, nullptr);
AssertAnns(result, nq, knowhere::GetMetaTopk(conf_));
// PrintResult(result, nq, k);
}
TEST_P(BinaryIVFTest, binaryivf_slice) {
// serialize index
index_->BuildAll(base_dataset, conf_);
auto binaryset = index_->Serialize(conf_);
index_->Load(binaryset);
EXPECT_EQ(index_->Count(), nb);
EXPECT_EQ(index_->Dim(), dim);
auto result = index_->Query(query_dataset, conf_, nullptr);
AssertAnns(result, nq, knowhere::GetMetaTopk(conf_));
// PrintResult(result, nq, k);
}
TEST_P(BinaryIVFTest, binaryivf_range_search_hamming) {
int hamming_radius = 50;
knowhere::SetMetaMetricType(conf_, knowhere::metric::HAMMING);
knowhere::SetMetaRadius(conf_, hamming_radius);
index_->BuildAll(base_dataset, conf_);
EXPECT_EQ(index_->Count(), nb);
EXPECT_EQ(index_->Dim(), dim);
auto qd = knowhere::GenDataset(nq, dim, xq_bin.data());
auto test_range_search_hamming = [&](float radius, const faiss::BitsetView bitset) {
std::vector<int64_t> golden_labels;
std::vector<size_t> golden_lims;
RunRangeSearchBF<CMin<float>>(golden_labels, golden_lims, xb_bin, nb, xq_bin, nq, dim, radius, hamming_dis, bitset);
auto result = index_->QueryByRange(qd, conf_, bitset);
CheckRangeSearchResult<CMin<float>>(result, nq, radius, golden_labels, golden_lims, false);
};
test_range_search_hamming(hamming_radius, nullptr);
test_range_search_hamming(hamming_radius, *bitset);
}
TEST_P(BinaryIVFTest, binaryivf_range_search_jaccard) {
float jaccard_radius = 0.5;
knowhere::SetMetaMetricType(conf_, knowhere::metric::JACCARD);
knowhere::SetMetaRadius(conf_, jaccard_radius);
// serialize index
index_->BuildAll(base_dataset, conf_);
EXPECT_EQ(index_->Count(), nb);
EXPECT_EQ(index_->Dim(), dim);
auto qd = knowhere::GenDataset(nq, dim, xq_bin.data());
auto test_range_search_jaccard = [&](float radius, const faiss::BitsetView bitset) {
std::vector<int64_t> golden_labels;
std::vector<size_t> golden_lims;
RunRangeSearchBF<CMin<float>>(golden_labels, golden_lims, xb_bin, nb, xq_bin, nq, dim, radius, jaccard_dis, bitset);
auto result = index_->QueryByRange(qd, conf_, bitset);
CheckRangeSearchResult<CMin<float>>(result, nq, radius, golden_labels, golden_lims, false);
};
test_range_search_jaccard(jaccard_radius, nullptr);
test_range_search_jaccard(jaccard_radius, *bitset);
}
TEST_P(BinaryIVFTest, binaryivf_range_search_tanimoto) {
float tanimoto_radius = 1.0;
knowhere::SetMetaMetricType(conf_, knowhere::metric::TANIMOTO);
knowhere::SetMetaRadius(conf_, tanimoto_radius);
index_->BuildAll(base_dataset, conf_);
EXPECT_EQ(index_->Count(), nb);
EXPECT_EQ(index_->Dim(), dim);
auto qd = knowhere::GenDataset(nq, dim, xq_bin.data());
auto test_range_search_tanimoto = [&](float radius, const faiss::BitsetView bitset) {
std::vector<int64_t> golden_labels;
std::vector<size_t> golden_lims;
RunRangeSearchBF<CMin<float>>(golden_labels, golden_lims, xb_bin, nb, xq_bin, nq, dim, radius, tanimoto_dis, bitset);
auto result = index_->QueryByRange(qd, conf_, bitset);
CheckRangeSearchResult<CMin<float>>(result, nq, radius, golden_labels, golden_lims, false);
};
test_range_search_tanimoto(tanimoto_radius, nullptr);
test_range_search_tanimoto(tanimoto_radius, *bitset);
}
TEST_P(BinaryIVFTest, binaryivf_range_search_superstructure) {
knowhere::SetMetaMetricType(conf_, knowhere::metric::SUPERSTRUCTURE);
ASSERT_ANY_THROW(index_->Train(base_dataset, conf_));
}
TEST_P(BinaryIVFTest, binaryivf_range_search_substructure) {
knowhere::SetMetaMetricType(conf_, knowhere::metric::SUBSTRUCTURE);
ASSERT_ANY_THROW(index_->Train(base_dataset, conf_));
}
| 35.823256 | 125 | 0.698909 | [
"vector"
] |
fa61f786b1e541d2a4101b2e22ad2cf6b4d97133 | 773 | cpp | C++ | Range Queries/Forest Queries.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T12:30:13.000Z | 2022-02-12T13:59:20.000Z | Range Queries/Forest Queries.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T11:09:41.000Z | 2022-02-12T11:55:49.000Z | Range Queries/Forest Queries.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int n,q;
vector<vector<int>> F;
int sum(int r,int c){
if (r<0||c<0) return 0;
int re=0;
for (int i=r;i>=0;i=(i&(i+1))-1){
for (int j=c;j>=0;j=(j&(j+1))-1){
re+=F[i][j];
}
}
return re;
}
void increase(int r,int c,int num){
for (int i=r;i<n;i=i|(i+1)){
for (int j=c;j<n;j=j|(j+1)){
F[i][j]+=num;
}
}
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);
cin>>n>>q;
F.assign(n,vector<int>(n,0));
string s;
for (int i=0;i<n;++i) {
cin>>s;
for (int j=0;j<n;++j){
if (s[j]=='*') increase(i,j,1);
}
}
for (int i=0;i<q;++i){
int r1,c1,r2,c2;
cin>>r1>>c1>>r2>>c2;--r1;--c1;--r2;--c2;
cout<<sum(r2,c2)-sum(r2,c1-1)-sum(r1-1,c2)+sum(r1-1,c1-1)<<'\n';
}
return 0;
}
| 17.177778 | 66 | 0.521345 | [
"vector"
] |
fa66411b7b2f49d19f1ed969499fa049db087652 | 6,642 | cpp | C++ | Outils/ICoCo/ICoCo_src/share/Validation/Rapports_automatiques/ThermalPower/src/TrioField/main.cpp | cea-trust-platform/trust-code | c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72 | [
"BSD-3-Clause"
] | 12 | 2021-06-30T18:50:38.000Z | 2022-03-23T09:03:16.000Z | Outils/ICoCo/ICoCo_src/share/Validation/Rapports_automatiques/ThermalPower/src/TrioField/main.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | null | null | null | Outils/ICoCo/ICoCo_src/share/Validation/Rapports_automatiques/ThermalPower/src/TrioField/main.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | 2 | 2021-10-04T09:19:39.000Z | 2021-12-15T14:21:04.000Z | #include <ICoCoProblem.h>
#include "CommInterface.hxx"
#include "ProcessorGroup.hxx"
#include "MPIProcessorGroup.hxx"
#include "TrioDEC.hxx"
#include <set>
#include <time.h>
#undef MM
#ifdef MM
#include <ICoCoMEDDoubleField.hxx>
#include <ICoCoProblem.h>
#else
#include <ICoCoTrioField.h>
#endif
#include <fstream>
#include <string.h>
using namespace MEDCoupling;
using namespace std;
using namespace ICoCo;
// Utility methods for synchronizing data
// from the the two trio instance
typedef enum {sync_and,sync_or} synctype;
void synchronize_bool(bool& stop, synctype s)
{
int my_stop=-1;
int my_stop_temp=stop?1:0;
if (s==sync_and)
MPI_Allreduce(&my_stop_temp,&my_stop,1,MPI_INTEGER,MPI_MIN,MPI_COMM_WORLD);
else if (s==sync_or)
MPI_Allreduce(&my_stop_temp,&my_stop,1,MPI_INTEGER,MPI_MAX,MPI_COMM_WORLD);
stop=(my_stop==1);
}
void synchronize_dt(double& dt)
{
double dttemp=dt;
MPI_Allreduce(&dttemp,&dt,1,MPI_DOUBLE,MPI_MIN,MPI_COMM_WORLD);
}
void modifie_n_TrioDEC(TrioDEC& dec)
{
dec.setNature(IntensiveMaximum); // Mot cle MEDCoupling pour le calcul par integration du debit par exemple
}
int main(int argc,char **argv) {
// Initialisation of MPI and creation of processor groups
MPI_Init(&argc,&argv);
// Begin
{
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
int nproc_dom=1; // nb of procs specified in the dom.data file // + ICoCo couplage
if (size !=nproc_dom) {
cout << "pb: must run on "<<nproc_dom <<" processors !"<<endl;
exit(1);
}
CommInterface comm;
set<int> dom_ids;
int n=0;
for (n=0;n<nproc_dom;n++)
dom_ids.insert(n);
MPIProcessorGroup dom_group(comm,dom_ids);
// Initialisation of Trio_U
std::string data_file;
const MPI_Comm* mpicomm=0;
if (dom_group.containsMyRank()) {
data_file="test"; // name of the first dom.data file // + ICoCo couplage
// Redirection des sorties couplage dans dom.out et dom.err
if (!freopen("test.out","w",stdout)) abort(); // + ICoCo couplage
if (!freopen("test.err","w",stderr)) abort(); // + ICoCo couplage
mpicomm=dom_group.getComm();
}
else
throw 0;
// Instanciation of Trio_U
Problem* T;
T=getProblem(); // new ProblemTrio;
T->setDataFile(data_file);
T->setMPIComm((void*)mpicomm);
T->initialize();
cout<<endl;
cout << "######################" << endl;
cout << data_file << " successfully initialised" << endl;
cout << "Listing Output Field Names:" << endl;
vector<string> outputnames=T->getOutputFieldsNames();
for (unsigned int ii=0;ii<outputnames.size();ii++)
cout<<data_file<<" Field Output " <<outputnames[ii]<<endl;
cout << "Listing Input Field Names:" << endl;
vector<string> inputnames=T->getInputFieldsNames();
for (unsigned int ii=0;ii<inputnames.size();ii++)
cout<<data_file<<" Field Input " <<inputnames[ii]<<endl;
cout << "######################" << endl;
// Field transferred
#ifdef MM
MEDDoubleField field_power;
#else
TrioField field_power;
#endif
bool stop=false; // Does the Problem want to stop ?
bool ok=true; // Is the time interval successfully solved ?
synchronize_bool(stop,sync_or);
// Boucle sur les pas de temps
while (!stop) {
ok=false; // Time interval not yet successfully solved
// Loop on the time interval tries
while (!ok && !stop) {
// Compute the time step length
// and check if the Problem wants to stop
double dt=T->computeTimeStep(stop);
synchronize_dt(dt);
synchronize_bool(stop, sync_or);
if (stop) // Impossible to solve the next time step, the Problem has given up
break;
// Prepare the next time step
T->initTimeStep(dt);
// Perform field exchange
{
////////////////////////////////////////////////////
// On renseigne le maillage des champs a recevoir.//
////////////////////////////////////////////////////
cout<<endl;
cout << "######################" << endl;
cout << "Getting Output Fields" << endl;
cout << "Getting Input Field Templates" << endl;
if (dom_group.containsMyRank()) {
#ifdef MM
T->getInputMEDDoubleFieldTemplate("POWERDENSITY_CORE",field_power); // cf. "Boundary_Conditions" block in dom.data // + ICoCo couplage
#else
T->getInputFieldTemplate("POWERDENSITY_CORE",field_power); // cf. "Boundary_Conditions" block in dom.data // + ICoCo couplage
#endif
}
////////////////////////////////////////////////////////////////////////
// On receptionne les champs en appliquant ou non une sous-relaxation.//
////////////////////////////////////////////////////////////////////////
cout << "Setting Input Fields" << endl;
if (dom_group.containsMyRank() ) {
#ifdef MM
//int nbcase=field_power.getMCField()->getArray()->getNumberOfTuples();
//for(int i=0;i<nbcase;i++) {
// field_power.getMCField()->getArray()->setIJ(i,0,25.);
//}
field_power.getMCField()->getArray()->fillWithValue(25.);
T->setInputMEDDoubleField("POWERDENSITY_CORE",field_power); // cf. "Boundary_Conditions" block in dom.data // + ICoCo couplage
#else
field_power.set_standalone();
int nbcase=field_power.nb_values()*field_power._nb_field_components;
for(int i=0;i<nbcase;i++) {
field_power._field[i]=25.;
}
T->setInputField("POWERDENSITY_CORE",field_power); // cf. "Boundary_Conditions" block in dom.data // + ICoCo couplage
#endif
}
cout << "######################" << endl;
} // End perform field exchange
// Solve the next time step
ok=T->solveTimeStep();
synchronize_bool(ok,sync_and);
if (!ok) // The resolution failed, try with a new time interval.
T->abortTimeStep();
else // The resolution was successful, validate and go to the next time step.
T->validateTimeStep();
} // End loop on the time interval tries
// Stop the resolution if the Problem is stationnary
bool stat=T->isStationary();
synchronize_bool(stat, sync_and);
if (stat)
stop=true;
} // Fin boucle sur les pas de temps
T->terminate();
delete T;
} // End
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
} // end main
| 30.893023 | 150 | 0.596206 | [
"vector"
] |
fa66c5f2d95e486cf8451b437982886634815016 | 762 | hpp | C++ | src/engine/effect/Shadow.hpp | stanfortonski/Procedural-Terrain-Generator-OpenGL | a88bf2d7a44e7efa10dd980147e2bad0d1a782bf | [
"MIT"
] | 93 | 2020-03-06T21:40:48.000Z | 2022-03-28T06:30:55.000Z | src/engine/effect/Shadow.hpp | pashashigalev/Shigalev-Pavel | 0c9094f409eb5a9d44ea4825fba86fcfe07a757e | [
"BSD-3-Clause"
] | 1 | 2021-08-31T07:56:37.000Z | 2021-08-31T16:06:35.000Z | src/engine/effect/Shadow.hpp | stanfortonski/Procedural-Terrain-Generator-OpenGL | a88bf2d7a44e7efa10dd980147e2bad0d1a782bf | [
"MIT"
] | 10 | 2020-06-06T11:21:35.000Z | 2022-03-24T01:55:20.000Z | /* Copyright (c) 2020 by Stan Fortoński */
#ifndef SHADOW_HPP
#define SHADOW_HPP 1
#include <vector>
#include <glm/glm.hpp>
#include "../buffer/FrameBuffer.hpp"
#include "../buffer/CubeDepthBuffer.hpp"
#include "../Config.hpp"
#include "../renderable/light/light.hpp"
namespace Engine
{
class Shadow
{
FrameBuffer depth;
CubeDepthBuffer depthBuffer;
void initCastShadow(const Light & light, const std::vector<Program*> & programs);
public:
Shadow();
virtual ~Shadow(){;}
void startCastShadow(const Light & light, const std::vector<Program*> & programs);
void endCastShadow(const Light & light, const std::vector<Program*> & programs);
void updateBuffer();
ShadowTransforms generateShadowTransforms();
};
}
#endif
| 23.8125 | 86 | 0.7021 | [
"vector"
] |
fa68c05d80a27a3dec216ad4f05c879ba95a7aef | 1,079 | cpp | C++ | grpc/cpp-cubic/cubic_model.cpp | cobaltspeech/sdk-cubic | 68ed5b67d4aa32f1b5085f6f167614b0fe6aeccb | [
"Apache-2.0"
] | 5 | 2019-10-10T09:30:58.000Z | 2020-05-28T11:08:00.000Z | grpc/cpp-cubic/cubic_model.cpp | cobaltspeech/sdk-cubic | 68ed5b67d4aa32f1b5085f6f167614b0fe6aeccb | [
"Apache-2.0"
] | 75 | 2019-04-18T07:55:25.000Z | 2022-02-11T02:36:04.000Z | grpc/cpp-cubic/cubic_model.cpp | cobaltspeech/sdk-cubic | 68ed5b67d4aa32f1b5085f6f167614b0fe6aeccb | [
"Apache-2.0"
] | 2 | 2020-01-07T19:57:19.000Z | 2020-01-08T22:02:12.000Z | // Copyright (2019) Cobalt Speech and Language, Inc.
#include "cubic_model.h"
CubicModel::CubicModel(const cobaltspeech::cubic::Model &model) :
mId(model.id()),
mName(model.name()),
mSampleRate(model.attributes().sample_rate()),
mSupportsContext(model.attributes().context_info().supports_context())
{
// getting list of context tokens
cobaltspeech::cubic::ContextInfo contextInfo = model.attributes().context_info();
mAllowedContextTokens.resize(contextInfo.allowed_context_tokens_size());
for(int i=0; i < mAllowedContextTokens.size(); i++)
{
mAllowedContextTokens[i] = contextInfo.allowed_context_tokens(i);
}
}
CubicModel::~CubicModel()
{}
const std::string& CubicModel::id() const
{
return mId;
}
const std::string& CubicModel::name() const
{
return mName;
}
unsigned int CubicModel::sampleRate() const
{
return mSampleRate;
}
bool CubicModel::supportsContext() const
{
return mSupportsContext;
}
std::vector<std::string> CubicModel::allowedContextTokens() const
{
return mAllowedContextTokens;
}
| 22.957447 | 85 | 0.714551 | [
"vector",
"model"
] |
fa6dcb86155c58b0c9c431e1386733f6cadc995a | 2,297 | cpp | C++ | src/OutputHID.cpp | erichlf/Hemiola | 3549be9b9cba907ddb5bb581872fc96d435995c7 | [
"MIT"
] | null | null | null | src/OutputHID.cpp | erichlf/Hemiola | 3549be9b9cba907ddb5bb581872fc96d435995c7 | [
"MIT"
] | 29 | 2021-12-16T16:00:28.000Z | 2022-02-01T18:37:28.000Z | src/OutputHID.cpp | erichlf/Hemiola | 3549be9b9cba907ddb5bb581872fc96d435995c7 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2021 Erich L Foster
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 "OutputHID.h"
#include "Exceptions.h"
#include "KeyboardEvents.h"
#include "Logger.h"
#include <fcntl.h>
#include <fmt/ranges.h>
#include <linux/input.h>
#include <unistd.h>
#include <cassert>
#include <vector>
using namespace hemiola;
hemiola::OutputHID::OutputHID ( const std::string& device )
: HID ( device )
{}
hemiola::OutputHID::~OutputHID()
{
// make sure all key presses are released
write ( KeyReport {} );
}
void hemiola::OutputHID::open()
{
HID::open ( O_WRONLY | O_SYNC );
}
void hemiola::OutputHID::write ( const KeyReport& report ) const
{
assert ( m_Opened );
LOG ( DEBUG, "Sending Report: {}, ({})", report.modifiers, fmt::join ( report.keys, ", " ) );
const auto data = std::vector<uint8_t> { report.modifiers, 0x00,
report.keys [0], report.keys [1],
report.keys [2], report.keys [3],
report.keys [4], report.keys [5] };
if ( ::write ( m_HIDId, data.data(), sizeof ( uint8_t ) * data.size() ) <= 0 ) {
throw IoException ( "Unable to write to output device", errno );
}
}
| 35.338462 | 97 | 0.668698 | [
"vector"
] |
fa87918ad3b23b41dd96e4463bd704cb3722a890 | 11,999 | cpp | C++ | test/test_uart.cpp | JasonFevang/R502-interface | 73d842f5d23624625f2e687a2acdc3dcc3511eb5 | [
"MIT"
] | null | null | null | test/test_uart.cpp | JasonFevang/R502-interface | 73d842f5d23624625f2e687a2acdc3dcc3511eb5 | [
"MIT"
] | null | null | null | test/test_uart.cpp | JasonFevang/R502-interface | 73d842f5d23624625f2e687a2acdc3dcc3511eb5 | [
"MIT"
] | null | null | null | #include <limits.h>
#include "unity.h"
#include <array>
#include "R502Interface.hpp"
#include "esp_err.h"
#include "esp_log.h"
#include "esp32/rom/uart.h"
#define PIN_TXD (GPIO_NUM_4)
#define PIN_NC_1 (GPIO_NUM_16)
#define PIN_NC_2 (GPIO_NUM_17)
#define PIN_NC_3 (GPIO_NUM_18)
#define PIN_RXD (GPIO_NUM_5)
#define PIN_IRQ (GPIO_NUM_13)
#define PIN_RTS (UART_PIN_NO_CHANGE)
#define PIN_CTS (UART_PIN_NO_CHANGE)
#define TAG "TestR502"
// The object under test
static R502Interface R502;
void tearDown(){
R502.deinit();
}
void wait_with_message(char *message){
printf(message);
uart_rx_one_char_block();
}
static int up_image_size = 0;
void up_image_callback(std::array<uint8_t, R502_max_data_len * 2> &data,
int data_len)
{
// this is where you would store or otherwise do something with the image
up_image_size += data_len;
//int box_width = 16;
//int total = 0;
//while(total < data_len){
//for(int i = 0; i < box_width; i++){
//printf("0x%02X ", data[total]);
//total++;
//}
//printf("\n");
//}
// Check that all bytes have the lower four bytes 0
for(int i = 0; i < data_len; i++){
TEST_ASSERT_EQUAL(0, data[i] & 0x0f);
}
}
TEST_CASE("Not connected", "[initialization]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_NC_1, PIN_NC_2, PIN_NC_3);
TEST_ESP_OK(err);
std::array<uint8_t, 4> pass = {0x00, 0x00, 0x00, 0x00};
R502_conf_code_t conf_code = R502_fail;
err = R502.vfy_pass(pass, conf_code);
TEST_ASSERT_EQUAL(ESP_ERR_NOT_FOUND, err);
}
TEST_CASE("Reinitialize", "[initialization]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_NC_1, PIN_NC_2, PIN_NC_3);
TEST_ESP_OK(err);
err = R502.deinit();
TEST_ESP_OK(err);
err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
std::array<uint8_t, 4> pass = {0x00, 0x00, 0x00, 0x00};
R502_conf_code_t conf_code = R502_fail;
err = R502.vfy_pass(pass, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(conf_code, R502_ok);
}
TEST_CASE("VfyPwd", "[system command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
std::array<uint8_t, 4> pass = {0x00, 0x00, 0x00, 0x00};
R502_conf_code_t conf_code = R502_fail;
err = R502.vfy_pass(pass, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
pass[3] = 0x01;
err = R502.vfy_pass(pass, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_err_wrong_pass, conf_code);
err = R502.deinit();
TEST_ESP_OK(err);
}
TEST_CASE("ReadSysPara", "[system command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_sys_para_t sys_para;
R502_conf_code_t conf_code;
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
TEST_ASSERT_EQUAL_UINT8_ARRAY(R502.get_module_address(),
sys_para.device_address, 4);
printf("status_register %d\n", sys_para.status_register);
printf("system_identifier_code %d\n", sys_para.system_identifier_code);
printf("finger_library_size %d\n", sys_para.finger_library_size);
printf("security_level %d\n", sys_para.security_level);
printf("device_address %x%x%x%x\n", sys_para.device_address[0],
sys_para.device_address[1], sys_para.device_address[2],
sys_para.device_address[3]);
printf("data_package_length %d\n", sys_para.data_package_length);
printf("baud_setting %d\n", sys_para.baud_setting);
}
TEST_CASE("SetBaudRate", "[system command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_conf_code_t conf_code = R502_fail;
R502_baud_t current_baud = R502_baud_57600;
R502_sys_para_t sys_para;
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
current_baud = sys_para.baud_setting;
// 9600
err = R502.set_baud_rate(R502_baud_9600, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
// 19200
err = R502.set_baud_rate(R502_baud_19200, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
// 38400
err = R502.set_baud_rate(R502_baud_38400, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
// 57600
err = R502.set_baud_rate(R502_baud_57600, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
// 115200
err = R502.set_baud_rate(R502_baud_115200, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
// error baud rate
conf_code = R502_fail;
err = R502.set_baud_rate((R502_baud_t)9600, conf_code);
TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, err);
TEST_ASSERT_EQUAL(R502_fail, conf_code);
// rest baud rate to what it was before testing
err = R502.set_baud_rate(current_baud, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
}
TEST_CASE("SetSecurityLevel", "[system command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_conf_code_t conf_code = R502_fail;
int current_security_level = 0;
R502_sys_para_t sys_para;
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
current_security_level = sys_para.security_level;
for(int sec_lev = 1; sec_lev <= 5; sec_lev++){
err = R502.set_security_level(sec_lev, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
TEST_ASSERT_EQUAL(sys_para.security_level, sec_lev);
}
conf_code = R502_fail;
err = R502.set_security_level(6, conf_code);
TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, err);
TEST_ASSERT_EQUAL(R502_fail, conf_code);
err = R502.set_security_level(current_security_level, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
}
TEST_CASE("SetDataPackageLength", "[system command]")
{
// Can only set to 128 and 256 bytes, not 32 or 64
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_conf_code_t conf_code = R502_fail;
R502_data_len_t current_data_length = R502_data_len_32;
R502_sys_para_t sys_para;
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
current_data_length = sys_para.data_package_length;
err = R502.set_data_package_length(R502_data_len_64, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
// this should be 64bytes, but my module only goes down to 128
// Leaving assert in so if it changes with another module I will know
TEST_ASSERT_EQUAL(R502_data_len_128, sys_para.data_package_length);
err = R502.set_data_package_length(R502_data_len_256, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
TEST_ASSERT_EQUAL(R502_data_len_256, sys_para.data_package_length);
err = R502.set_data_package_length(R502_data_len_128, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
TEST_ASSERT_EQUAL(R502_data_len_128, sys_para.data_package_length);
// reset to starting data length
err = R502.set_data_package_length(current_data_length, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
}
TEST_CASE("TemplateNum", "[system command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_conf_code_t conf_code;
uint16_t template_num = 65535;
err = R502.template_num(conf_code, template_num);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
}
TEST_CASE("GenImage", "[fingerprint processing command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_conf_code_t conf_code;
err = R502.gen_image(conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_err_no_finger, conf_code);
}
TEST_CASE("GenImageSuccess", "[fingerprint processing command][userInput]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502_conf_code_t conf_code;
wait_with_message("Place finger on sensor, then press enter\n");
err = R502.gen_image(conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
}
TEST_CASE("UpImage", "[fingerprint processing command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
// read and save current data_package_length and baud rate
R502_sys_para_t sys_para;
R502_conf_code_t conf_code;
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
R502_data_len_t starting_data_len = sys_para.data_package_length;
// Attempt up_image without setting the callback
err = R502.up_image(starting_data_len, conf_code);
TEST_ASSERT_EQUAL(ESP_ERR_INVALID_STATE, err);
// reset counter to measure size of the uploaded image
R502.set_up_image_cb(up_image_callback);
up_image_size = 0;
err = R502.up_image(starting_data_len, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
TEST_ASSERT_EQUAL(R502_image_size, up_image_size);
}
TEST_CASE("UpImageAdvanced", "[fingerprint processing command]")
{
esp_err_t err = R502.init(UART_NUM_1, PIN_TXD, PIN_RXD, PIN_IRQ);
TEST_ESP_OK(err);
R502.set_up_image_cb(up_image_callback);
// read and save current data_package_length and baud rate
R502_sys_para_t sys_para;
R502_conf_code_t conf_code;
err = R502.read_sys_para(conf_code, sys_para);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
R502_data_len_t starting_data_len = sys_para.data_package_length;
R502_baud_t starting_baud = sys_para.baud_setting;
R502_baud_t test_bauds[5] = { R502_baud_9600, R502_baud_19200,
R502_baud_38400, R502_baud_57600, R502_baud_115200 };
R502_data_len_t test_data_lens[2] = { R502_data_len_128,
R502_data_len_256 };
// Loop through all bauds and data lengths to test all combinations
for(int baud_i = 0; baud_i < 5; baud_i++){
ESP_LOGI(TAG, "Test baud %d", test_bauds[baud_i]);
err = R502.set_baud_rate(test_bauds[baud_i], conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
for(int data_i = 0; data_i < 2; data_i++){
ESP_LOGI(TAG, "Test data len %d", test_data_lens[data_i]);
// reset counter to measure size of the uploaded image
up_image_size = 0;
err = R502.set_data_package_length(test_data_lens[data_i],
conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
err = R502.up_image(test_data_lens[data_i], conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
TEST_ASSERT_EQUAL(R502_image_size, up_image_size);
}
}
// reset the data package length and baud settings to default
err = R502.set_data_package_length(starting_data_len, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
err = R502.set_baud_rate(starting_baud, conf_code);
TEST_ESP_OK(err);
TEST_ASSERT_EQUAL(R502_ok, conf_code);
} | 33.238227 | 77 | 0.708809 | [
"object"
] |
fa896dcfcb2527cc40cdc7a1705c1ef01972012c | 3,521 | cpp | C++ | src/Canvas.cpp | SpookyGhost2D/SpookyGhost | bfddccee9239aedf7928e781042e5ca1d78a49e1 | [
"MIT"
] | 182 | 2021-05-23T19:00:06.000Z | 2022-03-29T06:00:18.000Z | src/Canvas.cpp | SpookyGhost2D/SpookyGhost | bfddccee9239aedf7928e781042e5ca1d78a49e1 | [
"MIT"
] | 2 | 2021-05-25T04:56:23.000Z | 2021-11-08T17:52:26.000Z | src/Canvas.cpp | SpookyGhost2D/SpookyGhost | bfddccee9239aedf7928e781042e5ca1d78a49e1 | [
"MIT"
] | 9 | 2021-06-02T16:47:56.000Z | 2021-12-04T08:40:18.000Z | #include <ncine/config.h>
#include "Canvas.h"
#include "RenderingResources.h"
#include <ncine/Application.h>
#include <ncine/GLTexture.h>
#include <ncine/GLFramebufferObject.h>
#include <ncine/TextureSaverPng.h>
#include "shader_strings.h"
#ifdef __MINGW32__
#undef ERROR
#endif
///////////////////////////////////////////////////////////
// CONSTRUCTORS and DESTRUCTOR
///////////////////////////////////////////////////////////
Canvas::Canvas()
: backgroundColor(0.0f, 0.0f, 0.0f, 0.0f),
texWidth_(0), texHeight_(0), texSizeInBytes_(0)
{
const nc::IGfxCapabilities &gfxCaps = nc::theServiceLocator().gfxCapabilities();
maxTextureSize_ = gfxCaps.value(nc::IGfxCapabilities::GLIntValues::MAX_TEXTURE_SIZE);
}
Canvas::Canvas(int texWidth, int texHeight)
: backgroundColor(0.0f, 0.0f, 0.0f, 0.0f),
texWidth_(texWidth), texHeight_(texHeight), texSizeInBytes_(0)
{
const nc::IGfxCapabilities &gfxCaps = nc::theServiceLocator().gfxCapabilities();
maxTextureSize_ = gfxCaps.value(nc::IGfxCapabilities::GLIntValues::MAX_TEXTURE_SIZE);
resizeTexture(texWidth, texHeight);
}
///////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
///////////////////////////////////////////////////////////
void Canvas::resizeTexture(int width, int height)
{
FATAL_ASSERT(width > 0);
FATAL_ASSERT(height > 0);
if (pixels_ == nullptr || width != texWidth_ || height != texHeight_)
{
texWidth_ = (width <= maxTextureSize_) ? width : maxTextureSize_;
texHeight_ = (height <= maxTextureSize_) ? height : maxTextureSize_;
texSizeInBytes_ = static_cast<unsigned int>(texWidth_ * texHeight_ * 4);
pixels_ = nctl::makeUnique<unsigned char[]>(texSizeInBytes_);
texture_ = nctl::makeUnique<nc::GLTexture>(GL_TEXTURE_2D);
texture_->texStorage2D(1, GL_RGBA8, width, height);
texture_->texParameteri(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texture_->texParameteri(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
fbo_ = nctl::makeUnique<nc::GLFramebufferObject>();
fbo_->attachTexture(*texture_, GL_COLOR_ATTACHMENT0);
if (fbo_->isStatusComplete() == false)
LOGE("Framebuffer object status is not complete\n");
}
}
void Canvas::bindTexture()
{
texture_->bind();
}
void Canvas::unbindTexture()
{
texture_->unbind();
}
void Canvas::bindRead()
{
fbo_->bind(GL_READ_FRAMEBUFFER);
}
void Canvas::bindDraw()
{
fbo_->bind(GL_DRAW_FRAMEBUFFER);
}
void Canvas::bind()
{
RenderingResources::setCanvasSize(texWidth_, texHeight_);
glViewport(0, 0, texWidth_, texHeight_);
fbo_->bind(GL_FRAMEBUFFER);
glClearColor(backgroundColor.r(), backgroundColor.g(), backgroundColor.b(), backgroundColor.a());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Canvas::unbind()
{
fbo_->unbind();
glViewport(0, 0, nc::theApplication().widthInt(), nc::theApplication().heightInt());
}
void Canvas::save(const char *filename)
{
#if !defined(NCINE_WITH_OPENGLES) && !defined(__EMSCRIPTEN__)
fbo_->unbind();
texture_->getTexImage(0, GL_RGBA, GL_UNSIGNED_BYTE, pixels_.get());
#else
fbo_->bind(GL_READ_FRAMEBUFFER);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glReadPixels(0, 0, texWidth_, texHeight_, GL_RGBA, GL_UNSIGNED_BYTE, pixels_.get());
fbo_->unbind();
#endif
nc::TextureSaverPng saver;
nc::ITextureSaver::Properties props;
props.width = texWidth_;
props.height = texHeight_;
props.pixels = pixels_.get();
props.format = nc::ITextureSaver::Format::RGBA8;
saver.saveToFile(props, filename);
}
void *Canvas::imguiTexId()
{
return reinterpret_cast<void *>(texture_.get());
}
| 27.944444 | 98 | 0.689577 | [
"object"
] |
fa8cf19242c9eac1df86bf3962f48be5458299fa | 2,717 | cpp | C++ | C++/Trajectory/graph.cpp | MohamedMkaouar/Some_Projects | 8170126dc91f313638595f9f4b81e9ae8b308334 | [
"Apache-2.0"
] | null | null | null | C++/Trajectory/graph.cpp | MohamedMkaouar/Some_Projects | 8170126dc91f313638595f9f4b81e9ae8b308334 | [
"Apache-2.0"
] | null | null | null | C++/Trajectory/graph.cpp | MohamedMkaouar/Some_Projects | 8170126dc91f313638595f9f4b81e9ae8b308334 | [
"Apache-2.0"
] | 1 | 2021-02-02T17:09:04.000Z | 2021-02-02T17:09:04.000Z | #include <iostream>
#include <iterator>
#include <map>
#include <cmath>
#include <vector>
#include <limits.h>
#include <stdio.h>
#include <fstream>
#include<omp.h>
#include "graph.h"
using namespace std;
void graph::confirmGraph(){
for(int i=0;i<A.size();i++)
{
cout<<"arc numero"<<i+1<<"\n"<<A[i]<<endl;
};
}
bool test_intersect(sommet S1,sommet S2,vector <sommet> A1){
int n=A1.size();
int j=0;
segment s(S1,S2);
for(int i=0;i<n;i++)
{
segment s2(A1[i],A1[i+1]);
if(s.intersect(s2)==1)
{
return 1;
};
};
return 0;
};
graph::graph(vector <sommet> V)
{
int size=V.size();
int i;
for(i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
A.push_back(arc(V[i],V[j]));
}
}
};
float graph::traj(sommet C,sommet B){
for(int i=0;i<A.size();i++)
{
if(((A[i].start==C)&&(A[i].end==B))||((A[i].start==B)&&(A[i].end==C)))
{
return A[i].cost;
}
}
return 0;
}
vector<vector<float>> graph::ComputeMatrix(vector<sommet> S){
vector<float>L;
vector<vector<float>> M;
#pragma omp parallel for
for(int i=0;i<S.size();i++)
{
for(int j=0;j<S.size();j++)
{
//cout<<T[i]<<T[j]<<endl;
//cout<<traj(T[i],T[j],g_new);
L.push_back(traj(S[i],S[j]));
//cout<<"L="<<L[j]<<endl;
}
//cout<<"size of L"<<L.size()<<endl;
M.push_back(L);
L.clear();
}
return M;
}
void graph::ShortestPath(vector<sommet> T,int startnode,int n) {
vector<vector<float>> G = ComputeMatrix(T);
int max=G.size();
float cost[max][max],distance[max],pred[max];
int visited[max],count;
float mindistance;
int nextnode,i,j;
for(i=0;i<max;i++)
{
for(j=0;j<max;j++)
{
if(G[i][j]==0)
cost[i][j]=9999;
else
cost[i][j]=G[i][j];
}}
for(i=0;i<max;i++) {
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<max-1) {
mindistance=9999;
for(i=0;i<max;i++)
if(distance[i]<mindistance&&!visited[i]) {
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<max;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i]) {
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<max;i++)
if(i!=startnode) {
cout<<"\nDistance of node"<<i<<"="<<distance[i];
cout<<"\nPath="<<i;
j=i;
do {
j=pred[j];
cout<<"<-"<<j;
}while(j!=startnode);
}
}
| 19 | 74 | 0.503865 | [
"vector"
] |
fa917e287655e93cd71a81af82d319dd1aeedb3e | 3,809 | cc | C++ | Samples/2_ConstantBuff/Source/FObjTriangle.cc | liliilli/SH-D3D11 | 1ffb4639d5d9dd06d08b2aa21ebc781ee22fb26c | [
"Unlicense",
"MIT"
] | null | null | null | Samples/2_ConstantBuff/Source/FObjTriangle.cc | liliilli/SH-D3D11 | 1ffb4639d5d9dd06d08b2aa21ebc781ee22fb26c | [
"Unlicense",
"MIT"
] | null | null | null | Samples/2_ConstantBuff/Source/FObjTriangle.cc | liliilli/SH-D3D11 | 1ffb4639d5d9dd06d08b2aa21ebc781ee22fb26c | [
"Unlicense",
"MIT"
] | null | null | null | ///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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 <FObjTriangle.h>
#include <Graphics/MD3D11Resources.h>
#include <Resource/D11DefaultHandles.h>
#include <Math/Utility/XGraphicsMath.h>
#include <MGuiManager.h>
#include <FGuiWindow.h>
#include <XBuffer.h>
namespace
{
inline std::array<DVertex, 3> vertices =
{
DVertex
{ {-1.0f, -1.0f, 0.0f}, {1.0f, 1.0f, 0.0f, 1.0f} },
{ {+1.0f, -1.0f, 0.0f}, {0.0f, 1.0f, 1.0f, 1.0f} },
{ {+0.0f, +1.0f, 0.0f}, {1.0f, 0.0f, 1.0f, 1.0f} },
};
// Create Index Buffer.
inline std::array<unsigned, 3> indices =
{ // 1 2 3 4
0, 1, 2,
};
}
void FObjTriangle::Initialize(void* pData)
{
const auto& param = *static_cast<DObjTriangle*>(pData);
assert(param.mpData != nullptr);
assert(param.mpCbObject != nullptr);
const auto& defaults = *param.mpData;
this->hCbObject = *param.mpCbObject;
this->mDc.emplace(MD3D11Resources::GetDeviceContext(defaults.mDevice));
this->mCbObject.emplace(MD3D11Resources::GetBuffer(this->hCbObject));
{
D3D11_BUFFER_DESC vbDesc = {};
vbDesc.Usage = D3D11_USAGE_IMMUTABLE;
vbDesc.ByteWidth = sizeof(vertices);
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.CPUAccessFlags = 0;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
this->hVBuffer = *MD3D11Resources::CreateBuffer(defaults.mDevice, vbDesc, vertices.data());
assert(MD3D11Resources::HasBuffer(hVBuffer) == true);
this->mVBuffer.emplace(MD3D11Resources::GetBuffer(this->hVBuffer));
}
{
D3D11_BUFFER_DESC ibDesc;
ibDesc.Usage = D3D11_USAGE_IMMUTABLE;
ibDesc.ByteWidth = sizeof(indices);
ibDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibDesc.CPUAccessFlags = 0;
ibDesc.MiscFlags = 0;
ibDesc.StructureByteStride = 0;
this->hIBuffer = *MD3D11Resources::CreateBuffer(defaults.mDevice, ibDesc, indices.data());
assert(MD3D11Resources::HasBuffer(hIBuffer) == true);
this->mIBuffer.emplace(MD3D11Resources::GetBuffer(this->hIBuffer));
}
}
void FObjTriangle::Release(void* pData)
{
this->mVBuffer = std::nullopt;
this->mIBuffer = std::nullopt;
{
const auto flag = MD3D11Resources::RemoveBuffer(this->hIBuffer);
assert(flag == true);
}
{
const auto flag = MD3D11Resources::RemoveBuffer(this->hVBuffer);
assert(flag == true);
}
}
void FObjTriangle::Update(float delta)
{
if (MGuiManager::HasSharedModel("Window") == true)
{
auto& model = static_cast<DModelWindow&>(MGuiManager::GetSharedModel("Window"));
this->mScale = model.mScale;
}
}
void FObjTriangle::Render()
{
assert(this->mCbObject.has_value() == true);
assert(this->mDc.has_value() == true);
// Update object matrix
{
using namespace ::dy::math;
init.mModel = CreateModelMatrix<TReal>(
EGraphics::DirectX,
this->mPosition, this->mDegRotate, this->mScale,
true);
}
(*this->mDc)->UpdateSubresource((*this->mCbObject).GetPtr(), 0, nullptr, &this->init, 0, 0);
// Set Vertex, Index and draw.
auto* pVBuffer = (*mVBuffer).GetPtr();
UINT stride = sizeof(DVertex); UINT offset = 0;
(*this->mDc)->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
(*this->mDc)->IASetIndexBuffer((*mIBuffer).GetPtr(), DXGI_FORMAT_R32_UINT, 0);
(*this->mDc)->DrawIndexed(3, 0, 0);
}
| 29.757813 | 95 | 0.678918 | [
"render",
"object",
"model"
] |
fa93475b68ea78d51e0ff7a3470f1edde48d73fb | 24,500 | cpp | C++ | src/SubsetOfRegressors.cpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | 3 | 2019-08-04T20:18:00.000Z | 2021-06-22T23:50:27.000Z | src/SubsetOfRegressors.cpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | null | null | null | src/SubsetOfRegressors.cpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by friedrich on 16.08.16.
//
#include <SubsetOfRegressors.hpp>
#include <assert.h>
#include <random>
#include <algorithm>
#include <iostream>
#include <cmath>
//--------------------------------------------------------------------------------
SubsetOfRegressors::SubsetOfRegressors(int n, double &delta_input) :
FullyIndependentTrainingConditional(n, delta_input) {
}
//--------------------------------------------------------------------------------
SubsetOfRegressors::SubsetOfRegressors(int n, double &delta_input, std::vector<double> gp_parameters_input) :
FullyIndependentTrainingConditional(n, delta_input, gp_parameters_input) {
}
//--------------------------------------------------------------------------------
void SubsetOfRegressors::build(std::vector<std::vector<double> > const &nodes,
std::vector<double> const &values, std::vector<double> const &noise) {
int nb_u_nodes = u.rows();
if (nb_u_nodes > 0) {
std::cout << "SoR build with [" << nodes.size() << "," << nb_u_nodes
<< "]" << std::endl;
std::cout << "With Parameters: " << std::endl;
for ( int i = 0; i < dim+1; ++i )
std::cout << "gp_param = " << gp_parameters[i] << std::endl;
std::cout << std::endl;
//nb_u_nodes++;
nb_gp_nodes = nodes.size();
gp_nodes.clear();
gp_noise.clear();
gp_nodes_eigen.resize(nb_gp_nodes, dim);
gp_noise_eigen.resize(nb_gp_nodes);
for (int i = 0; i < nb_gp_nodes; ++i) {
gp_nodes.push_back(nodes.at(i));
gp_noise.push_back(noise.at(i));
for(int j = 0; j < dim; ++j){
gp_nodes_eigen(i,j) = nodes[i][j];
}
gp_noise_eigen(i) = noise[i];
}
/*
if (resample_u){
this->sample_u(nb_u_nodes);
if (do_hp_estimation)
this->estimate_hyper_parameters(nodes, values, noise);
resample_u = false;
}
*/
//Set up matrix K_u_f and K_f_u
compute_Kuf_and_Kuu();
MatrixXd K_f_u = K_u_f.transpose();
VectorXd diag_Q_f_f;
compute_Qff(K_f_u, diag_Q_f_f);
VectorXd diag_K_f_f;
compute_Kff(diag_K_f_f);
VectorXd diff_Kff_Qff(nb_gp_nodes);
diff_Kff_Qff.setZero();
compute_Lambda(diff_Kff_Qff, noise);
MatrixXd Lambda_K_f_u;
compute_Lambda_times_Kfu(K_f_u, Lambda_K_f_u);
MatrixXd K_u_f_Lambda_f_u;
compute_KufLambdaKfu(Lambda_K_f_u, K_u_f_Lambda_f_u);
L_eigen.compute(K_u_u + K_u_f_Lambda_f_u);
scaled_function_values.clear();
scaled_function_values.resize(nb_gp_nodes);
for (int i = 0; i < nb_gp_nodes; i++) {
scaled_function_values.at(i) = values.at(i);
}
VectorXd LambdaInv_f;
compute_LambdaInvF(LambdaInv_f);
VectorXd alpha_eigen_rhs = K_u_f * LambdaInv_f;
//Solve Sigma_not_inv^(-1)*alpha
alpha_eigen = L_eigen.solve(alpha_eigen_rhs);
} else {
GaussianProcess::build(nodes, values, noise);
}
return;
}
//--------------------------------------------------------------------------------
void SubsetOfRegressors::evaluate(std::vector<double> const &x, double &mean,
double &variance) {
int nb_u_nodes = u.rows();
if (nb_u_nodes > 0) {
int nb_u_nodes = u.rows();
VectorXd x_eigen;
x_eigen.resize(x.size());
for(int i = 0; i < x.size(); ++i){
x_eigen(i) = x[i];
}
K0_eigen.resize(nb_u_nodes);
for (int i = 0; i < nb_u_nodes; i++) {
K0_eigen(i) = evaluate_kernel(x_eigen, u.row(i));
}
// std::cout << "K0" << std::endl;
// VectorOperations::print_vector(K0);
// std::cout << "alpha=(K_u_u + K_u_f*sigmaI*K_f_u)*K_u_f*noise*y:" << std::endl;
// VectorOperations::print_vector(alpha);
mean = K0_eigen.dot(alpha_eigen);
// std::cout << "mean:" << mean << std::endl;
variance = K0_eigen.dot(L_eigen.solve(K0_eigen));
/*
std::cout << "Variance: " << variance << std::endl;
std::cout << "######################################" << std::endl;
evaluate_counter++;
assert(evaluate_counter<20*3);
*/
} else {
GaussianProcess::evaluate(x, mean, variance);
}
return;
}
void SubsetOfRegressors::run_optimizer(std::vector<double> const &values){
double optval;
int exitflag;
nlopt::opt* local_opt;
nlopt::opt* global_opt;
int dimp1 = gp_parameters_hp.size();
set_optimizer(values, local_opt, global_opt);
std::vector<double> tol(dimp1);
for(int i = 0; i < dimp1; ++i){
tol[i] = 0.0;
}
if (optimize_global){
print = 0;
std::cout << "Global optimization" << std::endl;
exitflag=-20;
global_opt->add_inequality_mconstraint(trust_region_constraint, gp_pointer, tol);
global_opt->set_min_objective( parameter_estimation_objective, gp_pointer);
exitflag = global_opt->optimize(gp_parameters_hp, optval);
std::cout << "exitflag = "<< exitflag<<std::endl;
std::cout << "Function calls: " << print << std::endl;
std::cout << "OPTVAL .... " << optval << std::endl;
//for ( int i = 0; i < 1+dim; ++i )
// std::cout << "gp_param = " << gp_parameters_hp[i] << std::endl;
//std::cout << std::endl;
}
if (optimize_local){
print = 0;
std::cout << "Local optimization" << std::endl;
exitflag=-20;
//try {
local_opt->add_inequality_mconstraint(trust_region_constraint, gp_pointer, tol);
local_opt->set_min_objective( parameter_estimation_objective_w_gradients, gp_pointer);
exitflag = local_opt->optimize(gp_parameters_hp, optval);
std::cout << "exitflag = "<< exitflag<<std::endl;
std::cout << "Function calls: " << print << std::endl;
std::cout << "OPTVAL .... " << optval << std::endl;
//for ( int i = 0; i < 1+dim; ++i )
//std::cout << "gp_param = " << gp_parameters_hp[i] << std::endl;
//std::cout << std::endl;
}
delete local_opt;
delete global_opt;
return;
}
void SubsetOfRegressors::estimate_hyper_parameters_all ( std::vector< std::vector<double> > const &nodes,
std::vector<double> const &values,
std::vector<double> const &noise )
{
//std::cout << "in sor1" << std::endl;
if(u.rows() > 0){
copy_data_to_members(nodes, values, noise);
gp_pointer = this;
sample_u(u.rows());
set_hyperparameters();
run_optimizer(values);
copy_hyperparameters();
//this->build(nodes, values, noise);
for ( int i = 0; i < 1+dim; ++i )
std::cout << "gp_param = " << gp_parameters[i] << std::endl;
}else{
GaussianProcess::estimate_hyper_parameters(nodes, values, noise);
}
return;
}
void SubsetOfRegressors::estimate_hyper_parameters_induced_only ( std::vector< std::vector<double> > const &nodes,
std::vector<double> const &values,
std::vector<double> const &noise )
{
//std::cout << "in sor1" << "u size:" << u.rows() << std::endl;
if(u.rows() > 0){
copy_data_to_members(nodes, values, noise);
gp_pointer = this;
sample_u(u.rows());
set_hyperparameters_induced_only();
run_optimizer(values);
copy_hyperparameters();
//this->build(nodes, values, noise);
for ( int i = 0; i < 1+dim; ++i )
std::cout << "gp_param = " << gp_parameters[i] << std::endl;
}else{
GaussianProcess::estimate_hyper_parameters(nodes, values, noise);
}
return;
}
void SubsetOfRegressors::estimate_hyper_parameters_ls_only ( std::vector< std::vector<double> > const &nodes,
std::vector<double> const &values,
std::vector<double> const &noise )
{
if(u.rows() > 0){
copy_data_to_members(nodes, values, noise);
gp_pointer = this;
sample_u(u.rows());
set_hyperparameters_ls_only();
run_optimizer(values);
copy_hyperparameters();
//this->build(nodes, values, noise);
for ( int i = 0; i < 1+dim; ++i )
std::cout << "gp_param = " << gp_parameters[i] << std::endl;
}else{
GaussianProcess::estimate_hyper_parameters(nodes, values, noise);
}
return;
}
//--------------------------------------------------------------------------------
double SubsetOfRegressors::parameter_estimation_objective(std::vector<double> const &x,
std::vector<double> &grad,
void *data)
{
SubsetOfRegressors *d = reinterpret_cast<SubsetOfRegressors*>(data);
int offset;
std::vector<double> local_params(d->dim+1);
if(x.size()==1+d->dim){
offset = 0;
for(int i = 0; i < local_params.size(); ++i){
local_params[i] = x[i];
}
}else{
if(x.size() > d->u.rows()*d->dim){
offset = 1+d->dim;
for(int i = 0; i < local_params.size(); ++i){
local_params[i] = x[i];
}
}else{
offset = 0;
for(int i = 0; i < local_params.size(); ++i){
local_params[i] = d->gp_parameters[i];
}
}
int u_counter;
for (int i = 0; i < d->dim; ++i) {
u_counter = 0;
for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){
d->u(u_counter,i) = x[j];
u_counter++;
}
}
}
//Compute Kuf, Kuu
//Set up matrix K_u_f and K_f_u
int nb_gp_nodes = d->gp_nodes.size();
int nb_u_nodes = d->u.rows();
d->K_u_f.resize(nb_u_nodes, nb_gp_nodes);
for (int i = 0; i < nb_u_nodes; ++i) {
for (int j = 0; j < nb_gp_nodes; ++j) {
d->K_u_f(i,j) = d->evaluate_kernel(d->u.row(i), d->gp_nodes_eigen.row(j), local_params);
}
}
MatrixXd K_f_u = d->K_u_f.transpose();
//std::cout << "Kuf\n" << d->K_u_f << std::endl;
//Set up matrix K_u_u
d->K_u_u.resize(nb_u_nodes, nb_u_nodes);
for (int i = 0; i < nb_u_nodes; ++i) {
for (int j = 0; j < nb_u_nodes; ++j) {
d->K_u_u(i,j) = d->evaluate_kernel(d->u.row(i), d->u.row(j), local_params);
if(i==j)
d->K_u_u(i,j) += d->Kuu_opt_nugget;
}
}
//std::cout << "Kuu\n" << d->K_u_u << std::endl;
d->LLTofK_u_u.compute(d->K_u_u);
MatrixXd K_u_u_u_f = d->LLTofK_u_u.solve(d->K_u_f);
VectorXd diag_Q_f_f;
diag_Q_f_f.resize(nb_gp_nodes);
for (int i = 0; i < nb_gp_nodes; ++i) {
diag_Q_f_f(i) = 0.0;
for (int j = 0; j < nb_u_nodes; ++j) {
diag_Q_f_f(i) += (K_f_u(i,j) * K_u_u_u_f(j,i));
}
}
VectorXd diag_K_f_f;
diag_K_f_f.resize(nb_gp_nodes);
for (int i = 0; i < nb_gp_nodes; ++i) {
diag_K_f_f(i) = d->evaluate_kernel(d->gp_nodes_eigen.row(i),
d->gp_nodes_eigen.row(i), local_params);
}
/*std::cout << "diag_K_f_f\n" << diag_K_f_f << std::endl;
std::cout << "diag_Q_f_f\n" << diag_Q_f_f << std::endl;*/
d->Lambda.resize(nb_gp_nodes);
//std::cout << "noise\n" << std::endl;
for (int i = 0; i < nb_gp_nodes; ++i) {
d->Lambda(i) = (pow( d->gp_noise.at(i) / 2e0 + d->noise_regularization, 2e0 ));
}
//std::cout << std::endl;
MatrixXd Lambda_K_f_u;
Lambda_K_f_u.resize(nb_gp_nodes, nb_u_nodes);
for(int i = 0; i < nb_gp_nodes; i++){
for(int j = 0; j < nb_u_nodes; j++){
Lambda_K_f_u(i,j) = ((1.0/(d->Lambda(i) + d->Lambda_opt_nugget)) * K_f_u(i,j));
}
}
MatrixXd K_u_f_Lambda_f_u;
K_u_f_Lambda_f_u.resize(nb_u_nodes, nb_u_nodes);
K_u_f_Lambda_f_u = d->K_u_f*Lambda_K_f_u;
MatrixXd Sigma = d->K_u_u + K_u_f_Lambda_f_u;
for (int i = 0; i < nb_u_nodes; ++i) {
//Sigma(i,i) += nugget;
}
d->L_eigen.compute(Sigma);
double L12 = 0.0;//-log(d->K_u_u.determinant());
for (int i = 0; i < d->u.rows(); ++i){
L12 += log(d->LLTofK_u_u.vectorD()(i));
//std::cout << L1 << "L11-" << i << std::endl;
}
double det_Leigen = 0.0;
for (int i = 0; i < d->u.rows(); ++i){
det_Leigen += log(d->L_eigen.vectorD()(i));
//std::cout << d->L_eigen.matrixL()(i,i) << " " << log(d->L_eigen.matrixL()(i,i)) << "det_Leigen-" << i << std::endl;
}
double L11 = 0.0;
//std::cout << L1 << "L12 " << std::endl;
for (int i = 0; i < d->nb_gp_nodes; ++i){
L11 += log(d->Lambda(i));
//std::cout << "Lambda: " << i << " " << d->Lambda(i) <<" "<<log(d->Lambda(i)) << std::endl;
}
double L1 = 0.0;
//L1 = 0.5*L11 + (2*0.5)*det_Leigen + 0.5*det_LeigenD - (2*0.5)*L12 - 0.5*L12D;
L1 = 0.5*L11 + 0.5*det_Leigen - 0.5*L12;
MatrixXd Q_f_f = K_f_u*K_u_u_u_f;
for(int i = 0; i < nb_gp_nodes; i++){
Q_f_f(i,i) += d->Lambda(i) + d->Qff_opt_nugget;
}
LLT<MatrixXd> LLTofQ_f_f(Q_f_f);
double L2 = 0.5*d->scaled_function_values_eigen.dot(LLTofQ_f_f.solve(d->scaled_function_values_eigen));
//std::cout << d->scaled_function_values_eigen << std::endl;
double result = L1 + L2;
if (std::isinf(result) || std::isnan(result)){
std::cout << "Result is inf or nan" << std::endl;
std::cout << "L11 " << L11 << " " << 'x' << std::endl;
std::cout << "L12 " << L12 << std::endl; //<< " " << log(d->K_u_u.determinant()) << std::endl;
std::cout << "L13 " << det_Leigen << std::endl;// << " " << log(Sigma.determinant()) << std::endl;
std::cout << L1 << ' ' << L2 << std::endl;
result = std::numeric_limits<double>::infinity();
if(d->Kuu_opt_nugget < d->nugget_max){
d->Kuu_opt_nugget *= 10;
d->Lambda_opt_nugget *= 10;
d->Qff_opt_nugget *= 10;
}
}else{
if(d->Kuu_opt_nugget > d->nugget_min){
d->Kuu_opt_nugget *= 0.1;
d->Lambda_opt_nugget *= 0.1;
d->Qff_opt_nugget *= 0.1;
}
}
if ((d->print%1000)==0){
/*for ( int i = 0; i < d->dim + 1; ++i )
std::cout << "gp_param = " << x[i] << std::endl;
for(int j = offset; j < offset + d->u.rows(); ++j)
std::cout << "gp_param = " << x[j] <<","<<x[j+ d->u.rows()]<< std::endl;*/
//std::cout << d->print <<" Objective: " << L1 << " " << L2 << " "<< result<< std::endl;
}
d->print++;
return result;
}
double SubsetOfRegressors::parameter_estimation_objective_w_gradients(std::vector<double> const &x,
std::vector<double> &grad,
void *data)
{
//std::cout << "in sor2" << std::endl;
SubsetOfRegressors *d = reinterpret_cast<SubsetOfRegressors*>(data);
int offset;
std::vector<double> local_params(d->dim+1);
if(x.size()==1+d->dim){
offset = 0;
for(int i = 0; i < local_params.size(); ++i){
local_params[i] = x[i];
}
}else{
if(x.size() > d->u.rows()*d->dim){
offset = 1+d->dim;
for(int i = 0; i < local_params.size(); ++i){
local_params[i] = x[i];
}
}else{
offset = 0;
for(int i = 0; i < local_params.size(); ++i){
local_params[i] = d->gp_parameters[i];
}
}
int u_counter;
for (int i = 0; i < d->dim; ++i) {
u_counter = 0;
for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){
d->u(u_counter,i) = x[j];
u_counter++;
}
}
}
//Compute Kuf, Kuu
//Set up matrix K_u_f and K_f_u
int nb_gp_nodes = d->gp_nodes.size();
int nb_u_nodes = d->u.rows();
d->K_u_f.resize(nb_u_nodes, nb_gp_nodes);
for (int i = 0; i < nb_u_nodes; ++i) {
for (int j = 0; j < nb_gp_nodes; ++j) {
d->K_u_f(i,j) = d->evaluate_kernel(d->u.row(i), d->gp_nodes_eigen.row(j), local_params);
}
}
MatrixXd K_f_u = d->K_u_f.transpose();
//std::cout << "Kuf\n" << d->K_u_f << std::endl;
//Set up matrix K_u_u
d->K_u_u.resize(nb_u_nodes, nb_u_nodes);
for (int i = 0; i < nb_u_nodes; ++i) {
for (int j = 0; j < nb_u_nodes; ++j) {
d->K_u_u(i,j) = d->evaluate_kernel(d->u.row(i), d->u.row(j), local_params);
if(i==j)
d->K_u_u(i,j) += d->Kuu_opt_nugget;
}
}
//std::cout << "Kuu\n" << d->K_u_u << std::endl;
d->LLTofK_u_u.compute(d->K_u_u);
MatrixXd K_u_u_u_f = d->LLTofK_u_u.solve(d->K_u_f);
VectorXd diag_Q_f_f;
diag_Q_f_f.resize(nb_gp_nodes);
for (int i = 0; i < nb_gp_nodes; ++i) {
diag_Q_f_f(i) = 0.0;
for (int j = 0; j < nb_u_nodes; ++j) {
diag_Q_f_f(i) += (K_f_u(i,j) * K_u_u_u_f(j,i));
}
}
VectorXd diag_K_f_f;
diag_K_f_f.resize(nb_gp_nodes);
for (int i = 0; i < nb_gp_nodes; ++i) {
diag_K_f_f(i) = d->evaluate_kernel(d->gp_nodes_eigen.row(i),
d->gp_nodes_eigen.row(i), local_params);
}
/*std::cout << "diag_K_f_f\n" << diag_K_f_f << std::endl;
std::cout << "diag_Q_f_f\n" << diag_Q_f_f << std::endl;*/
d->Lambda.resize(nb_gp_nodes);
//std::cout << "noise\n" << std::endl;
for (int i = 0; i < nb_gp_nodes; ++i) {
d->Lambda(i) = (pow( d->gp_noise.at(i) / 2e0 + d->noise_regularization, 2e0 ));
}
//std::cout << std::endl;
MatrixXd Lambda_K_f_u;
Lambda_K_f_u.resize(nb_gp_nodes, nb_u_nodes);
for(int i = 0; i < nb_gp_nodes; i++){
for(int j = 0; j < nb_u_nodes; j++){
Lambda_K_f_u(i,j) = ((1.0/(d->Lambda(i) + d->Lambda_opt_nugget)) * K_f_u(i,j));
}
}
MatrixXd K_u_f_Lambda_f_u;
K_u_f_Lambda_f_u.resize(nb_u_nodes, nb_u_nodes);
K_u_f_Lambda_f_u = d->K_u_f*Lambda_K_f_u;
MatrixXd Sigma = d->K_u_u + K_u_f_Lambda_f_u;
for (int i = 0; i < nb_u_nodes; ++i) {
//Sigma(i,i) += nugget;
}
d->L_eigen.compute(Sigma);
double L12 = 0.0;//-log(d->K_u_u.determinant());
for (int i = 0; i < d->u.rows(); ++i){
L12 += log(d->LLTofK_u_u.vectorD()(i));
//std::cout << L1 << "L11-" << i << std::endl;
}
double det_Leigen = 0.0;
for (int i = 0; i < d->u.rows(); ++i){
det_Leigen += log(d->L_eigen.vectorD()(i));
//std::cout << d->L_eigen.matrixL()(i,i) << " " << log(d->L_eigen.matrixL()(i,i)) << "det_Leigen-" << i << std::endl;
}
double L11 = 0.0;
//std::cout << L1 << "L12 " << std::endl;
for (int i = 0; i < d->nb_gp_nodes; ++i){
L11 += log(d->Lambda(i));
//std::cout << "Lambda: " << i << " " << d->Lambda(i) <<" "<<log(d->Lambda(i)) << std::endl;
}
double L1 = 0.0;
//L1 = 0.5*L11 + (2*0.5)*det_Leigen + 0.5*det_LeigenD - (2*0.5)*L12 - 0.5*L12D;
L1 = 0.5*L11 + 0.5*det_Leigen - 0.5*L12;
MatrixXd Q_f_f = K_f_u*K_u_u_u_f;
for(int i = 0; i < nb_gp_nodes; i++){
Q_f_f(i,i) += d->Lambda(i) + d->Qff_opt_nugget;
}
LLT<MatrixXd> LLTofQ_f_f(Q_f_f);
double L2 = 0.5*d->scaled_function_values_eigen.dot(LLTofQ_f_f.solve(d->scaled_function_values_eigen));
//std::cout << d->scaled_function_values_eigen << std::endl;
double result = L1 + L2;
if (std::isinf(result) || std::isnan(result)){
std::cout << "Result is inf or nan" << std::endl;
std::cout << "L11 " << L11 << " " << 'x' << std::endl;
std::cout << "L12 " << L12 << std::endl; //<< " " << log(d->K_u_u.determinant()) << std::endl;
std::cout << "L13 " << det_Leigen << std::endl;// << " " << log(Sigma.determinant()) << std::endl;
std::cout << L1 << ' ' << L2 << std::endl;
result = std::numeric_limits<double>::infinity();
if(d->Kuu_opt_nugget < d->nugget_max){
d->Kuu_opt_nugget *= 10;
d->Lambda_opt_nugget *= 10;
d->Qff_opt_nugget *= 10;
}
}else{
if(d->Kuu_opt_nugget > d->nugget_min){
d->Kuu_opt_nugget *= 0.1;
d->Lambda_opt_nugget *= 0.1;
d->Qff_opt_nugget *= 0.1;
}
}
if ((d->print%1000)==0){
/*for ( int i = 0; i < d->dim + 1; ++i )
std::cout << "gp_param = " << x[i] << std::endl;
for(int j = offset; j < offset + d->u.rows(); ++j)
std::cout << "gp_param = " << x[j] <<","<<x[j+ d->u.rows()]<< std::endl;*/
//std::cout << d->print <<" Objective: " << L1 << " " << L2 << " "<< result<< std::endl;
}
//Gradient computation:
int dim_grad = x.size();
grad.resize(dim_grad);
for(int i = 0; i < grad.size(); i++){
MatrixXd Kffdot;
MatrixXd Kufdot;
MatrixXd Kfudot;
MatrixXd Kuudot;
VectorXd LambdaDot;
if(dim_grad == d->dim + 1){
if(i == 0){//grad sigma_f
d->derivate_K_u_u_wrt_sigmaf(local_params, Kuudot);
d->derivate_K_f_f_wrt_sigmaf(local_params, Kffdot);
d->derivate_K_u_f_wrt_sigmaf(local_params, Kufdot);
Kfudot = Kufdot.transpose();
}else{//grad length parameter
d->derivate_K_u_u_wrt_l(local_params, i-1, Kuudot);
d->derivate_K_f_f_wrt_l(local_params, i-1, Kffdot);
d->derivate_K_u_f_wrt_l(local_params, i-1, Kufdot);
Kfudot = Kufdot.transpose();
}
}else{
if( dim_grad > d->u.rows()*d->dim){//if we optimize also for sigma_f and lengthscales
if(i == 0){//grad sigma_f
d->derivate_K_u_u_wrt_sigmaf(local_params, Kuudot);
d->derivate_K_f_f_wrt_sigmaf(local_params, Kffdot);
d->derivate_K_u_f_wrt_sigmaf(local_params, Kufdot);
Kfudot = Kufdot.transpose();
}else if(i > 0 && i < 1 + d->dim){//grad length parameter
d->derivate_K_u_u_wrt_l(local_params, i-1, Kuudot);
d->derivate_K_f_f_wrt_l(local_params, i-1, Kffdot);
d->derivate_K_u_f_wrt_l(local_params, i-1, Kufdot);
Kfudot = Kufdot.transpose();
}else{//grad u
int uidx = (i-offset)%d->u.rows();
int udim = (int) ((i-offset)/d->u.rows());
d->derivate_K_u_u_wrt_uik(local_params, uidx, udim, Kuudot);
d->derivate_K_u_f_wrt_uik(local_params, uidx, udim, Kufdot);
Kffdot.resize(nb_gp_nodes, nb_gp_nodes);
Kffdot.setZero();
Kfudot = Kufdot.transpose();
}
}else{
int uidx = (i-offset)%d->u.rows();
int udim = (int) ((i-offset)/d->u.rows());
d->derivate_K_u_u_wrt_uik(local_params, uidx, udim, Kuudot);
d->derivate_K_u_f_wrt_uik(local_params, uidx, udim, Kufdot);
Kffdot.resize(nb_gp_nodes, nb_gp_nodes);
Kffdot.setZero();
Kfudot = Kufdot.transpose();
}
}
VectorXd LambdaInv(nb_gp_nodes);
for(int j = 0; j < nb_gp_nodes; ++j){
LambdaInv(j) = 1.0/d->Lambda(j);
}
/*
IOFormat HeavyFmt(FullPrecision, 0, ", ", ";\n", "", "", "[", "]");
std::cout << "Kuudot\n" << Kuudot.format(HeavyFmt) << std::endl;
std::cout << "Kffdot\n" << Kffdot.format(HeavyFmt) << std::endl;
std::cout << "Kufdot\n" << Kufdot.format(HeavyFmt) << std::endl;
std::cout << "Kuu\n" << d->K_u_u.format(HeavyFmt) << std::endl;
std::cout << "Kuf\n" << d->K_u_f.format(HeavyFmt) << std::endl;
std::cout << "Qff\n" << Q_f_f.format(HeavyFmt) << std::endl;
std::cout << "noise:\n" << std::endl;
for (int i = 0; i < nb_gp_nodes; ++i) {
std::cout << (pow( d->gp_noise.at(i) / 2e0 + d->noise_regularization, 2e0 )) << std::endl;
}
std::cout << std::endl;
std::cout << "y:\n" << d->scaled_function_values_eigen << std::endl;
*/
//L1-term: dL1/dtheta= tr(Kuu^(-1) * Kuudot)
double dL1 = (d->LLTofK_u_u.solve(Kuudot)).trace();
//L2-term: d(log(det(Kuu+Kuf*(noise^2)^(-1)*Kfu)))/dtheta
MatrixXd LambdaInvDiag = LambdaInv.asDiagonal();
MatrixXd dSigma = Kuudot
+ 2*Kufdot*LambdaInvDiag*K_f_u;
//+ d->K_u_f*LambdaInvDiag*Kfudot;
//std::cout << "LambdaInv:\n" << LambdaInv.format(HeavyFmt) << std::endl;
//std::cout << "LambdaInvDiag:\n" << LambdaInvDiag.format(HeavyFmt) << std::endl;
//std::cout << "dSigma:\n" << dSigma.format(HeavyFmt) << std::endl;
double dL2 = (d->L_eigen.solve(dSigma)).trace();
//L3-term: d(yT*Q*y)/dtheta
MatrixXd KfudotKuinvKuf = Kfudot * d->LLTofK_u_u.solve(d->K_u_f);
MatrixXd KfuKuinvKufdot = K_f_u * d->LLTofK_u_u.solve(Kufdot);
MatrixXd KfuKuinfKudotKuinvKuf = K_f_u*(d->LLTofK_u_u.solve(Kuudot*(d->LLTofK_u_u.solve(d->K_u_f))));
MatrixXd dQ = KfudotKuinvKuf - KfuKuinfKudotKuinvKuf + KfuKuinvKufdot;
//std::cout << "dQ:\n" << dQ.format(HeavyFmt) << std::endl;
double dL3 = (-1)*d->scaled_function_values_eigen.dot(
LLTofQ_f_f.solve(dQ*LLTofQ_f_f.solve(
d->scaled_function_values_eigen)));
grad[i] = 0.5*(-dL1 + dL2 + dL3);
if ((d->print%1)==0){
//std::cout << "Grad: " << i << "|" << 0.5*dL1 << " + "<< 0.5*dL2 << " + "<< 0.5*dL3 << " = " << grad[i] << std::endl;
}
//exit(-1);
}
d->print++;
return result;
}
void SubsetOfRegressors::trust_region_constraint(unsigned int m, double* c, unsigned int n, const double* x, double* grad,
void *data){
SubsetOfRegressors *d = reinterpret_cast<SubsetOfRegressors*>(data);
int offset;
if(m == d->dim + 1){
for (int i = 0; i < d->dim+1; ++i) {
c[i] = -1;
}
}else{
if(m > d->u.rows()*d->dim){
offset = 1+d->dim;
}else{
offset = 0;
}
int u_counter;
for (int i = 0; i < offset; ++i) {
c[i] = -1;
}
MatrixXd u_intern(d->u.rows(), d->u.cols());
for (int i = 0; i < d->dim; ++i) {
u_counter = 0;
for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){
u_intern(u_counter, i) = x[j];
u_counter++;
}
}
VectorXd c_intern(u_intern.rows());
VectorXd dist(d->dim);
for (int i = 0; i < u_intern.rows(); ++i) {
for (int j = 0; j < d->dim; ++j) {
dist(j) = (u_intern(i, j)-d->constraint_ball_center(j));
}
c_intern(i) = sqrt( dist.dot(dist) ) - d->constraint_ball_radius;
}
for (int i = 0; i < d->dim; ++i) {
u_counter = 0;
for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){
c[j] = c_intern(u_counter);
u_counter++;
}
}
}
return;
} | 32.152231 | 122 | 0.578735 | [
"vector"
] |
fa97abff3a754015bd73371728abad56bb9ee912 | 4,386 | cc | C++ | tensorflow/core/user_ops/direct_sparse_to_dense.cc | TimoHackel/ILA-SCNN | 99ff4b3f68877d660dc56e086b6a12d6846b379a | [
"Apache-2.0"
] | 24 | 2018-02-01T15:49:22.000Z | 2021-01-11T16:31:18.000Z | tensorflow/core/user_ops/direct_sparse_to_dense.cc | TimoHackel/ILA-SCNN | 99ff4b3f68877d660dc56e086b6a12d6846b379a | [
"Apache-2.0"
] | null | null | null | tensorflow/core/user_ops/direct_sparse_to_dense.cc | TimoHackel/ILA-SCNN | 99ff4b3f68877d660dc56e086b6a12d6846b379a | [
"Apache-2.0"
] | 4 | 2018-10-29T18:43:22.000Z | 2020-09-28T07:19:52.000Z | #include <omp.h>
#include <map>
#include <sstream>
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/common_shape_fns.h"
#if GOOGLE_CUDA
#include "direct_sparse_to_dense_gpu.h"
#endif //GOOGLE_CUDA
/** DirectSparseConvKD
* \ingroup CXX11_NeuralNetworks_Module
*
* \brief Applies a 3D convolution over a multichannel input voxel block.
*
* The input parameter is expected to be a tensor with a rank of 4 or more (channels, depth, height, width, and optionally others).
* The kernel parameter is expected to be a 5D tensor (filters, channels, kernel_depth, kernel_height, kernel_width).
*
* The result can be assigned to a tensor of rank equal to the rank of the input. The dimensions of the result will be filters, depth, height, width (and others if applicable).
*/
REGISTER_OP("DirectSparseToDense")
.Attr("T: realnumbertype")
.Attr("Tindices: {int32, int64}")
.Input("in_indices: Tindices")
.Input("in_values: T")
.Input("in_shape: Tindices")
.Input("in_block_channel_mapping: int32")
.Output("out_values: T")
.Attr("dim: int = 5");
REGISTER_OP("DirectSparseToDenseBackprop")
.Attr("T: realnumbertype")
.Attr("Tindices: {int32, int64}")
.Input("in_indices: Tindices")
.Input("in_values: T")
.Input("in_shape: Tindices")
.Input("in_block_channel_mapping: int32")
.Input("out_values: T")
.Input("grads: T")
.Output("backprops: T")
.Attr("dim: int = 5");
REGISTER_OP("DirectDenseToSparse")
.Attr("T: realnumbertype")
.Attr("Tindices: {int32, int64}")
.Input("in_values: T")
.Input("in_shape: Tindices") //dummy to define type of Tindices
.Output("out_indices: Tindices")
.Output("out_values: T")
.Output("out_shape: Tindices")
.Output("out_block_channel_mapping: int32")
.Attr("dim: int = 5");
REGISTER_OP("DirectDenseToSparseBackprop")
.Attr("T: realnumbertype")
.Attr("Tindices: {int32, int64}")
.Input("in_values: T")
.Input("out_indices: Tindices")
.Input("out_values: T")
.Input("out_shape: Tindices")
.Input("out_block_channel_mapping: int32")
.Input("grads: T")
.Output("backprops: T")
.Attr("dim: int = 5");
#include "tensorflow/core/framework/op_kernel.h"
typedef Eigen::ThreadPoolDevice CPUDevice;
using namespace tensorflow;
template <typename DeviceT, typename T, typename Tindices, template<typename, typename, typename, int> class FunctorT>
class DirectSparseToDense : public OpKernel {
public:
explicit DirectSparseToDense(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("dim", &dim));
}
void Compute(OpKernelContext* context) override {
//functor requires kernel context since output shape is not known befor computing results
if(dim == 5){
FunctorT<DeviceT, T, Tindices, 5>()(context);
} //TODO: add more dimensions
}
private:
int32 dim;
};
#if GOOGLE_CUDA
#define REGISTER_GPU_TYPE(type, indice_type) \
REGISTER_KERNEL_BUILDER(Name("DirectSparseToDense").Device(DEVICE_GPU).TypeConstraint<type>("T").TypeConstraint<indice_type>("Tindices"), \
DirectSparseToDense<GPUDevice, type, indice_type, functor::DirectSparseToDenseFunctor>); \
REGISTER_KERNEL_BUILDER(Name("DirectSparseToDenseBackprop").Device(DEVICE_GPU).TypeConstraint<type>("T").TypeConstraint<indice_type>("Tindices"), \
DirectSparseToDense<GPUDevice, type, indice_type, functor::DirectSparseToDenseBackpropFunctor>); \
REGISTER_KERNEL_BUILDER(Name("DirectDenseToSparse").Device(DEVICE_GPU).TypeConstraint<type>("T").TypeConstraint<indice_type>("Tindices"), \
DirectSparseToDense<GPUDevice, type, indice_type, functor::DirectDenseToSparseFunctor>); \
REGISTER_KERNEL_BUILDER(Name("DirectDenseToSparseBackprop").Device(DEVICE_GPU).TypeConstraint<type>("T").TypeConstraint<indice_type>("Tindices"), \
DirectSparseToDense<GPUDevice, type, indice_type, functor::DirectDenseToSparseBackpropFunctor>);
#define REGISTER_GPU_ALL(type) \
REGISTER_GPU_TYPE(type, int64); \
REGISTER_GPU_TYPE(type, int32);
REGISTER_GPU_ALL(float);
//REGISTER_GPU_ALL(double);
//REGISTER_GPU_ALL(int32);
//REGISTER_GPU_ALL(complex64);
//REGISTER_GPU_ALL(complex128);
#undef REGISTER_GPU_TYPE
#undef REGISTER_GPU_ALL
#endif //GOOGLE_CUDA
| 37.487179 | 177 | 0.727314 | [
"shape",
"3d"
] |
b703216a0be311e60b754497dfa1bf16660203b2 | 4,215 | cpp | C++ | test/vec/opr/num.cpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | 1 | 2017-03-14T20:45:54.000Z | 2017-03-14T20:45:54.000Z | test/vec/opr/num.cpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | 1 | 2017-03-08T17:14:03.000Z | 2017-03-08T23:40:35.000Z | test/vec/opr/num.cpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include <mmm.hpp>
using namespace mmm;
TEST_CASE("vector numeric operator +", "[vec][num]") {
SECTION("vec2") {
vec2 v = vec2(1, 2);
vec2 u = vec2(3, 4);
REQUIRE(1 + v == vec2(2, 3));
REQUIRE(v + 1 == vec2(2, 3));
REQUIRE(v + u == vec2(4, 6));
REQUIRE(v.x + u == vec2(4, 5));
REQUIRE(u + v.x == vec2(4, 5));
REQUIRE(v.xy + u.xy == vec2(4, 6));
}
SECTION("vec3") {
vec3 v = vec3(1, 2, 3);
vec3 u = vec3(4, 5, 6);
REQUIRE(1 + v == vec3(2, 3, 4));
REQUIRE(v + 1 == vec3(2, 3, 4));
REQUIRE(v + u == vec3(5, 7, 9));
REQUIRE(v.x + u == vec3(5, 6, 7));
REQUIRE(u + v.x == vec3(5, 6, 7));
REQUIRE(v.xyz + u.xyz == vec3(5, 7, 9));
}
SECTION("vec4") {
vec4 v = vec4(1, 2, 3, 4);
vec4 u = vec4(5, 6, 7, 8);
REQUIRE(1 + v == vec4(2, 3, 4, 5));
REQUIRE(v + 1 == vec4(2, 3, 4, 5));
REQUIRE(v + u == vec4(6, 8, 10, 12));
REQUIRE(v.x + u == vec4(6, 7, 8, 9));
REQUIRE(u + v.x == vec4(6, 7, 8, 9));
REQUIRE(v.xyzw + u.xyzw == vec4(6, 8, 10, 12));
}
}
TEST_CASE("vector numeric operator -", "[vec][num]") {
SECTION("vec2") {
vec2 v = vec2(1, 2);
vec2 u = vec2(3, 4);
REQUIRE(1 - v == vec2(0, -1));
REQUIRE(v - 1 == vec2(0, 1));
REQUIRE(v - u == vec2(-2, -2));
REQUIRE(v.x - u == vec2(-2, -3));
REQUIRE(u - v.x == vec2(2, 3));
REQUIRE(v.xy - u.xy == vec2(-2, -2));
}
SECTION("vec3") {
vec3 v = vec3(1, 2, 3);
vec3 u = vec3(4, 5, 6);
REQUIRE(1 - v == vec3(0, -1, -2));
REQUIRE(v - 1 == vec3(0, 1, 2));
REQUIRE(v - u == vec3(-3, -3, -3));
REQUIRE(v.x - u == vec3(-3, -4, -5));
REQUIRE(u - v.x == vec3(3, 4, 5));
REQUIRE(v.xyz - u.xyz == vec3(-3, -3, -3));
}
SECTION("vec4") {
vec4 v = vec4(1, 2, 3, 4);
vec4 u = vec4(5, 6, 7, 8);
REQUIRE(1 - v == vec4(0, -1, -2, -3));
REQUIRE(v - 1 == vec4(0, 1, 2, 3));
REQUIRE(v - u == vec4(-4, -4, -4, -4));
REQUIRE(v.x - u == vec4(-4, -5, -6, -7));
REQUIRE(u - v.x == vec4(4, 5, 6, 7));
REQUIRE(v.xyzw - u.xyzw == vec4(-4, -4, -4, -4));
}
}
TEST_CASE("vector numeric operator *", "[vec][num]") {
SECTION("vec2") {
vec2 v = vec2(1, 2);
vec2 u = vec2(3, 4);
REQUIRE(1 * v == vec2(1, 2));
REQUIRE(v * 1 == vec2(1, 2));
REQUIRE(v * u == vec2(3, 8));
REQUIRE(v.x * u == vec2(3, 4));
REQUIRE(u * v.x == vec2(3, 4));
REQUIRE(v.xy * u.xy == vec2(3, 8));
}
SECTION("vec3") {
vec3 v = vec3(1, 2, 3);
vec3 u = vec3(4, 5, 6);
REQUIRE(1 * v == vec3(1, 2, 3));
REQUIRE(v * 1 == vec3(1, 2, 3));
REQUIRE(v * u == vec3(4, 10, 18));
REQUIRE(v.x * u == vec3(4, 5, 6));
REQUIRE(u * v.x == vec3(4, 5, 6));
REQUIRE(v.xyz * u.xyz == vec3(4, 10, 18));
}
SECTION("vec4") {
vec4 v = vec4(1, 2, 3, 4);
vec4 u = vec4(5, 6, 7, 8);
REQUIRE(1 * v == vec4(1, 2, 3, 4));
REQUIRE(v * 1 == vec4(1, 2, 3, 4));
REQUIRE(v * u == vec4(5, 12, 21, 32));
REQUIRE(v.x * u == vec4(5, 6, 7, 8));
REQUIRE(u * v.x == vec4(5, 6, 7, 8));
REQUIRE(v.xyzw * u.xyzw == vec4(5, 12, 21, 32));
}
}
TEST_CASE("vector numeric operator /", "[vec][num]") {
SECTION("vec2") {
vec2 v = vec2(1, 2);
vec2 u = vec2(2, 4);
REQUIRE(1 / v == vec2(1, 0.5));
REQUIRE(v / 1 == vec2(1, 2));
REQUIRE(v / u == vec2(0.5, 0.5));
REQUIRE(v.x / u == vec2(0.5, 0.25));
REQUIRE(u / v.x == vec2(2, 4));
REQUIRE(v.xy / u.xy == vec2(0.5, 0.5));
}
SECTION("vec3") {
vec3 v = vec3(1, 2, 4);
vec3 u = vec3(2, 4, 8);
REQUIRE(1 / v == vec3(1, 0.5, 0.25));
REQUIRE(v / 1 == vec3(1, 2, 4));
REQUIRE(v / u == vec3(0.5, 0.5, 0.5));
REQUIRE(v.x / u == vec3(0.5, 0.25, 0.125));
REQUIRE(u / v.x == vec3(2, 4, 8));
REQUIRE(v.xyz / u.xyz == vec3(0.5, 0.5, 0.5));
}
SECTION("vec4") {
vec4 v = vec4(1, 2, 4, 8);
vec4 u = vec4(2, 4, 8, 16);
REQUIRE(1 / v == vec4(1, 0.5, 0.25, 0.125));
REQUIRE(v / 1 == vec4(1, 2, 4, 8));
REQUIRE(v / u == vec4(0.5, 0.5, 0.5, 0.5));
REQUIRE(v.x / u == vec4(0.5, 0.25, 0.125, 0.0625));
REQUIRE(u / v.x == vec4(2, 4, 8, 16));
REQUIRE(v.xyzw / u.xyzw == vec4(0.5, 0.5, 0.5, 0.5));
}
}
| 26.180124 | 57 | 0.455516 | [
"vector"
] |
b718f79f51257d42f3e163c01c5cc05352af3605 | 14,078 | cpp | C++ | src/glfw_window.cpp | jfcameron/simple-glfw | 311a5732a147b270ceb6024b21ef103a2f9a17fc | [
"MIT"
] | null | null | null | src/glfw_window.cpp | jfcameron/simple-glfw | 311a5732a147b270ceb6024b21ef103a2f9a17fc | [
"MIT"
] | 11 | 2019-11-29T15:33:33.000Z | 2020-10-05T15:38:50.000Z | src/glfw_window.cpp | jfcameron/simple-glfw | 311a5732a147b270ceb6024b21ef103a2f9a17fc | [
"MIT"
] | null | null | null | // © 2018-2019 Joseph Cameron - All Rights Reserved
#include <simpleglfw/buildinfo.h>
#include <jfc/glfw_window.h>
#ifdef JFC_TARGET_PLATFORM_Emscripten
#include <emscripten/bind.h>
#include <emscripten/emscripten.h>
#define GLFW_INCLUDE_ES2
#elif defined JFC_TARGET_PLATFORM_Linux || defined JFC_TARGET_PLATFORM_Windows
#define GLEW_STATIC
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
#include <exception>
#include <functional>
#include <iostream>
#include <mutex>
#include <sstream>
static constexpr char TAG[] = "glfw_window";
//! 16x16 RGBA32 Image of a gauntlet
static const unsigned char cursor_contrast_data[] = {
0x24, 0x26, 0x2b, 0xff, 0x3b, 0x3f, 0x47, 0xff, 0x18, 0x1b, 0x1b, 0x40,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x3a, 0x3c, 0x3c, 0x6d,
0x1b, 0x1e, 0x1e, 0x80, 0x1f, 0x23, 0x23, 0x3a, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00,
0xff, 0xff, 0xff, 0x00, 0x1d, 0x1f, 0x20, 0xd4, 0x65, 0x74, 0x82, 0xff,
0x46, 0x4c, 0x51, 0xff, 0x1c, 0x20, 0x20, 0xf4, 0x28, 0x2a, 0x2d, 0xf7,
0x44, 0x4a, 0x51, 0xff, 0x34, 0x3b, 0x42, 0xff, 0x23, 0x27, 0x2a, 0xf8,
0x2f, 0x33, 0x3a, 0x33, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00, 0x35, 0x3a, 0x40, 0x2b,
0x30, 0x38, 0x40, 0xff, 0x9b, 0xa2, 0xa9, 0xff, 0x42, 0x4b, 0x57, 0xff,
0x65, 0x6c, 0x73, 0xff, 0x49, 0x4b, 0x50, 0xff, 0x5d, 0x66, 0x6d, 0xff,
0x30, 0x39, 0x40, 0xff, 0x1c, 0x1f, 0x22, 0xff, 0x2e, 0x32, 0x3b, 0x47,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00,
0x11, 0x11, 0x11, 0x00, 0x1b, 0x1b, 0x1e, 0x7d, 0x4d, 0x55, 0x5a, 0xff,
0xa0, 0xa6, 0xac, 0xff, 0x35, 0x3e, 0x47, 0xff, 0x92, 0x97, 0x9c, 0xff,
0x89, 0x8d, 0x90, 0xff, 0x91, 0x9e, 0xa7, 0xff, 0x47, 0x53, 0x5f, 0xff,
0x1e, 0x21, 0x23, 0xcb, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00,
0xff, 0xff, 0xff, 0x00, 0x5a, 0x5a, 0x5a, 0x00, 0x5e, 0x63, 0x6a, 0x80,
0x36, 0x3f, 0x46, 0xff, 0x51, 0x5b, 0x68, 0xff, 0xbf, 0xc1, 0xc3, 0xff,
0xc2, 0xc7, 0xcc, 0xff, 0x7a, 0x86, 0x96, 0xff, 0x34, 0x3c, 0x44, 0xff,
0x19, 0x1c, 0x1c, 0xff, 0x12, 0x12, 0x12, 0xff, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00, 0x7c, 0x7c, 0x7c, 0x00,
0x3f, 0x48, 0x4c, 0xff, 0x29, 0x2f, 0x35, 0xff, 0x4c, 0x56, 0x60, 0xff,
0x65, 0x72, 0x7e, 0xff, 0xc0, 0xc6, 0xcb, 0xff, 0xc7, 0xca, 0xcc, 0xff,
0x67, 0x6f, 0x7a, 0xff, 0x24, 0x28, 0x2a, 0xff, 0x16, 0x18, 0x1a, 0xff,
0x24, 0x28, 0x2d, 0x40, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00,
0x7c, 0x7c, 0x7c, 0x00, 0x3c, 0x46, 0x4c, 0xff, 0x1a, 0x1d, 0x1f, 0xff,
0x47, 0x4e, 0x55, 0xff, 0x4d, 0x58, 0x61, 0xff, 0xa5, 0xad, 0xb5, 0xff,
0xcc, 0xce, 0xce, 0xff, 0x83, 0x8c, 0x99, 0xff, 0x2b, 0x32, 0x38, 0xff,
0x33, 0x3b, 0x42, 0xff, 0x3b, 0x41, 0x49, 0xb0, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00,
0xff, 0xff, 0xff, 0x00, 0x7c, 0x7c, 0x7c, 0x00, 0x38, 0x42, 0x4b, 0xff,
0x4e, 0x57, 0x60, 0xff, 0x16, 0x16, 0x18, 0xff, 0x7b, 0x83, 0x8b, 0xff,
0x6b, 0x78, 0x85, 0xff, 0xcc, 0xce, 0xcf, 0xff, 0x9a, 0xa1, 0xa5, 0xff,
0x2e, 0x34, 0x39, 0xff, 0x2f, 0x37, 0x3a, 0xff, 0x38, 0x3f, 0x44, 0xff,
0x22, 0x22, 0x24, 0x40, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00, 0x11, 0x11, 0x11, 0x00,
0x13, 0x13, 0x14, 0x47, 0x23, 0x28, 0x2a, 0xff, 0x24, 0x2a, 0x2d, 0xff,
0x82, 0x89, 0x8e, 0xff, 0x47, 0x52, 0x5d, 0xff, 0x92, 0x9c, 0xa6, 0xff,
0xa1, 0xa5, 0xab, 0xff, 0x6b, 0x70, 0x74, 0xff, 0x5d, 0x6f, 0x7b, 0xff,
0x80, 0x8b, 0x99, 0xff, 0x40, 0x49, 0x54, 0xff, 0x28, 0x28, 0x31, 0x40,
0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x1f, 0x22, 0x25, 0x49,
0x20, 0x25, 0x27, 0xff, 0x54, 0x5e, 0x67, 0xff, 0x39, 0x42, 0x4c, 0xff,
0x4b, 0x55, 0x61, 0xff, 0x9f, 0xa3, 0xa7, 0xff, 0x94, 0x97, 0x9a, 0xff,
0x58, 0x60, 0x69, 0xff, 0x64, 0x75, 0x7e, 0xff, 0x72, 0x7d, 0x89, 0xff,
0x28, 0x2f, 0x3e, 0xff, 0x1d, 0x20, 0x20, 0x40, 0xbc, 0xbc, 0xbc, 0x00,
0xff, 0xff, 0xff, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x49, 0x28, 0x2e, 0x36, 0xff,
0x29, 0x2c, 0x31, 0xff, 0x7e, 0x8a, 0x95, 0xff, 0xb5, 0xb8, 0xbb, 0xff,
0xae, 0xb2, 0xb2, 0xff, 0x66, 0x6f, 0x78, 0xff, 0x30, 0x38, 0x40, 0xff,
0x51, 0x61, 0x68, 0xff, 0x41, 0x4e, 0x57, 0xff, 0x1d, 0x22, 0x24, 0xff,
0x1d, 0x20, 0x21, 0x57, 0xff, 0xff, 0xff, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x47, 0x3f, 0x48, 0x50, 0xff, 0x44, 0x52, 0x5f, 0xff,
0xaf, 0xb3, 0xb8, 0xff, 0xb2, 0xb6, 0xb8, 0xff, 0xa0, 0xa2, 0xa4, 0xff,
0x46, 0x4e, 0x57, 0xff, 0x2c, 0x34, 0x39, 0xff, 0x29, 0x32, 0x37, 0xff,
0x19, 0x1b, 0x1e, 0xff, 0x11, 0x11, 0x11, 0x80, 0xff, 0xff, 0xff, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x1e, 0x20, 0x21, 0xbf,
0x23, 0x25, 0x28, 0xff, 0x74, 0x7d, 0x85, 0xff, 0xa5, 0xa9, 0xac, 0xff,
0x61, 0x66, 0x6a, 0xff, 0x16, 0x16, 0x18, 0xff, 0x1a, 0x1b, 0x1c, 0xff,
0x21, 0x24, 0x25, 0xff, 0x1a, 0x1d, 0x1d, 0xff, 0x11, 0x11, 0x11, 0x7e,
0xff, 0xff, 0xff, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x24, 0x28, 0x29, 0x38, 0x1a, 0x1b, 0x1c, 0xff, 0x3c, 0x43, 0x49, 0xff,
0x2d, 0x32, 0x37, 0xff, 0x1d, 0x1f, 0x22, 0xff, 0x21, 0x27, 0x2a, 0xff,
0x24, 0x27, 0x2a, 0xff, 0x20, 0x22, 0x23, 0xff, 0x15, 0x15, 0x18, 0xd3,
0x11, 0x11, 0x11, 0x15, 0xff, 0xff, 0xff, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x19, 0x19, 0x1d, 0xab,
0x22, 0x24, 0x28, 0xff, 0x25, 0x2a, 0x2f, 0xff, 0x32, 0x3e, 0x48, 0xff,
0x38, 0x40, 0x49, 0xff, 0x1e, 0x1f, 0x23, 0xff, 0x13, 0x13, 0x15, 0xaa,
0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00, 0xff, 0xff, 0xff, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00,
0x12, 0x12, 0x14, 0x3b, 0x12, 0x13, 0x13, 0xcb, 0x1d, 0x1f, 0x23, 0xff,
0x22, 0x28, 0x2d, 0xff, 0x14, 0x15, 0x16, 0xd4, 0x1d, 0x1d, 0x22, 0x3e,
0x11, 0x11, 0x11, 0x00, 0x11, 0x11, 0x11, 0x00, 0xbc, 0xbc, 0xbc, 0x00,
0xff, 0xff, 0xff, 0x00
};
using namespace gdk;
glfw_window::glfw_window(const std::string_view aName,
const window_size_type &aScreenSize)
: m_pGLFWWindow([&]()
{
glfwSetErrorCallback([](int, const char *msg)
{
throw std::runtime_error(std::string(TAG).append("/").append(msg));
});
static std::once_flag glfwInitFlag;
std::call_once(glfwInitFlag, []()
{
if (!glfwInit()) throw std::runtime_error(std::string(TAG).append("/glfwInit failed"));
glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
});
if (GLFWwindow *const pWindow = glfwCreateWindow(aScreenSize.first, aScreenSize.second, aName.data(), nullptr, nullptr))
{
glfwMakeContextCurrent(pWindow);
// Vsync controller. if not called, the interval is platform dependent. 0 is off.
// negative values allow for swapping even if the backbuffer arrives late (vendor extension dependent).
glfwSwapInterval(-1);
#if !defined JFC_TARGET_PLATFORM_Emscripten
//! if the mouse is locked, then use unaccellerated mouse input
if (glfwRawMouseMotionSupported()) glfwSetInputMode(pWindow, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
#endif
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(pWindow); //Must be called once to see the buffer we cleared
glfwPollEvents(); //Must be called once for window to render
glfwSetWindowUserPointer(pWindow, static_cast<void *>(this));
glfwSetWindowSizeCallback(pWindow, [](GLFWwindow *const pCurrentGLFWwindow, int aX, int aY)
{
if (auto pCurrentWrapper = static_cast<glfw_window *const>(glfwGetWindowUserPointer(pCurrentGLFWwindow)))
{
pCurrentWrapper->m_WindowSize.first = aX;
pCurrentWrapper->m_WindowSize.second = aY;
}
else throw std::runtime_error(std::string(TAG).append("/wrapper associated with current glfw window instance is null"));
});
glfwSetWindowCloseCallback(pWindow, [](GLFWwindow *const pCurrentWindow)
{
glfwSetWindowShouldClose(pCurrentWindow, GLFW_TRUE);
});
#if defined JFC_TARGET_PLATFORM_Linux || defined JFC_TARGET_PLATFORM_Windows
static std::once_flag glewInitFlag;
std::call_once(glewInitFlag, []()
{
glewExperimental = true; //Required on a Linux (Ubuntu 18.04.1 LTS) x86 32bit system
if (GLenum err = glewInit() != GLEW_OK)
{
std::stringstream ss;
ss << TAG << "/glewinit failed: " << glewGetErrorString(err);
throw std::runtime_error(ss.str());
}
});
#endif
return pWindow;
}
else throw std::runtime_error(std::string(TAG).append("/glfwCreateWindow failed. Can the environment provide a GLES2.0/WebGL1.0 context?"));
}()
,[](GLFWwindow *const ptr)
{
glfwDestroyWindow(ptr);
})
, m_Name(aName)
, m_WindowSize(aScreenSize.first, aScreenSize.second)
{
cursor_image_type image;
for (int i(0); i < (16 * 16 * 4);++i) image[i] = static_cast<std::byte>(cursor_contrast_data[i]);
setCursor(image);
icon_image_type icon;
icon.width_pixels = 16;
icon.height_pixels = 16;
for (int i(0); i < (16 * 16 * 4);++i) icon.data_rgba32.push_back(static_cast<std::byte>(cursor_contrast_data[i]));
setIcons({icon});
}
GLFWwindow *const glfw_window::getPointerToGLFWWindow()
{
return m_pGLFWWindow.get();
}
void glfw_window::swapBuffer()
{
glfwSwapBuffers(m_pGLFWWindow.get());
}
glfw_window::window_size_type glfw_window::getWindowSize() const
{
return m_WindowSize;
}
glfw_window::window_aspect_ratio_type glfw_window::getAspectRatio() const
{
return
static_cast<window_aspect_ratio_type>(m_WindowSize.first) /
static_cast<window_aspect_ratio_type>(m_WindowSize.second)
;
}
glfw_window::cursor_position_type glfw_window::getCursorPos() const
{
double x,y;
glfwGetCursorPos(m_pGLFWWindow.get(), &x, &y);
return cursor_position_type(
static_cast<cursor_position_type::first_type>(x),
static_cast<cursor_position_type::second_type>(y));
}
bool glfw_window::getKey(const int aKeyCode) const
{
return static_cast<bool>(glfwGetKey(m_pGLFWWindow.get(), aKeyCode));
}
std::string_view glfw_window::getName() const
{
return m_Name;
}
bool glfw_window::shouldClose() const
{
return glfwWindowShouldClose(m_pGLFWWindow.get());
}
void glfw_window::close()
{
glfwSetWindowShouldClose(m_pGLFWWindow.get(), true);
}
bool glfw_window::operator==(const glfw_window &a) const
{
return m_pGLFWWindow == a.m_pGLFWWindow;
}
bool glfw_window::operator!=(const glfw_window &a) const
{
return !(*this == a);
}
void glfw_window::setIcons(const icon_image_collection_type &aIconImages)
{
std::vector<GLFWimage> glfwImages;
for (const auto &iconImage : aIconImages)
{
GLFWimage image;
image.width = iconImage.width_pixels;
image.height = iconImage.height_pixels;
image.pixels = const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(&iconImage.data_rgba32[0]));
glfwImages.push_back(std::move(image));
}
glfwSetWindowIcon(m_pGLFWWindow.get(), aIconImages.size(), &glfwImages[0]);
}
void glfw_window::setCursor(const cursor_image_type &aRGBA32PNG)
{
GLFWimage image;
image.width = 16;
image.height = 16;
image.pixels = const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(&aRGBA32PNG[0]));
m_pGLFWCursor = decltype(m_pGLFWCursor)(
glfwCreateCursor(&image, 0, 0),
[](GLFWcursor *p)
{
if (p) glfwDestroyCursor(p);
});
glfwSetCursor(m_pGLFWWindow.get(), m_pGLFWCursor.get());
}
void glfw_window::setCursor(const standard_cursor_graphic cursor)
{
decltype(GLFW_ARROW_CURSOR) glfwStandardCursor;
switch(cursor)
{
case standard_cursor_graphic::arrow: glfwStandardCursor = GLFW_ARROW_CURSOR; break;
case standard_cursor_graphic::ibeam: glfwStandardCursor = GLFW_IBEAM_CURSOR; break;
case standard_cursor_graphic::crosshair: glfwStandardCursor = GLFW_CROSSHAIR_CURSOR; break;
case standard_cursor_graphic::hand: glfwStandardCursor = GLFW_HAND_CURSOR; break;
case standard_cursor_graphic::horizontal_resizer: glfwStandardCursor = GLFW_HRESIZE_CURSOR; break;
case standard_cursor_graphic::vertical_resizer: glfwStandardCursor = GLFW_VRESIZE_CURSOR; break;
default: throw std::invalid_argument("unhandled standard_cursor_graphic type");
}
m_pGLFWCursor = decltype(m_pGLFWCursor)(
glfwCreateStandardCursor(glfwStandardCursor),
[](GLFWcursor *p)
{
if (p) glfwDestroyCursor(p);
});
glfwSetCursor(m_pGLFWWindow.get(), m_pGLFWCursor.get());
}
| 41.163743 | 144 | 0.662452 | [
"render",
"vector"
] |
b71c5daebaebe707fb423ecb40b655c240484ea7 | 5,342 | cpp | C++ | src/ObjectTool.Sound.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | null | null | null | src/ObjectTool.Sound.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 3 | 2019-09-10T03:50:40.000Z | 2019-09-23T04:20:14.000Z | src/ObjectTool.Sound.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 1 | 2021-10-02T14:16:28.000Z | 2021-10-02T14:16:28.000Z |
#include "stdafx.h"
#include "afxpriv.h"
#include <malloc.h>
#include <stdlib.h>
#undef abs
#include <math.h>
#include <mmsystem.h>
#include <stdio.h>
#include "mine.h"
#include "dle-xp.h"
#include "toolview.h"
#include "TextureManager.h"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP (CObjectSoundTool, CObjectTabDlg)
ON_CBN_SELCHANGE (IDC_OBJ_SOUND_EXPLODE, OnChange)
ON_CBN_SELCHANGE (IDC_OBJ_SOUND_ATTACK, OnChange)
ON_CBN_SELCHANGE (IDC_OBJ_SOUND_SEE, OnChange)
ON_CBN_SELCHANGE (IDC_OBJ_SOUND_CLAW, OnChange)
ON_CBN_SELCHANGE (IDC_OBJ_SOUND_DEATH, OnChange)
END_MESSAGE_MAP ()
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOL CObjectSoundTool::OnInitDialog ()
{
if (!CObjectTabDlg::OnInitDialog ())
return FALSE;
CGameObject *pObject = current->Object ();
CStringResource res;
for (int i = 0; i < 196; i++) {
res.Clear ();
res.Load (6000 + i);
int nSound = atoi (res.Value ());
int index = CBSoundExpl ()->AddString (res.Value () + 3);
CBSoundExpl ()->SetItemData (index, nSound);
index = CBSoundSee ()->AddString (res.Value () + 3);
CBSoundSee ()->SetItemData (index, nSound);
index = CBSoundAttack ()->AddString (res.Value () + 3);
CBSoundAttack ()->SetItemData (index, nSound);
index = CBSoundClaw ()->AddString (res.Value () + 3);
CBSoundClaw ()->SetItemData (index, nSound);
index = CBSoundDeath ()->AddString (res.Value () + 3);
CBSoundDeath ()->SetItemData (index, nSound);
}
Refresh ();
m_bInited = true;
return TRUE;
}
//------------------------------------------------------------------------------
void CObjectSoundTool::DoDataExchange (CDataExchange *pDX)
{
}
//------------------------------------------------------------------------------
void CObjectSoundTool::EnableControls (BOOL bEnable)
{
CDlgHelpers::EnableControls (IDC_OBJ_SOUND_EXPLODE, IDC_OBJ_SOUND_DEATH, bEnable && (objectManager.Count () > 0) && (current->Object ()->Type () == OBJ_ROBOT));
}
//------------------------------------------------------------------------------
bool CObjectSoundTool::Refresh (void)
{
if (!(m_bInited && theMine))
return false;
if (current->ObjectId () == objectManager.Count ()) {
EnableControls (FALSE);
return true;
}
EnableControls (TRUE);
// update object list box
CGameObject* pObject = current->Object ();
// gray contains and behavior if not a robot type object
if (pObject->Type () != OBJ_ROBOT) {
for (int i = IDC_OBJ_SOUND_EXPLODE; i <= IDC_OBJ_SOUND_DEATH; i++)
CBCtrl (i)->SetCurSel (-1);
}
else {
for (int i = IDC_OBJ_SOUND_EXPLODE; i <= IDC_OBJ_SOUND_DEATH; i++)
CBCtrl (i)->SetCurSel (0);
}
RefreshRobot ();
UpdateData (FALSE);
DLE.MineView ()->Refresh (FALSE);
return true;
}
//------------------------------------------------------------------------------
void CObjectSoundTool::RefreshRobot (void)
{
CGameObject* pObject = current->Object ();
int nType = pObject->Type ();
if (nType != OBJ_ROBOT) {
CBSoundExpl ()->SetCurSel (-1);
CBSoundSee ()->SetCurSel (-1);
CBSoundAttack ()->SetCurSel (-1);
CBSoundClaw ()->SetCurSel (-1);
CBSoundDeath ()->SetCurSel (-1);
return;
}
int nId = int (pObject->Id ());
CRobotInfo robotInfo = *robotManager.RobotInfo (nId);
SelectItemData (CBSoundExpl (), (int) robotInfo.Info ().expl [1].nSound);
SelectItemData (CBSoundSee (), (int) robotInfo.Info ().sounds.see);
SelectItemData (CBSoundAttack (), (int) robotInfo.Info ().sounds.attack);
SelectItemData (CBSoundClaw (), (int) robotInfo.Info ().sounds.claw);
SelectItemData (CBSoundDeath (), (int) robotInfo.Info ().deathRollSound);
}
//------------------------------------------------------------------------------
void CObjectSoundTool::UpdateRobot (void)
{
CGameObject* pObject = current->Object ();
int nId = int (pObject->Id ());
if (nId < 0 || nId >= MAX_ROBOT_ID_D2)
nId = 0;
CRobotInfo robotInfo = *robotManager.RobotInfo (nId);
robotInfo.Info ().bCustom |= 1;
robotInfo.SetModified (true);
int index;
if (0 <= (index = CBSoundExpl ()->GetCurSel ()))
robotInfo.Info ().expl [1].nSound = (ubyte) CBSoundExpl ()->GetItemData (index);
if (0 <= (index = CBSoundSee ()->GetCurSel ()))
robotInfo.Info ().sounds.see = (ubyte) CBSoundSee ()->GetItemData (index);
if (0 <= (index = CBSoundAttack ()->GetCurSel ()))
robotInfo.Info ().sounds.attack = (ubyte) CBSoundAttack ()->GetItemData (index);
if (0 <= (index = CBSoundClaw ()->GetCurSel ()))
robotInfo.Info ().sounds.claw = (ubyte) CBSoundClaw ()->GetItemData (index);
if (0 <= (index = CBSoundDeath ()->GetCurSel ()))
robotInfo.Info ().deathRollSound = (ubyte) CBSoundDeath ()->GetItemData (index);
undoManager.Begin (__FUNCTION__, udRobots);
*robotManager.RobotInfo (nId) = robotInfo;
undoManager.End (__FUNCTION__);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//eof objectdlg.cpp | 32.375758 | 160 | 0.549981 | [
"object"
] |
b71cb834048bead52bb73351a8f69a824315e3f7 | 9,019 | cpp | C++ | qtdoc/doc/src/snippets/modelview-subclasses/view.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtdoc/doc/src/snippets/modelview-subclasses/view.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtdoc/doc/src/snippets/modelview-subclasses/view.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
view.cpp
Provides a view to represent a one-dimensional sequence of integers
obtained from a list model as a series of rows.
*/
#include <QAbstractItemModel>
#include <QBrush>
#include <QItemSelection>
#include <QPainter>
#include <QPaintEvent>
#include <QPen>
#include <QPoint>
#include <QResizeEvent>
#include <QScrollBar>
#include <QSizePolicy>
#include "view.h"
LinearView::LinearView(QWidget *parent)
: QAbstractItemView(parent)
{
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
}
/*!
Returns the position of the item in viewport coordinates.
*/
QRect LinearView::itemViewportRect(const QModelIndex &index) const
{
QRect rect = itemRect(index);
QRect result(rect.left() - horizontalScrollBar()->value(),
rect.top() - verticalScrollBar()->value(),
rect.width(), viewport()->height());
return result;
}
/*!
Returns the rectangle of the item at position \a index in the
model. The rectangle is in contents coordinates.
*/
QRect LinearView::itemRect(const QModelIndex &index) const
{
if (!index.isValid())
return QRect();
else
return QRect(index.row(), 0, 1, 1);
}
void LinearView::ensureVisible(const QModelIndex &index)
{
QRect area = viewport()->rect();
QRect rect = itemViewportRect(index);
if (rect.left() < area.left())
horizontalScrollBar()->setValue(
horizontalScrollBar()->value() - rect.left());
else if (rect.right() > area.right())
horizontalScrollBar()->setValue(
horizontalScrollBar()->value() + rect.left() - area.width());
}
/*!
Returns the item that covers the coordinate given in the view.
*/
QModelIndex LinearView::itemAt(int x, int /* y */) const
{
int row = x + horizontalScrollBar()->value();
return model()->index(row, 0, QModelIndex());
}
//void LinearView::dataChanged(const QModelIndex &/* topLeft */,
// const QModelIndex &/* bottomRight */)
//{
// updateGeometries();
// if (isVisible())
// repaint();
//}
void LinearView::rowsInserted(const QModelIndex &/* parent */, int /* start */,
int /* end */)
{
updateGeometries();
if (isVisible())
repaint();
}
void LinearView::rowsRemoved(const QModelIndex &/* parent */, int /* start */,
int /* end */)
{
updateGeometries();
if (isVisible())
repaint();
}
/*
void LinearView::verticalScrollbarAction(int action)
{
}
void LinearView::horizontalScrollbarAction(int action)
{
}
*/
/*!
Select the items in the model that lie within the rectangle specified by
\a rect, using the selection \a command.
*/
void LinearView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
{
QModelIndex leftIndex = itemAt(rect.left(), 0);
QModelIndex rightIndex = itemAt(rect.right(), 0);
QItemSelection selection(leftIndex, rightIndex);
selectionModel()->select(selection, command);
}
QModelIndex LinearView::moveCursor(QAbstractItemView::CursorAction cursorAction,
Qt::KeyboardModifiers)
{
QModelIndex current = currentIndex();
switch (cursorAction) {
case MoveLeft:{
if (current.row() > 0)
return model()->index(current.row() - 1, 0, QModelIndex());
else
return model()->index(0, 0, QModelIndex());
break;}
case MoveRight:{
if (current.row() < rows(current) - 1)
return model()->index(current.row() + 1, 0, QModelIndex());
else
return model()->index(rows(current) - 1, 0,QModelIndex());
break;}
case MoveUp:
return current;
case MoveDown:
return current;
case MovePageUp:
return current;
case MovePageDown:
return current;
case MoveHome:
return model()->index(0, 0, QModelIndex());
case MoveEnd:
return model()->index(rows(current) - 1, 0, QModelIndex());
default:
return current;
}
}
int LinearView::horizontalOffset() const
{
return horizontalScrollBar()->value();
}
int LinearView::verticalOffset() const
{
return verticalScrollBar()->value();
}
/*!
Returns a rectangle corresponding to the selection in viewport cooridinates.
*/
QRect LinearView::selectionViewportRect(const QItemSelection &selection) const
{
int ranges = selection.count();
if (ranges == 0)
return QRect();
// Note that we use the top and bottom functions of the selection range
// since the data is stored in rows.
int firstRow = selection.at(0).top();
int lastRow = selection.at(0).top();
for (int i = 0; i < ranges; ++i) {
firstRow = qMin(firstRow, selection.at(i).top());
lastRow = qMax(lastRow, selection.at(i).bottom());
}
QModelIndex firstItem = model()->index(qMin(firstRow, lastRow), 0,
QModelIndex());
QModelIndex lastItem = model()->index(qMax(firstRow, lastRow), 0,
QModelIndex());
QRect firstRect = itemViewportRect(firstItem);
QRect lastRect = itemViewportRect(lastItem);
return QRect(firstRect.left(), firstRect.top(),
lastRect.right() - firstRect.left(), firstRect.height());
}
void LinearView::paintEvent(QPaintEvent *event)
{
QPainter painter(viewport());
QRect updateRect = event->rect();
QBrush background(Qt::black);
QPen foreground(Qt::white);
painter.fillRect(updateRect, background);
painter.setPen(foreground);
QModelIndex firstItem = itemAt(updateRect.left(), updateRect.top());
if (!firstItem.isValid())
firstItem = model()->index(0, 0, QModelIndex());
QModelIndex lastItem = itemAt(updateRect.right(), updateRect.bottom());
if (!lastItem.isValid())
lastItem = model()->index(rows() - 1, 0, QModelIndex());
int x = updateRect.left();
//int top = updateRect.top();
//int bottom = updateRect.bottom();
int row = firstItem.row();
QModelIndex index = model()->index(row, 0, QModelIndex());
int value = model()->data(index, Qt::DisplayRole).toInt();
int midPoint = viewport()->height()/2;
int y2 = midPoint - int(value * midPoint/255.0);
while (row <= lastItem.row()) {
QModelIndex index = model()->index(row, 0, QModelIndex());
int value = model()->data(index, Qt::DisplayRole).toInt();
int y1 = y2;
y2 = midPoint - int(value * midPoint/255.0);
painter.drawLine(x-1, y1, x, y2);
++row; ++x;
}
}
void LinearView::resizeEvent(QResizeEvent * /* event */)
{
updateGeometries();
}
void LinearView::updateGeometries()
{
if (viewport()->width() < rows()) {
horizontalScrollBar()->setPageStep(viewport()->width());
horizontalScrollBar()->setRange(0, rows() - viewport()->width() - 1);
}
}
QSize LinearView::sizeHint() const
{
return QSize(rows(), 200);
}
int LinearView::rows(const QModelIndex &index) const
{
return model()->rowCount(model()->parent(index));
}
bool LinearView::isIndexHidden(const QModelIndex &index) const
{
return false;
}
| 28.631746 | 93 | 0.647855 | [
"model"
] |
b727577841b6f2a518aafcf41951f57638181b81 | 4,831 | cc | C++ | diagnostics/wilco_dtc_supportd/telemetry/bluetooth_event_service_impl.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | diagnostics/wilco_dtc_supportd/telemetry/bluetooth_event_service_impl.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | diagnostics/wilco_dtc_supportd/telemetry/bluetooth_event_service_impl.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2019 The Chromium OS 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 "diagnostics/wilco_dtc_supportd/telemetry/bluetooth_event_service_impl.h"
#include <algorithm>
#include <utility>
namespace diagnostics {
BluetoothEventServiceImpl::BluetoothEventServiceImpl(
BluetoothClient* bluetooth_client)
: bluetooth_client_(bluetooth_client) {
DCHECK(bluetooth_client_);
bluetooth_client_->AddObserver(this);
}
BluetoothEventServiceImpl::~BluetoothEventServiceImpl() {
bluetooth_client_->RemoveObserver(this);
}
const std::vector<BluetoothEventService::AdapterData>&
BluetoothEventServiceImpl::GetLatestEvent() {
return last_adapters_data_;
}
void BluetoothEventServiceImpl::AdapterAdded(
const dbus::ObjectPath& adapter_path,
const BluetoothClient::AdapterProperties& properties) {
AdapterChanged(adapter_path, properties);
UpdateAdaptersData();
}
void BluetoothEventServiceImpl::AdapterRemoved(
const dbus::ObjectPath& adapter_path) {
adapters_.erase(adapter_path);
connected_devices_.erase(adapter_path);
UpdateAdaptersData();
}
void BluetoothEventServiceImpl::AdapterPropertyChanged(
const dbus::ObjectPath& adapter_path,
const BluetoothClient::AdapterProperties& properties) {
AdapterChanged(adapter_path, properties);
UpdateAdaptersData();
}
void BluetoothEventServiceImpl::DeviceAdded(
const dbus::ObjectPath& device_path,
const BluetoothClient::DeviceProperties& properties) {
DeviceChanged(device_path, properties);
UpdateAdaptersData();
}
void BluetoothEventServiceImpl::DeviceRemoved(
const dbus::ObjectPath& device_path) {
RemoveConnectedDevice(device_path);
UpdateAdaptersData();
}
void BluetoothEventServiceImpl::DevicePropertyChanged(
const dbus::ObjectPath& device_path,
const BluetoothClient::DeviceProperties& properties) {
DeviceChanged(device_path, properties);
UpdateAdaptersData();
}
void BluetoothEventServiceImpl::AdapterChanged(
const dbus::ObjectPath& adapter_path,
const BluetoothClient::AdapterProperties& properties) {
auto adapters_iter = adapters_.find(adapter_path);
if (adapters_iter != adapters_.end()) {
adapters_iter->second.name = properties.name.value();
adapters_iter->second.address = properties.address.value();
adapters_iter->second.powered = properties.powered.value();
return;
}
std::set<dbus::ObjectPath> devices;
AdapterData adapter;
adapter.name = properties.name.value();
adapter.address = properties.address.value();
adapter.powered = properties.powered.value();
adapter.connected_devices_count =
static_cast<uint32_t>(connected_devices_[adapter_path].size());
adapters_.insert({adapter_path, adapter});
}
void BluetoothEventServiceImpl::DeviceChanged(
const dbus::ObjectPath& device_path,
const BluetoothClient::DeviceProperties& properties) {
if (!properties.connected.value()) {
RemoveConnectedDevice(device_path);
return;
}
device_to_adapter_[device_path] = properties.adapter.value();
const dbus::ObjectPath& adapter_path = properties.adapter.value();
connected_devices_[adapter_path].insert(device_path);
UpdateAdapterConnectedDevicesCount(adapter_path);
}
void BluetoothEventServiceImpl::RemoveConnectedDevice(
const dbus::ObjectPath& device_path) {
auto device_to_adapter_iter = device_to_adapter_.find(device_path);
if (device_to_adapter_iter == device_to_adapter_.end()) {
return;
}
const dbus::ObjectPath& adapter_path = device_to_adapter_iter->second;
auto connected_devices_iter = connected_devices_.find(adapter_path);
if (connected_devices_iter != connected_devices_.end()) {
connected_devices_iter->second.erase(device_path);
}
device_to_adapter_.erase(device_to_adapter_iter);
UpdateAdapterConnectedDevicesCount(adapter_path);
}
void BluetoothEventServiceImpl::UpdateAdapterConnectedDevicesCount(
const dbus::ObjectPath& adapter_path) {
auto adapters_iter = adapters_.find(adapter_path);
if (adapters_iter != adapters_.end()) {
adapters_iter->second.connected_devices_count =
static_cast<uint32_t>(connected_devices_[adapter_path].size());
}
}
void BluetoothEventServiceImpl::UpdateAdaptersData() {
std::vector<AdapterData> new_adapters_data_;
for (const auto& it : adapters_) {
new_adapters_data_.push_back(it.second);
}
if (last_adapters_data_.size() == new_adapters_data_.size() &&
std::equal(last_adapters_data_.begin(), last_adapters_data_.end(),
new_adapters_data_.begin())) {
return;
}
last_adapters_data_ = std::move(new_adapters_data_);
for (auto& observer : observers_) {
observer.BluetoothAdapterDataChanged(last_adapters_data_);
}
}
} // namespace diagnostics
| 31.37013 | 82 | 0.772511 | [
"vector"
] |
b72e3ecd381c182224293a65b2d88d8e051b9012 | 7,427 | cc | C++ | fully_dynamic_submodular_maximization/dynamic_submodular_algorithm.cc | deepneuralmachine/google-research | d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231 | [
"Apache-2.0"
] | 23,901 | 2018-10-04T19:48:53.000Z | 2022-03-31T21:27:42.000Z | fully_dynamic_submodular_maximization/dynamic_submodular_algorithm.cc | deepneuralmachine/google-research | d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231 | [
"Apache-2.0"
] | 891 | 2018-11-10T06:16:13.000Z | 2022-03-31T10:42:34.000Z | fully_dynamic_submodular_maximization/dynamic_submodular_algorithm.cc | deepneuralmachine/google-research | d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231 | [
"Apache-2.0"
] | 6,047 | 2018-10-12T06:31:02.000Z | 2022-03-31T13:59:28.000Z | // Copyright 2020 The Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Our algorithm
//
// The simple algorithm from Section 3 of the paper.
// Reconstructs starting from level l_begin.
#include "dynamic_submodular_algorithm.h"
using std::vector;
void OurSimpleAlgorithm::OurSimpleAlgorithmSingleThreshold::LevelConstruct(
int l_begin) {
// For levels lower than l_begin, just condition f on the S-sets of those
// levels.
// When we are at l, this is the size of S_1 u S_2 u ... S_l.
size_of_S_ = 0;
sub_func_f_.Reset();
for (int l = 0; l < l_begin; ++l) {
for (int e : solutions_S_[l]) {
sub_func_f_.AddAndIncreaseOracleCall(e);
// We do not count these in our model.
sub_func_f_.oracle_calls_--;
++size_of_S_;
}
}
// For levels beginning from l_begin, remake A, B and S.
// currentA = union of B[l_begin] and A[l_begin].
vector<int> currentA(buffer_B_[l_begin].begin(), buffer_B_[l_begin].end());
currentA.insert(currentA.end(), levels_A_[l_begin].begin(),
levels_A_[l_begin].end());
RandomHandler::Shuffle(currentA);
for (int l = l_begin; l <= num_T_; ++l) {
levels_A_[l].clear();
solutions_S_[l].clear();
buffer_B_[l].clear();
}
Filter(currentA, [&](int e) {
return sub_func_f_.DeltaAndIncreaseOracleCall(e) >=
gamma_ / (2 * cardinality_k_);
});
for (int l = l_begin; l <= num_T_ && size_of_S_ < cardinality_k_; ++l) {
levels_A_[l].insert(currentA.begin(), currentA.end());
if (currentA.empty()) {
return;
}
while (currentA.size() >= 1ULL << (num_T_ - l)) {
for (int e : currentA) {
if (sub_func_f_.DeltaAndIncreaseOracleCall(e) >
gamma_ / (2 * cardinality_k_)) {
solutions_S_[l].insert(e);
sub_func_f_.AddAndIncreaseOracleCall(e);
size_of_S_++;
if (size_of_S_ == cardinality_k_) return;
break;
}
}
Filter(currentA, [&](int e) {
return sub_func_f_.DeltaAndIncreaseOracleCall(e) >=
gamma_ / (2 * cardinality_k_);
});
}
}
}
// Preprocessing the variables as explained in the paper.
OurSimpleAlgorithm::OurSimpleAlgorithmSingleThreshold::
OurSimpleAlgorithmSingleThreshold(int num_T, SubmodularFunction& sub_func_f,
int cardinality_k, double gamma,
double eps)
: num_T_(num_T),
buffer_B_(num_T + 1),
levels_A_(num_T + 1),
solutions_S_(num_T + 1),
size_of_S_(0),
sub_func_f_(sub_func_f),
lowest_level_(-1),
cardinality_k_(cardinality_k),
gamma_(gamma),
eps_(eps) {}
// Take any k elements (or all if fewer).
double
OurSimpleAlgorithm::OurSimpleAlgorithmSingleThreshold::GetSolutionValue() {
sub_func_f_.Reset();
int count = 0;
double obj_val = 0.0;
for (int l = 0; l <= num_T_ && count < cardinality_k_; ++l) {
for (int e : solutions_S_[l]) {
obj_val += sub_func_f_.AddAndIncreaseOracleCall(e, -1);
++count;
if (count == cardinality_k_) {
break;
}
}
}
// In our oracle model it is just one call.
SubmodularFunction::oracle_calls_ -= 2 * count - 1;
return obj_val;
}
// Take any k elements (or all if fewer).
vector<int>
OurSimpleAlgorithm::OurSimpleAlgorithmSingleThreshold::GetSolutionVector() {
vector<int> solution;
for (int l = 0; l <= num_T_; ++l) {
for (int e : solutions_S_[l]) {
solution.push_back(e);
if (static_cast<int>(solution.size()) == cardinality_k_) {
return solution;
}
}
}
return solution;
}
void OurSimpleAlgorithm::OurSimpleAlgorithmSingleThreshold::Insert(
int element) {
sub_func_f_.Reset();
if (sub_func_f_.DeltaAndIncreaseOracleCall(element) <
gamma_ / (2 * cardinality_k_)) {
return;
}
for (int l = 0; l <= num_T_; ++l) {
buffer_B_[l].insert(element);
}
for (int l = 0; l <= num_T_; ++l) {
if (buffer_B_[l].size() >= (1ULL << (num_T_ - l)) &&
size_of_S_ < cardinality_k_) {
LevelConstruct(l);
return;
}
}
}
void OurSimpleAlgorithm::OurSimpleAlgorithmSingleThreshold::Erase(int element) {
// Erase from A and B:
for (int l = 0; l <= num_T_; ++l) {
buffer_B_[l].erase(element);
levels_A_[l].erase(element);
}
// Erase from S:
for (int l = 0; l <= num_T_; ++l) {
if (solutions_S_[l].find(element) != solutions_S_[l].end()) {
sub_func_f_.Reset();
solutions_S_[l].erase(element);
size_of_S_--;
// Recompute objective function.
double objective = 0.0;
for (int i = 0; i <= num_T_; ++i) {
for (int w : solutions_S_[i]) {
objective += sub_func_f_.AddAndIncreaseOracleCall(w, -1);
SubmodularFunction::oracle_calls_ -= 2;
}
}
SubmodularFunction::oracle_calls_++;
// Update lowest_level.
if (lowest_level_ == -1) {
lowest_level_ = l;
}
lowest_level_ = std::min(lowest_level_, l);
// If objective function decreased by too much, then recompute
// starting from lowest_level.
if (objective < (1 - eps_) * (gamma_ / 2)) {
LevelConstruct(lowest_level_);
lowest_level_ = -1;
}
// An element can be in at most one S-set, so we can return.
return;
}
}
}
OurSimpleAlgorithm::OurSimpleAlgorithm(double eps) : eps_(eps) {}
void OurSimpleAlgorithm::Init(const SubmodularFunction& sub_func_f,
int cardinality_k) {
// Create a copy of f to be shared among the "singles".
sub_func_f_ = sub_func_f.Clone();
singles_.clear();
// To make sure we do not make error because of double computations.
constexpr double double_error = 1e-6;
// num_T = log_2(n)
int num_T = static_cast<int>(
ceil(log2(sub_func_f_->GetUniverse().size()) - double_error));
for (double gamma : sub_func_f_->GetOptEstimates(cardinality_k)) {
singles_.emplace_back(num_T, *sub_func_f_, cardinality_k, gamma, eps_);
}
}
double OurSimpleAlgorithm::GetSolutionValue() {
double best = 0.0;
for (auto& single : singles_) {
best = std::max(best, single.GetSolutionValue());
}
return best;
}
vector<int> OurSimpleAlgorithm::GetSolutionVector() {
vector<int> solution;
double best = 0.0;
for (auto& single : singles_) {
double val = single.GetSolutionValue();
if (val > best) {
best = val;
solution = single.GetSolutionVector();
}
}
return solution;
}
void OurSimpleAlgorithm::Insert(int element) {
for (auto& single : singles_) {
single.Insert(element);
}
}
void OurSimpleAlgorithm::Erase(int element) {
for (auto& single : singles_) {
single.Erase(element);
}
}
std::string OurSimpleAlgorithm::GetAlgorithmName() const {
return std::string("our simple algorithm (eps = ") + std::to_string(eps_) +
std::string(")");
}
| 30.438525 | 80 | 0.632018 | [
"vector",
"model"
] |
b73776256296141663328b83a48b6b9102d21963 | 15,051 | cpp | C++ | BLAST CPU/main.cpp | FranklinAQP/BLAST | 411fa0818e8837204c6e1dd4c0c2faa75fc083c5 | [
"Apache-2.0"
] | null | null | null | BLAST CPU/main.cpp | FranklinAQP/BLAST | 411fa0818e8837204c6e1dd4c0c2faa75fc083c5 | [
"Apache-2.0"
] | null | null | null | BLAST CPU/main.cpp | FranklinAQP/BLAST | 411fa0818e8837204c6e1dd4c0c2faa75fc083c5 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <stdio.h> //printf
#include <time.h> //time, time_t, struct tm, difftime, mktime, clock_t, clock, CLOCKS_PER_SEC
#include <stdlib.h> //srand, rand
#include <algorithm> //fill_n(iterator,size,val)
#include "string.h"
#include <fstream>
#include <math.h>
#include <vector>
using namespace std;
//#define N (1048576) //1024 * 1024*5) //longitud cadena A para procesamiento en GPU
//#define M 300 //longitud cadena B para procesamiento en GPU
#define BLOCK_SIZE 16
#define SIZE_KEY 15 //tamaño de la key
#define SUCCESS 13 //minimo valor de coincidencias a considerar en la key
#define PENALTY -1
long long int M,N;
//probando que un elemento output es el resultado de la suma de su input con 14 posteriores
void semillero(char *A, char *B, bool *out){
int result;
cout<<"tamano cadena A: "<<N<<endl;
cout<<"tamano cadena B: "<<M<<endl;
for(long long int j=0; j<N; j=j+1 ){
result = 0;
if(j%100000000==0)
cout<<"j= "<<j<<endl;
for (int i = 0 ; i < SIZE_KEY ; ++i){
//cout<<"B+i = pos "<<i<<" = "<<*(B+i)<<" y "<< "(*(A+j+i)) = pos " << j+i << " " << (*(A+j+i)) << endl;
if( (*(B+i)) == (*(A+j+i)) ){
result = result + 1;
//cout << (*(B+i)) << " == " << (*(A+j+i))<<endl;
}
}
// Almacena los resultados
//cout<<"almacenando datos"<<endl;
if( result>=SUCCESS ){
//cout<<"result = "<<result<<endl;
//cout<<"*(out+j) = ";
//cout<<*(out+j)<<endl;
*(out+j) = true;
//cout<<"coincidencia en posicion: "<<j<<endl;
}else{
*(out+j) = false;
}
}
}
int similarityScore(char *a, char *b){
int result;
if((*a)==(*b)){
result=2;
}else{
result=PENALTY;
}
return result;
}
int findMax(int *traceback, int length, int &index){
int max = *traceback;
index = 0;
for(int i=1; i<length; ++i){
if(*(traceback+i) > max){
max = *(traceback+i);
index=i;
}
}
return max;
}
void Smith_Waterman_run(char *A, char *B, int n, bool *out, int *ind){
if((*out)==0)
return;
int matrix[n][n];
int matrix_max, i_max, j_max;
int type_index; ///tipo de rastreo con mayor indice
///inicializar a 0s la matriz
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
matrix[i][j]=0;
}
}
int traceback[4]; ///Para rastrear el mayor posible valor que tomaria el indice local
int I_i[n+1][n+1];///Guarda i de secuencia de generación de mayor indice
int I_j[n+1][n+1];///Guarda j de secuencia de generación de mayor indice
///Comparación de cadenas con key SUCCESS
for (int i=1;i<=n;i++){
for(int j=0;j<=n;j++){
traceback[0] = matrix[i-1][j-1]+similarityScore(A+i-1,B+j-1);
traceback[1] = matrix[i-1][j]+PENALTY;
traceback[2] = matrix[i][j-1]+PENALTY;
traceback[3] = 0;
matrix[i][j] = findMax(&(traceback[0]),4, type_index);
switch(type_index){
case 0:
I_i[i][j] = i-1;
I_j[i][j] = j-1;
break;
case 1:
I_i[i][j] = i-1;
I_j[i][j] = j;
break;
case 2:
I_i[i][j] = i;
I_j[i][j] = j-1;
break;
case 3:
I_i[i][j] = i;
I_j[i][j] = j;
break;
}
}
}
/// imprime lo almacenado en consola
for(int i=1;i<n;i++){
for(int j=1;j<n;j++){
printf("%d - ",matrix[i][j]);
}
printf("\n \n");
}
/// Encuentra el maximo score de la matriz
matrix_max = 0;
i_max=0; j_max=0;
for(int i=1;i<n;i++){
for(int j=1;j<n;j++){
if(matrix[i][j]>matrix_max){
matrix_max = matrix[i][j];
i_max=i;
j_max=j;
}
}
}
*(ind) = matrix_max;
printf("Maximo escore es: %d \n \n",matrix_max);
}
/*
void Smith_Waterman(char *A, char *B, long long int n, int *out, int *ind){
cout<<"Dentro de Smith waterman"<<endl;
int matrix[n+1][n+1];
int matrix_max, i_max, j_max;
int type_index;
cout<<"Se crearon variables de inicio"<<endl;
///inicializar a 0s la matriz
printf ("Iniciando matriz a 0s\n");
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
matrix[i][j]=0;
}
}
int traceback[4];
int I_i[n+1][n+1];
int I_j[n+1][n+1];
///Comparación de cadenas con key SUCCESS
//printf ("cadena grande = %d\n",N);
//printf ("cadena corta = %d\n",M);
printf ("Iniciando comparación\n");
for (long long int k=0;k<N + SIZE_KEY -2 -M; ++k){
if(*(out+k)>=SUCCESS){
printf ("Iniciando comparación en posicion %d \n",k);
for (long long int i=1;i<=n;i++){
for(long long int j=0;j<=n;j++){
//cout <<"i: " << i << " -- " << "j: "<< j << seqA[i-1] << seqA[j-1] << endl;
traceback[0] = matrix[i-1][j-1]+similarityScore(A+k+i-1,B+j-1);
traceback[1] = matrix[i-1][j]+PENALTY;
traceback[2] = matrix[i][j-1]+PENALTY;
traceback[3] = 0;
matrix[i][j] = findMax(&(traceback[0]),4, type_index);
switch(type_index){
case 0:
I_i[i][j] = i-1;
I_j[i][j] = j-1;
break;
case 1:
I_i[i][j] = i-1;
I_j[i][j] = j;
break;
case 2:
I_i[i][j] = i;
I_j[i][j] = j-1;
break;
case 3:
I_i[i][j] = i;
I_j[i][j] = j;
break;
}
}
}
/// imprime lo almacenado en consola
/// Encuentra el maximo score de la matriz
matrix_max = 0;
int i_max=0, j_max=0;
for(long long int i=1;i<n;i++){
for(long long int j=1;j<n;j++){
if(matrix[i][j]>matrix_max){
matrix_max = matrix[i][j];
i_max=i;
j_max=j;
}
}
}
*(ind+k) = matrix_max;
printf("Maximo escore es: %d \n",matrix_max);
}
}
}
*/
void Smith_Waterman(char *A, char *B, long long int n, bool *out, int *ind){
cout<<"Dentro de Smith waterman"<<endl;
int **matrix = (int**) malloc( (n+1) * sizeof(int *) );
for(long long int i = 0; i < n+1; i++)
{
matrix[i] = (int*) malloc( (n+1) * sizeof(int));
if(matrix[i] == NULL)
{
fprintf(stderr, "No hay memoria suficiente\n");
return;
}
}
int matrix_max, i_max, j_max;
int type_index;
cout<<"Se crearon variables de inicio"<<endl;
///inicializar a 0s la matriz
cout<<"Iniciando matriz a 0s con \n";
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
matrix[i][j]=0;
}
}
int traceback[4];
int I_i[n+1][n+1];
int I_j[n+1][n+1];
///Comparación de cadenas con key SUCCESS
//printf ("cadena grande = %d\n",N);
//printf ("cadena corta = %d\n",M);
printf ("Iniciando comparación\n");
for (long long int k=0;k<N + SIZE_KEY -2 -M; ++k){
if(*(out+k)==true){
printf ("Iniciando comparación en posicion %d \n",k);
for (long long int i=1;i<=n;i++){
for(long long int j=0;j<=n;j++){
//cout <<"i: " << i << " -- " << "j: "<< j << seqA[i-1] << seqA[j-1] << endl;
traceback[0] = matrix[i-1][j-1]+similarityScore(A+k+i-1,B+j-1);
traceback[1] = matrix[i-1][j]+PENALTY;
traceback[2] = matrix[i][j-1]+PENALTY;
traceback[3] = 0;
matrix[i][j] = findMax(&(traceback[0]),4, type_index);
switch(type_index){
case 0:
I_i[i][j] = i-1;
I_j[i][j] = j-1;
break;
case 1:
I_i[i][j] = i-1;
I_j[i][j] = j;
break;
case 2:
I_i[i][j] = i;
I_j[i][j] = j-1;
break;
case 3:
I_i[i][j] = i;
I_j[i][j] = j;
break;
}
}
}
/// imprime lo almacenado en consola
/*
cout<<" ";
for(int i=0;i<n;i++){
cout<<*(B+i)<<" ";
}
cout<<endl;
for(int i=0;i<n;i++){
cout<<*(A+k+i)<<" ";
for(int j=0;j<n;j++){
cout << matrix[i+1][j+1] << " ";
}
cout << endl;
}
*/
/// Encuentra el maximo score de la matriz
matrix_max = 0;
int i_max=0, j_max=0;
for(long long int i=1;i<n;i++){
for(long long int j=1;j<n;j++){
if(matrix[i][j]>matrix_max){
matrix_max = matrix[i][j];
i_max=i;
j_max=j;
}
}
}
//*(ind+k) = matrix_max;
printf("Maximo escore es: %d \n",matrix_max);
}
}
for(long long int i = 0; i < n+1; i++)
{
free (matrix[i]);
}
free (matrix);
}
void fill_ints (int *x,int n) {
fill_n(x, n, 0);
}
void fill_ADN (char *x, int n){
char bases[4] = {'A','C','G','T'};
int tmp;
for(int i=0; i<n-1; ++i){
tmp = rand()%4;
*(x+i)=bases[tmp];
}
}
void print_ADN(char *x, int n){
printf("valor de cadena ADN: \n");
for(int i=0; i<n; ++i){
printf("%c",*(x+i));
}
printf(" \n \n");
}
int main(void) {
clock_t t;
srand(time(NULL)); //Inicia random
char *A, *B;
bool *out;
int *ind; // coincidencias e indice mayor de coincidencias Smith_waterman
/*Codigo para probar cadenas de determinada longitufd*/
/*long int sizeA = (N + SIZE_KEY -1) *sizeof(char);
long int sizeB = (M) *sizeof(char);
long int sizeout = (N + SIZE_KEY -1) *sizeof(int);
long int sizeind = (N + SIZE_KEY -1) *sizeof(int);
cout<<"size A = "<<sizeA<<"\n";
cout<<"size B = "<<sizeB<<"\n";
cout<<"size out = "<<sizeout<<"\n";
cout<<"size ind = "<<sizeind<<"\n";
cout<<"Generando punteros\n";
A = (char *)malloc(sizeA); fill_ADN(A, N + SIZE_KEY -1);
cout<<"Cadena A generada\n";
B = (char *)malloc(sizeB); fill_ADN(B, M);
cout<<"Cadena B generada\n";
out = (int *)malloc(sizeout); fill_ints(out, N + SIZE_KEY -1);
cout<<"Cadena out generada\n";
ind = (int *)malloc(sizeind); fill_ints(ind, N + SIZE_KEY -1);
cout<<"Cadena ind generada\n";
cout<<"Iniciando semillero\n";
semillero(A, B, out);
*/
/*Codigo para probar cadenas de determinada longitufd*/
/*Codigo para cargar archivo*/
string a,b;
char namefile_a[256];
char namefile_b[256];
char *fileA,*fileB;
char base;
char index_a[256], index_b[256];
/*
cout<<"ingrese nombre del archivo A (a.txt): "<<endl;
cin>>namefile_a;
//cin.get (namefile_a,256);
cout<<"ingrese nombre del archivo B (b.txt): "<<endl;
//cin.get (namefile_b,256);
cin>>namefile_b;
*/
t = clock();
cout<<"\nArchivo A leido: " << namefile_a<<"\n";
ifstream filea("a.txt", std::ifstream::binary);//namefile_a
filea.seekg(0,filea.end);///Calcula el tamano del archivo
long long int size_a = filea.tellg();
cout<<"tamaño: "<< filea.tellg()<<endl;///Imprime al tamano
filea.seekg(0,filea.beg);///Retorna el puntero al inicio del documento
fileA = (char*) malloc( size_a * sizeof(char) );
/*
while (filea.get(base)){
cout<<base;
if(base=='\n')
break;
}*/
filea.read( fileA, size_a );
cout<<"Cadena: "<<endl;
/*
for(long long int h=0; h<size_a-1; ++h){
if(h<100 || h>3151400000)
cout << *(fileA+h);
}*/
filea.close();
cout<<"\n\nArchivo B leido: " << namefile_b<<"\n";
ifstream fileb("b.txt", std::ifstream::binary);//namefile_b
fileb.seekg(0,fileb.end);///Calcula el tamano del archivo
long long int size_b = fileb.tellg();
cout<<"tamano: "<<fileb.tellg()<<endl;///Imprime al tamano
fileb.seekg(0,fileb.beg);
/*
long long int z =0;
while (fileb.get(base)){
cout<<base;
++z;
if(base=='\n')
break;
}
cout<<"\nz= "<<z<<endl;
*/
//fileb.seekg(0,fileb.beg);///Retorna el puntero al inicio del documento
fileB = (char*) malloc( size_b * sizeof(char) );
// loop getting single characters
fileb.read( fileB, size_b);//-z
/*
cout<<"Cadena: "<<endl;
for(long long int h=0; h<size_b-z; ++h){
cout << *(fileB+h);
}
cout<<"Cadena impresa: "<<endl;
*/
fileb.close();
/*Codigo para cargar archivo*/
cout<<"pasando a semillar"<<endl;
N = size_a -1;
M = size_b -1;// -z;
cout<<"creando variables de almacenamiento de resultados"<<endl;
long int sizeout = (size_a -1+ SIZE_KEY) *sizeof(bool);
cout<<"sizeout = "<< sizeout << endl;
out = (bool*)malloc(sizeout); //fill_ints(out, N + SIZE_KEY);
//long long int sizeind = (size_a -1 + SIZE_KEY) *sizeof(int);
//ind = (int*)malloc(sizeind); //fill_ints(ind, N + SIZE_KEY -1);
if (out==NULL){
free(fileA); free(fileB); free(out); free(ind);
cout<<"No se puede asignar memoria a la variable"<<endl;
exit (1);
}
cout<<"Iniciando semillero\n";
semillero(fileA, fileB, out);
cout<<"Tiempo de semillero: "<<double(clock() - t)/double(CLOCKS_PER_SEC);
printf ("\n Iniciando Smith Waterman\n");
//Smith_Waterman(A, B, int (M), out, ind);
Smith_Waterman(fileA, fileB, (long long int) (M), out, ind);
printf ("\n Terminando Smith Waterman\n");
t = clock() - t;
//Imprimiendo
//print_ADN(A,N + SIZE_KEY -1);
//print_ADN(B,M);
printf ("Tiempo t: %f seconds.\n", double(t)/double(CLOCKS_PER_SEC));
//Cleanup
free(fileA); free(fileB); free(out); //free(ind);
//free(A); free(B); free(out); free(ind);
return 0;
}
| 29.339181 | 119 | 0.465484 | [
"vector"
] |
b73c376f5278e8e3d94a23ac45cf18bbad662ea0 | 2,093 | cpp | C++ | FroggerObjects/Utilities/HitableObject.cpp | RicardoEPRodrigues/FroggerOpenGL | dc02437dfe14203e9bdb39f160e4877b44363c42 | [
"MIT"
] | null | null | null | FroggerObjects/Utilities/HitableObject.cpp | RicardoEPRodrigues/FroggerOpenGL | dc02437dfe14203e9bdb39f160e4877b44363c42 | [
"MIT"
] | 1 | 2016-12-31T15:43:29.000Z | 2016-12-31T15:43:29.000Z | FroggerObjects/Utilities/HitableObject.cpp | RicardoEPRodrigues/FroggerOpenGL | dc02437dfe14203e9bdb39f160e4877b44363c42 | [
"MIT"
] | null | null | null | /*
* HitableObject.cpp
*
* Created on: Oct 30, 2014
* Author: ricardo
*/
#include "HitableObject.h"
HitableObject::HitableObject(Vector3 minBounds, Vector3 maxBounds) {
this->_min_bounds = minBounds;
this->_max_bounds = maxBounds;
}
HitableObject::~HitableObject() {
}
bool HitableObject::hitAux(Vector3 firstMinBounds, Vector3 firstMaxBounds,
Vector3 secondMinBounds, Vector3 secondMaxBounds, bool compareZ) {
bool isXCollision = ((firstMinBounds.getX() >= secondMinBounds.getX()
&& firstMinBounds.getX() <= secondMaxBounds.getX())
|| (firstMaxBounds.getX() >= secondMinBounds.getX()
&& firstMaxBounds.getX() <= secondMaxBounds.getX()));
bool isYCollision = ((firstMinBounds.getY() >= secondMinBounds.getY()
&& firstMinBounds.getY() <= secondMaxBounds.getY())
|| (firstMaxBounds.getY() >= secondMinBounds.getY()
&& firstMaxBounds.getY() <= secondMaxBounds.getY()));
// if compareZ is not active then the comparison if isZCollision is always true.
bool isZCollision =
!compareZ || (firstMinBounds.getZ() >= secondMinBounds.getZ()
&& firstMinBounds.getZ() <= secondMaxBounds.getZ())
|| (firstMaxBounds.getZ() >= secondMinBounds.getZ()
&& firstMaxBounds.getZ()
<= secondMaxBounds.getZ());
return isXCollision && isYCollision && isZCollision;
}
bool HitableObject::isHit(HitableObject* object, bool compareZ) {
Vector3 thisPosMin = (*this->getPosition()) + this->_min_bounds;
Vector3 thisPosMax = (*this->getPosition()) + this->_max_bounds;
Vector3 objPosMin = (*object->getPosition()) + object->getMinBounds();
Vector3 objPosMax = (*object->getPosition()) + object->getMaxBounds();
return hitAux(thisPosMin, thisPosMax, objPosMin, objPosMax, compareZ) ||
hitAux(objPosMin, objPosMax, thisPosMin, thisPosMax, compareZ);
}
| 44.531915 | 93 | 0.614429 | [
"object"
] |
b73d4b28125049d057ba1d70138f49ea165cf1f0 | 1,609 | cpp | C++ | main/utils/math.cpp | rain-377/rain-csgo-base | 58bed13ce272f5403ac7324f79ca9a6b3f7a63a5 | [
"MIT"
] | 13 | 2021-05-27T19:14:26.000Z | 2022-01-27T11:29:38.000Z | main/utils/math.cpp | rain-377/rain-csgo-base | 58bed13ce272f5403ac7324f79ca9a6b3f7a63a5 | [
"MIT"
] | 2 | 2021-06-03T16:18:59.000Z | 2022-03-29T15:29:17.000Z | main/utils/math.cpp | rain-377/rain-csgo-base | 58bed13ce272f5403ac7324f79ca9a6b3f7a63a5 | [
"MIT"
] | 4 | 2021-05-25T21:23:17.000Z | 2021-08-20T22:03:02.000Z | #include "math.h"
void math::vector_angles(const vector& forward, qangle& view_angle)
{
float pitch, yaw;
if (forward.x == 0.f && forward.y == 0.f)
{
pitch = (forward.z > 0.f) ? 270.f : 90.f;
yaw = 0.f;
}
else
{
pitch = std::atan2f(-forward.z, forward.length_2d()) * 180.f / M_PI;
if (pitch < 0.f)
pitch += 360.f;
yaw = std::atan2f(forward.y, forward.x) * 180.f / M_PI;
if (yaw < 0.f)
yaw += 360.f;
}
view_angle.x = pitch;
view_angle.y = yaw;
view_angle.z = 0.f;
}
void math::angle_vectors(const qangle& angles, vector* forward, vector* right, vector* up) {
float sp, sy, sr, cp, cy, cr;
DirectX::XMScalarSinCos(&sp, &cp, M_DEG2RAD(angles.x));
DirectX::XMScalarSinCos(&sy, &cy, M_DEG2RAD(angles.y));
DirectX::XMScalarSinCos(&sr, &cr, M_DEG2RAD(angles.z));
if (forward)
{
forward->x = cp * cy;
forward->y = cp * sy;
forward->z = -sp;
}
if (right)
{
right->x = -1 * sr * sp * cy + -1 * cr * -sy;
right->y = -1 * sr * sp * sy + -1 * cr * cy;
right->z = -1 * sr * cp;
}
if (up)
{
up->x = cr * sp * cy + -sr * -sy;
up->y = cr * sp * sy + -sr * cy;
up->z = cr * cp;
}
}
vector math::vector_transform(const vector& vec_transform, const matrix3x4_t& matrix) {
return vector(vec_transform.dot_product(matrix[0]) + matrix[0][3],
vec_transform.dot_product(matrix[1]) + matrix[1][3],
vec_transform.dot_product(matrix[2]) + matrix[2][3]);
}
qangle math::calc_angle(const vector& start, const vector& end)
{
qangle view_angle;
const vector delta = end - start;
vector_angles(delta, view_angle);
view_angle.normalize();
return view_angle;
} | 21.743243 | 92 | 0.614046 | [
"vector"
] |
b74604d36683a59ccda1e79f38c1ccc20a5e5995 | 8,596 | cpp | C++ | src/novatel_oem7_driver/src/receiverstatus_handler.cpp | ajay1606/novatel_oem7_driver | c18063a1ecd9a3ff1b824b73edb2d96dee511a39 | [
"MIT"
] | null | null | null | src/novatel_oem7_driver/src/receiverstatus_handler.cpp | ajay1606/novatel_oem7_driver | c18063a1ecd9a3ff1b824b73edb2d96dee511a39 | [
"MIT"
] | 1 | 2022-02-08T11:00:21.000Z | 2022-02-08T11:00:21.000Z | src/novatel_oem7_driver/src/receiverstatus_handler.cpp | ajay1606/novatel_oem7_driver | c18063a1ecd9a3ff1b824b73edb2d96dee511a39 | [
"MIT"
] | 1 | 2022-02-08T08:12:02.000Z | 2022-02-08T08:12:02.000Z | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020 NovAtel Inc.
//
// 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 <novatel_oem7_driver/oem7_message_handler_if.hpp>
#include <oem7_ros_publisher.hpp>
#include <ros/ros.h>
#include <vector>
#include <novatel_oem7_driver/oem7_ros_messages.hpp>
#include "novatel_oem7_msgs/RXSTATUS.h"
namespace novatel_oem7_driver
{
typedef std::vector<std::string> str_vector_t;
/*** Oem7 Receiver errors strings - refer to Oem7 manual */
const str_vector_t RECEIVER_ERROR_STRS
{
"DRAM",
"Invalid FW",
"ROM",
"",
"ESN Access",
"AuthCode",
"",
"Supply Voltage",
"",
"Temperature",
"MINOS",
"PLL RF",
"",
"",
"",
"NVM",
"Software resource limit exceeded",
"Model invalid for this receiver",
"",
"",
"Remote loading has begun",
"Export restriction",
"Safe Mode",
"",
"",
"",
"",
"",
"",
"",
"",
"Component hardware failure"
};
/** Oem7 receiver status strings - refer to Oem7 manual */
const str_vector_t RECEIVER_STATUS_STRS
{
"Receiver Error Flag",
"Temperature",
"Voltage Supply",
"Primary antenna not powered",
"LNA Failure",
"Primary antenna open circuit",
"Primary antenna short circuit",
"CPU overload",
"COM port tx buffer overrun",
"",
"",
"Link overrun",
"Input overrun",
"Aux transmit overrun",
"Antenna gain out of range",
"Jammer detected",
"INS reset",
"IMU communication failure",
"GPS almanac invalid",
"Position solution invalid",
"Position fixed",
"Clock steering disabled",
"Clock model invalid",
"External oscillator locked",
"Software resource warning",
"",
"Interpret Status/Error Bits as Oem7 format",
"Tracking mode: HDR",
"Digital filtering enabled",
"Aux3 event",
"Aux2 event",
"Aux1 event"
};
/** Auxiliary 1 Status strings - refer to Oem7 manual. */
const str_vector_t AUX1_STATUS_STRS
{
"Jammer detected on RF1",
"Jammer detected on RF2",
"Jammer detected on RF3",
"Position averaging On",
"Jammer detected on RF4",
"Jammer detected on RF5",
"Jammer detected on RF6",
"USB not connected",
"USB1 buffer overrun",
"USB2 buffer overrun",
"USB3 buffer overrun",
"",
"Profile Activation Error",
"Throttled Ethernet Reception",
"",
"",
"",
"",
"Ethernet not connected",
"ICOM1 buffer overrun",
"ICOM2 buffer overrun",
"ICOM3 buffer overrun",
"NCOM1 buffer overrun",
"NCOM2 buffer overrun",
"NCOM3 buffer overrun",
"",
"",
"",
"",
"",
"",
"IMU measurement outlier detected"
};
/** Auxiliary 2 Status strings - refer to Oem7 manual. */
const str_vector_t AUX2_STATUS_STRS
{
"SPI Communication Failure",
"I2C Communication Failure",
"COM4 buffer overrun",
"COM5 buffer overrun",
"",
"",
"",
"",
"",
"COM1 buffer overrun",
"COM2 buffer overrun",
"COM3 buffer overrun",
"PLL RF1 unlock",
"PLL RF2 unlock",
"PLL RF3 unlock",
"PLL RF4 unlock",
"PLL RF5 unlock",
"PLL RF6 unlock",
"CCOM1 buffer overrun",
"CCOM2 buffer overrun",
"CCOM3 buffer overrun",
"CCOM4 buffer overrun",
"CCOM5 buffer overrun",
"CCOM6 buffer overrun",
"ICOM4 buffer overrun",
"ICOM5 buffer overrun",
"ICOM6 buffer overrun",
"ICOM7 buffer overrun",
"Secondary antenna not powered",
"Secondary antenna open circuit",
"Secondary antenna short circuit",
"Reset loop detected",
};
/** Auxiliary 3 Status strings - refer to Oem7 manual. */
const str_vector_t AUX3_STATUS_STRS
{
"SCOM buffer overrun",
"WCOM1 buffer overrun",
"FILE buffer overrun",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"Web content is corrupt or does not exist",
"RF Calibration Data is present and in error",
"RF Calibration data exists and has no errors"
};
const str_vector_t AUX4_STATUS_STRS
{
"<60% of available satellites are tracked well",
"<15% of available satellites are tracked well",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"Clock freewheeling due to bad position integrity",
"",
"Usable RTK Corrections: < 60%",
"Usable RTK Corrections: < 15%",
"Bad RTK Geometry",
"",
"",
"Long RTK Baseline",
"Poor RTK COM link",
"Poor ALIGN COM link",
"GLIDE Not Active",
"Bad PDP Geometry",
"No TerraStar Subscription",
"",
"",
"",
"Bad PPP Geometry",
"",
"No INS Alignment",
"INS not converged"
};
void
get_status_info(
uint32_t bitmask,
const str_vector_t& str_map,
str_vector_t& str_list,
std::vector<uint8_t>& bit_list)
{
for(int bit = 0;
bit < (sizeof(bitmask) * 8);
bit++)
{
if(bitmask & (1 << bit))
{
bit_list.push_back(bit);
if(str_map[bit].length() > 0)
{
str_list.push_back(str_map[bit]);
}
}
}
}
/*** Handles RXSTATUS messages */
class ReceiverStatusHandler: public Oem7MessageHandlerIf
{
Oem7RosPublisher RXSTATUS_pub_;
std::string frame_id_;
public:
ReceiverStatusHandler()
{
static const size_t NUM_BITS = sizeof(uint32_t) * 8;
assert(RECEIVER_ERROR_STRS.size() == NUM_BITS);
assert(AUX1_STATUS_STRS.size() == NUM_BITS);
assert(AUX2_STATUS_STRS.size() == NUM_BITS);
assert(AUX3_STATUS_STRS.size() == NUM_BITS);
assert(AUX4_STATUS_STRS.size() == NUM_BITS);
}
~ReceiverStatusHandler()
{
}
void initialize(ros::NodeHandle& nh)
{
RXSTATUS_pub_.setup<novatel_oem7_msgs::RXSTATUS>("RXSTATUS", nh);
}
const std::vector<int>& getMessageIds()
{
static const std::vector<int> MSG_IDS({RXSTATUS_OEM7_MSGID});
return MSG_IDS;
}
void handleMsg(Oem7RawMessageIf::ConstPtr msg)
{
boost::shared_ptr<novatel_oem7_msgs::RXSTATUS> rxstatus;
MakeROSMessage(msg, rxstatus);
// Populate status strings:
get_status_info(rxstatus->error, RECEIVER_ERROR_STRS, rxstatus->error_strs, rxstatus->error_bits);
get_status_info(rxstatus->rxstat, RECEIVER_STATUS_STRS, rxstatus->rxstat_strs, rxstatus->rxstat_bits);
get_status_info(rxstatus->aux1_stat, AUX1_STATUS_STRS, rxstatus->aux1_stat_strs, rxstatus->aux1_stat_bits);
get_status_info(rxstatus->aux2_stat, AUX2_STATUS_STRS, rxstatus->aux2_stat_strs, rxstatus->aux2_stat_bits);
get_status_info(rxstatus->aux3_stat, AUX3_STATUS_STRS, rxstatus->aux3_stat_strs, rxstatus->aux3_stat_bits);
get_status_info(rxstatus->aux4_stat, AUX4_STATUS_STRS, rxstatus->aux4_stat_strs, rxstatus->aux4_stat_bits);
RXSTATUS_pub_.publish(rxstatus);
}
};
}
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(novatel_oem7_driver::ReceiverStatusHandler, novatel_oem7_driver::Oem7MessageHandlerIf)
| 24.988372 | 117 | 0.601443 | [
"geometry",
"vector",
"model"
] |
b74674a36eed2728d79c2a3d1a3d502eadb8e22b | 2,210 | hh | C++ | STMGeom/inc/SupportTable.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | STMGeom/inc/SupportTable.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | STMGeom/inc/SupportTable.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | #ifndef STMGeom_SupportTable_hh
#define STMGeom_SupportTable_hh
// Table to support things Object
//
// Author: Anthony Palladino
//
#include <string>
#include "CLHEP/Vector/Rotation.h"
#include "CLHEP/Vector/ThreeVector.h"
namespace mu2e {
class SupportTable {
public:
SupportTable(bool build, double tabletopHalfWidth,
double tabletopHalfHeight, double tabletopHalfLength,
double legRadius,
CLHEP::Hep3Vector const & originInMu2e = CLHEP::Hep3Vector(),
CLHEP::HepRotation const & rotation = CLHEP::HepRotation(),
std::string const & materialName = ""
) :
_build( build ),
_tabletopHalfWidth( tabletopHalfWidth ),
_tabletopHalfHeight( tabletopHalfHeight ),
_tabletopHalfLength( tabletopHalfLength ),
_legRadius( legRadius ),
_originInMu2e( originInMu2e ),
_rotation ( rotation ),
_materialName( materialName )
{}
bool build() const { return _build; }
double tabletopHalfWidth() const { return _tabletopHalfWidth; }
double tabletopHalfHeight() const { return _tabletopHalfHeight; }
double tabletopHalfLength() const { return _tabletopHalfLength; }
double legRadius() const { return _legRadius; }
//double zBegin() const { return _originInMu2e.z() - zTabletopHalfLength(); }
//double zEnd() const { return _originInMu2e.z() + zTabletopHalfLength(); }
CLHEP::Hep3Vector const & originInMu2e() const { return _originInMu2e; }
CLHEP::HepRotation const & rotation() const { return _rotation; }
std::string const & materialName() const { return _materialName; }
// Genreflex can't do persistency of vector<SupportTable> without a default constructor
SupportTable() {}
private:
bool _build;
double _tabletopHalfWidth;
double _tabletopHalfHeight;
double _tabletopHalfLength;
double _legRadius;
CLHEP::Hep3Vector _originInMu2e;
CLHEP::HepRotation _rotation; // wrt to parent volume
std::string _materialName;
};
}
#endif/*STMGeom_SupportTable_hh*/
| 34 | 91 | 0.652036 | [
"object",
"vector"
] |
b752922c25dffbff61d676817a118419beef8702 | 4,215 | ipp | C++ | TD3/Node.ipp | zdimension/tdpmp | 64b1560318c4790eaadbab8a41a8d8e02c93342c | [
"MIT"
] | null | null | null | TD3/Node.ipp | zdimension/tdpmp | 64b1560318c4790eaadbab8a41a8d8e02c93342c | [
"MIT"
] | null | null | null | TD3/Node.ipp | zdimension/tdpmp | 64b1560318c4790eaadbab8a41a8d8e02c93342c | [
"MIT"
] | null | null | null | //
// Created by Tom on 20/09/2021.
//
#ifndef TD3_NODE_IPP
#define TD3_NODE_IPP
#include <vector>
#include <ostream>
#include <stack>
template<typename T>
class Tree;
/**
* Binary tree node.
* @tparam T value type
*/
template<typename T>
class Node final
{
public:
explicit Node(T value) : value(value)
{
}
Node(const Node& node) :
value(node.value),
left_child(copy(node.left_child)),
right_child(copy(node.right_child))
{
}
Node(T value, Node<T>* leftChild, Node<T>* rightChild);
/**
* Removes all children from the node.
*/
void remove_all_children();
/**
* Performs an in-order traversal of the tree.
* @return nodes, in order of traversal
*/
std::vector<const Node<T>*> iterate_left_hand() const;
T get_value() const
{
return value;
}
void set_value(T val)
{
Node::value = val;
}
Node<T>* get_left_child() const
{
return left_child;
}
void set_left_child(Node<T>* leftChild)
{
left_child = leftChild;
}
Node<T>* get_right_child() const
{
return right_child;
}
void set_right_child(Node<T>* rightChild)
{
right_child = rightChild;
}
~Node()
{
delete left_child;
delete right_child;
}
/**
* @return the height of the node, i.e. the largest number of edges between the node and the deepest child node
*/
ssize_t height() const;
/**
* @return the total number of nodes in the subtree
*/
ssize_t count_nodes() const;
/**
* @see std::ostream& operator<<(std::ostream& os, const Tree<U>& tree)
*/
template<typename U>
friend std::ostream& operator<<(std::ostream& os, const Node<U>& node);
static Node<T>* copy(Node<T>* ptr)
{
if (ptr == nullptr)
return nullptr;
return new Node<T>(*ptr);
}
private:
template<typename U>
friend void remove_rec(U value, Node<U>** node);
template<typename U>
friend void Tree<U>::remove(U value);
T value;
Node<T>* left_child = nullptr;
Node<T>* right_child = nullptr;
};
template<typename T>
void Node<T>::remove_all_children()
{
remove_child(&this->left_child);
remove_child(&this->right_child);
}
template<typename T>
ssize_t Node<T>::height() const
{
if (left_child && right_child)
return std::max(left_child->height(), right_child->height()) + 1;
else if (left_child)
return left_child->height() + 1;
else if (right_child)
return right_child->height() + 1;
else
return 0;
}
template<typename T>
std::vector<const Node<T>*> Node<T>::iterate_left_hand() const
{
std::vector<const Node<T>*> vec{};
std::stack<const Node<T>*> s;
const Node<T>* curr = this;
while (curr != nullptr || !s.empty())
{
while (curr != nullptr)
{
s.push(curr);
curr = curr->get_left_child();
}
curr = s.top();
s.pop();
vec.push_back(curr);
curr = curr->get_right_child();
}
return vec;
}
template<typename T>
void remove_child(Node<T>** pointer)
{
if (*pointer != nullptr)
{
(*pointer)->remove_all_children();
delete *pointer;
*pointer = nullptr;
}
}
template<typename U>
std::ostream& operator<<(std::ostream& os, const Node<U>& node)
{
os << node.get_value();
os << "(";
if (node.get_left_child() != nullptr)
{
os << *node.get_left_child();
}
os << ")(";
if (node.get_right_child() != nullptr)
{
os << *node.get_right_child();
}
os << ")";
return os;
}
template<typename T>
ssize_t Node<T>::count_nodes() const
{
ssize_t result = 1;
if (left_child)
result += left_child->count_nodes();
if (right_child)
result += right_child->count_nodes();
return result;
}
template<typename T>
Node<T>::Node(T value, Node<T>* leftChild, Node<T>* rightChild):value(value), left_child(leftChild),
right_child(rightChild)
{
}
#endif //TD3_NODE_IPP
| 19.788732 | 115 | 0.57153 | [
"vector"
] |
b756a7cb420a03f84a817e750e2b8bda93badea1 | 6,887 | cpp | C++ | lab-08/Scheduler/SimTask.cpp | drahosj/308labs | 718a02fa943749d906d10085d48dd4b4f69931e9 | [
"MIT"
] | null | null | null | lab-08/Scheduler/SimTask.cpp | drahosj/308labs | 718a02fa943749d906d10085d48dd4b4f69931e9 | [
"MIT"
] | null | null | null | lab-08/Scheduler/SimTask.cpp | drahosj/308labs | 718a02fa943749d906d10085d48dd4b4f69931e9 | [
"MIT"
] | null | null | null | /*
* SimTask.cpp
*
* Created on: Mar 9, 2016
* Author: vens
*/
#include <iostream>
#include "Scheduler/Scheduler.h"
#include "SimTask.h"
#include "Task/Task.h"
#include "Debug.h"
#include <string>
enum TaskJsonField
{
NAME,
PRIORITY,
ARRIVE_TIME,
RUN_TIMES,
BLOCK_TIMES,
DEADLINE,
UNKNOWN
};
TaskJsonField NameToField(std::string const& str)
{
if(str == "name") return NAME;
if(str == "priority") return PRIORITY;
if(str == "arrive-time") return ARRIVE_TIME;
if(str == "run-times") return RUN_TIMES;
if(str == "block-times") return BLOCK_TIMES;
if(str == "deadline") return DEADLINE;
else return UNKNOWN;
}
SimTask::~SimTask() {
// TODO Auto-generated destructor stub
}
SimTask::SimTask(json_value * task, wavedrom::Group * wave_grp)
: times_index(0), state(SimTask::INIT), last_state(SimTask::INIT), remove_flag(false),
finish_time(0), num_context_switches(0), num_bursts(0)
{
int length, array_len;
length = task->u.object.length;
for(int i=0; i<length; i++)
{
json_value *value = task->u.object.values[i].value;
std::string val_name = task->u.object.values[i].name;
//std::cout << "processing value: " << val_name << std::endl;
switch(NameToField(val_name))
{
case NAME:
this->name = value->u.string.ptr;
this->SetName(this->name);
break;
case PRIORITY:
this->priority = value->u.integer;
this->SetPriority(this->priority);
break;
case ARRIVE_TIME:
this->next_arrival_time = value->u.integer;
break;
case RUN_TIMES:
array_len = value->u.array.length;
for(int j=0; j<array_len; j++)
{
this->times[j*2] = value->u.array.values[j]->u.integer;
}
this->times[array_len * 2 - 1] = 0;
this->num_runs = array_len;
break;
case BLOCK_TIMES:
array_len = value->u.array.length;
for(int j=0; j<array_len; j++)
{
this->times[j*2 + 1] = value->u.array.values[j]->u.integer;
}
break;
case DEADLINE:
this->deadline = value->u.integer;
this->SetDeadline(this->deadline);
break;
default:
std::cerr<< "Unrecogninzed Json Field: " << val_name << std::endl;
}
}
this->wave = wave_grp->AddSignal(this->name.c_str());
this->task = 0;
switch(this->GetPriority())
{
case 0:
// low prioirty
this->color = wavedrom::NODE::WHITE;
break;
case 1:
this->color = wavedrom::NODE::BLUE;
break;
case 2:
this->color = wavedrom::NODE::YELLOW;
break;
case 3:
default:
this->color = wavedrom::NODE::RED;
break;
}
// std::cout << "name: " << this->name << std::endl;
// std::cout << "prior: " << this->priority << std::endl;
// std::cout << "arrive: " << this->next_arrival_time << std::endl;
// std::cout << "times: ";
// for(int i=0;i<this->num_runs * 2;i++) std::cout << this->times[i] << ", ";
// std::cout << std::endl;
// std::cout << "deadline: " << this->deadline << std::endl;
}
bool SimTask::operator< (const SimTask& param)
{
return this->next_arrival_time < param.next_arrival_time;
}
unsigned long SimTask::GetArrivalTime()
{
return this->next_arrival_time;
}
bool SimTask::IsFinished()
{
return this->state == SimTask::FINISHED;
}
bool SimTask::IsRunning()
{
return this->state == SimTask::RUNNING;
}
std::string& SimTask::GetName()
{
return this->name;
}
//
void SimTask::OnStartTick(unsigned long sys_time)
{
if(this->state == SimTask::INIT)
{
this->state = SimTask::NOT_ARRIVED;
}
if(this->next_arrival_time == sys_time)
{
num_bursts += 1;
switch(this->state)
{
case SimTask::INIT:
case SimTask::NOT_ARRIVED:
Debug::AppendLog
(std::string("Task ") + this->name + " arrived at " + std::to_string(sys_time));
this->last_state = this->state;
this->state = SimTask::READY;
this->OnArrive(sys_time);
//this->task = new Task(this->name, this->priority);
Scheduler::AddTask(this, sys_time);
break;
case SimTask::RUNNING:
break;
case SimTask::READY:
break;
case SimTask::BLOCKED:
Debug::AppendLog(std::string("Task ") + this->name + " unblocked at " + std::to_string(sys_time));
this->last_state = this->state;
this->state = SimTask::READY;
Scheduler::AddTask(this, sys_time);
//this->task->MoveReady();
break;
case SimTask::FINISHED:
break;
}
}
}
void SimTask::SwapIn(unsigned long sys_time)
{
//this->last_state = this->state;
this->state = SimTask::RUNNING;
}
void SimTask::SwapOut(unsigned long sys_time)
{
this->state = SimTask::READY;
}
void SimTask::OnSysTick(unsigned long sys_time)
{
if(this->state == this->last_state)
{
this->wave->ContinueNode();
}
else
{
switch(this->state)
{
case SimTask::INIT:
case SimTask::NOT_ARRIVED:
this->wave->AddNode(wavedrom::NODE::DOWN);
break;
case SimTask::READY:
//if (this->last_state == SimTask::RUNNING)
// this->num_context_switches += 1;
this->wave->AddNode(wavedrom::NODE::Z);
break;
case SimTask::RUNNING:
this->num_context_switches += 1;
this->wave->AddNode(this->color, this->name.c_str());
break;
case SimTask::BLOCKED:
this->num_context_switches += 1;
this->wave->AddNode(wavedrom::NODE::X);
break;
case SimTask::FINISHED:
this->wave->AddNode(wavedrom::NODE::UP);
break;
}
this->last_state = this->state;
}
this->remove_flag = false;
if(this->state == SimTask::RUNNING)
{
this->task_info.run_time ++;
this->times[this->times_index]--;
if(this->times[this->times_index] == 0)
{
this->remove_flag = true;
this->times_index++;
if(this->times[this->times_index] > 0)
{
Debug::AppendLog(std::string("Task ") + this->name + " blocked at " + std::to_string(sys_time));
this->last_state = this->state;
this->state = SimTask::BLOCKED;
this->next_arrival_time = sys_time + this->times[this->times_index];
this->times[this->times_index] = 0;
this->times_index ++;
}
else
{
Debug::AppendLog(std::string("Task ") + this->name + " finished at " + std::to_string(sys_time));
this->finish_time = sys_time;
this->last_state = this->state;
this->state = SimTask::FINISHED;
}
}
}
else if(this->state == SimTask::BLOCKED)
{
this->task_info.block_time ++;
}
}
void SimTask::OnEndTick(unsigned long sys_time)
{
if(this->remove_flag)
{
SimTask::State tmp = this->state;
Scheduler::RemoveTask(sys_time);
this->state = tmp;
}
}
std::string SimTask::GetLogString()
{
std::string str("");
str += "Task " + this->name + ": ";
str += "priority=" + std::to_string(task_info.priority) + ", ";
str += "start=" + std::to_string(task_info.time_arive) + ", ";
str += "finish=" + std::to_string(finish_time) + ", ";
str += "deadline=" + std::to_string(task_info.deadline) + ", ";
str += "runtime=" + std::to_string(task_info.run_time) + ", ";
str += "blocktime=" + std::to_string(task_info.block_time) + ", ";
str += "switches=" + std::to_string(num_context_switches) + ", ";
str += "bursts=" + std::to_string(num_bursts);
return str;
}
| 23.266892 | 101 | 0.643676 | [
"object"
] |
b7605558d7dde3b27fc16987eddb8d9753bba421 | 9,926 | cpp | C++ | examples/example-ms2-ms1-matching.cpp | mkirchner/libfbi | 5a70ad70f38b4a9b9000610219e22ccaac7e3f5e | [
"MIT"
] | 6 | 2016-12-01T13:04:07.000Z | 2021-01-29T16:39:23.000Z | examples/example-ms2-ms1-matching.cpp | mkirchner/libfbi | 5a70ad70f38b4a9b9000610219e22ccaac7e3f5e | [
"MIT"
] | 3 | 2018-01-18T11:46:05.000Z | 2021-01-29T16:49:38.000Z | examples/example-ms2-ms1-matching.cpp | mkirchner/libfbi | 5a70ad70f38b4a9b9000610219e22ccaac7e3f5e | [
"MIT"
] | 5 | 2015-12-04T08:32:19.000Z | 2020-03-03T08:43:24.000Z | /*
* example-ms2-ms1-matching.cpp
*
* Copyright (c) 2010 Marc Kirchner <marc.kirchner@childrens.harvard.edu>
* Copyright (c) 2010 Buote Xu <buote.xu@gmail.com>
*
* This file is part of libfbi.
*
* 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/program_options.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "fbi/tuple.h"
#include "fbi/tuplegenerator.h"
#include "fbi/fbi.h"
#include "fbi/connectedcomponents.h"
/*
* User classes
*/
struct Xic
{
double rt_;
double mz_;
double abundance_;
Xic(const double &rt, const double& mz, const double & abundance)
: rt_(rt), mz_(mz), abundance_(abundance) {}
};
struct MS2Scan
{
double rt_;
double mz_;
typedef std::vector<std::pair<double, double> > Ions;
Ions ions_;
MS2Scan(const double &rt, const double& mz, const Ions& ions)
: rt_(rt), mz_(mz), ions_(ions) {}
};
/*
* Type traits info for libfbi
*/
namespace fbi {
template<> struct Traits<Xic> : mpl::TraitsGenerator<double, double> {};
template<> struct Traits<MS2Scan> : mpl::TraitsGenerator<double, double> {};
}
/*
* Xic adapters
*/
struct XicBoxGenerator
{
template <std::size_t N>
typename fbi::tuple_element<N,
typename fbi::Traits<Xic>::key_type>::type
get(const Xic &) const;
double fullScanPpm_;
double rtWindow_;
XicBoxGenerator(double fullScanPpm, double rtWindow)
: fullScanPpm_(fullScanPpm), rtWindow_(rtWindow)
{}
};
template <>
std::pair<double, double>
XicBoxGenerator::get<0>(const Xic& xic) const
{
return std::make_pair(
xic.mz_* (1 - fullScanPpm_ * 1E-6),
xic.mz_* (1 + fullScanPpm_ * 1E-6));
}
template <>
std::pair<double, double>
XicBoxGenerator::get<1>(const Xic & xic) const
{
return std::make_pair(xic.rt_ - rtWindow_, xic.rt_ + rtWindow_);
}
/*
* MS2Scan classes and adapters
*/
struct MS2ScanBoxGenerator
{
template <std::size_t N>
typename fbi::tuple_element<N,
typename fbi::Traits<MS2Scan>::key_type>::type
get(const MS2Scan &) const;
double preScanPpm_;
double rtWindow_;
MS2ScanBoxGenerator(double preScanPpm, double rtWindow)
: preScanPpm_(preScanPpm), rtWindow_(rtWindow)
{}
};
template <>
std::pair<double, double>
MS2ScanBoxGenerator::get<0>(const MS2Scan& ms2scan) const
{
return std::make_pair(
ms2scan.mz_* (1 - preScanPpm_ * 1E-6),
ms2scan.mz_* (1 + preScanPpm_ * 1E-6));
}
template <>
std::pair<double, double>
MS2ScanBoxGenerator::get<1>(const MS2Scan & ms2scan) const
{
return std::make_pair(ms2scan.rt_ - rtWindow_, ms2scan.rt_ + rtWindow_);
}
/*
* store and process user options
*/
struct ProgramOptions
{
double prescanPpm_;
double fullscanPpm_;
double rtWindow_;
std::string xicFileName_;
std::string ms2scanFileName_;
std::string outputFileName_;
};
int parseProgramOptions(int argc, char* argv[], ProgramOptions& options)
{
namespace po = boost::program_options;
std::string config_file;
double pres, fres;
po::options_description generic("Generic options");
generic.add_options()
("help", "Display this help message")
("config,c", po::value<std::string>(&config_file), "config file")
("xicfile,x", po::value<std::string>(&options.xicFileName_), "input file")
("ms2scanfile,m", po::value<std::string>(&options.ms2scanFileName_), "input file")
("outputfile,o", po::value<std::string>(&options.outputFileName_), "output file")
;
po::options_description config("Allowed options");
config.add_options()
("pr", po::value<double>(&pres)->default_value(7500.0),
"The resolution of the prescan.")
("fr", po::value<double>(&fres)->default_value(60000.0),
"The resolution of the full MS1 parent scan.")
("rt", po::value<double>(&options.rtWindow_)->default_value(60.0),
"The size of the retention time search window (in s).");
po::options_description cmdline_options("Options available via command line");
cmdline_options.add(generic).add(config);
po::options_description config_file_options(
"Options available in the config file");
config_file_options.add(config);
po::options_description visible("Allowed options");
visible.add(generic).add(config);
po::positional_options_description p;
p.add("xicfile", 1);
p.add("ms2scanfile", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(
cmdline_options).positional(p).run(), vm);
po::notify(vm);
if (vm.count("config")){
std::ifstream ifs(config_file.c_str());
if (!ifs) {
std::cout << "can't open config file: " << config_file << '\n';
return -1;
} else {
std::cerr << "Using config file" << config_file << '\n';
po::store(po::parse_config_file(ifs, config_file_options), vm);
po::notify(vm);
}
}
if (vm.count("help")) {
std::cout << visible << "\n";
return -1;
}
if (vm.count("xicfile")) {
std::cerr << "xicfile: " <<
options.xicFileName_ << '\n';
} else {
std::cerr << "XIC file required." << '\n';
std::cout << visible << '\n';
return -1;
}
if (vm.count("ms2scanfile")) {
std::cerr << "ms2scanfile: " <<
options.ms2scanFileName_ << '\n';
} else {
std::cerr << "MS2 input file required." << '\n';
std::cout << visible << '\n';
return -1;
}
if (vm.count("outputfile")) {
std::cerr << "outputfile: " <<
options.outputFileName_ << '\n';
} else {
options.outputFileName_ = options.xicFileName_ + std::string(".out");
std::cerr << "outputfile: " <<
options.outputFileName_ << '\n';
}
options.prescanPpm_ = 1e6 / (pres * (2*std::sqrt(2*std::log(2.0))));
options.fullscanPpm_ = 1e6 / (fres * (2*std::sqrt(2*std::log(2.0))));
return 0;
}
/*
* load xics from file
*/
std::vector<Xic> parseXicFile(ProgramOptions& options)
{
std::vector<Xic> xics;
std::ifstream ifs(options.xicFileName_.c_str());
ifs.setf(std::ios::fixed, std::ios::floatfield);
double mz, rt, abundance;
while (ifs >> rt >> mz >> abundance) {
xics.push_back(Xic(rt, mz, abundance));
}
return xics;
}
/*
* load MS2 scans from file
*/
std::vector<MS2Scan> parseMS2ScanFile(ProgramOptions & options)
{
std::vector<MS2Scan> ms2scans;
std::ifstream ifs(options.ms2scanFileName_.c_str());
ifs.setf(std::ios::fixed, std::ios::floatfield);
double mz, rt;
while (ifs >> rt >> mz) {
MS2Scan::Ions ions;
ms2scans.push_back(MS2Scan(rt, mz, ions));
}
return ms2scans;
}
int main(int argc, char* argv[])
{
using namespace fbi;
using namespace boost::posix_time;
ProgramOptions options;
if (parseProgramOptions(argc, argv, options) != 0) {
return -1;
}
// load data
std::vector<Xic> xics = parseXicFile(options);
std::vector<MS2Scan> ms2scans = parseMS2ScanFile(options);
// std::cerr << "# xics: " << xics.size() << std::endl;
// std::cerr << "# ms2scans: " << ms2scans.size() << std::endl;
ptime start = microsec_clock::universal_time();
SetA<Xic,0,1>::ResultType adjList = SetA<Xic, 0, 1>::SetB<MS2Scan, 0, 1>::intersect(
xics, XicBoxGenerator(options.fullscanPpm_, options.rtWindow_),
ms2scans, MS2ScanBoxGenerator(options.prescanPpm_, options.rtWindow_));
ptime end = microsec_clock::universal_time();
time_duration td = end - start;
std::cout << "fbi elapsed run time: "
<< td.total_seconds() << '\n';
// std::cerr << "size of adjecency list: " << adjList.size() << std::endl;
std::ofstream ofs(options.outputFileName_.c_str());
ofs.setf(std::ios::fixed, std::ios::floatfield);
std::size_t nXics = xics.size();
for (std::size_t i = 0; i < nXics; ++i) {
if (!adjList[i].empty()) {
typedef SetA<Xic,0,1>::ResultType::value_type ListType;
typedef ListType::const_iterator SI;
SI best = adjList[i].begin();
double bestDist = std::numeric_limits<double>::max();
// resolve conflict by choosing the closest m/z
for (SI j = adjList[i].begin(); j != adjList[i].end(); ++j) {
std::size_t k = *j - nXics;
double dist = std::abs(xics[i].mz_ - ms2scans[k].mz_);
// std::cerr << "d(" << xics[i].mz_ << "[" << i << "],"
// << ms2scans[k].mz_ << "[" << k << "]) = " << dist << std::endl;
if (dist < bestDist) {
best = j;
bestDist = dist;
}
}
// print the pair (current precursor -> new precursor)
std::size_t k = *best - nXics;
ofs << xics[i].mz_ << '\t' << xics[i].rt_
<< "\t->\t" << ms2scans[k].mz_ << '\t' << ms2scans[k].rt_ << '\n';
}
}
return 0;
}
| 29.108504 | 88 | 0.636006 | [
"vector"
] |
b76504235829ee3348bf992b21476f745a84bf45 | 3,798 | cc | C++ | GeneratorInterface/GenFilters/src/PythiaDauFilter.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | GeneratorInterface/GenFilters/src/PythiaDauFilter.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | GeneratorInterface/GenFilters/src/PythiaDauFilter.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null |
#include "GeneratorInterface/GenFilters/interface/PythiaDauFilter.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "HepMC/PythiaWrapper6_4.h"
#include <iostream>
using namespace edm;
using namespace std;
PythiaDauFilter::PythiaDauFilter(const edm::ParameterSet& iConfig) :
token_(consumes<edm::HepMCProduct>(edm::InputTag(iConfig.getUntrackedParameter("moduleLabel",std::string("generator")),"unsmeared"))),
particleID(iConfig.getUntrackedParameter("ParticleID", 0)),
chargeconju(iConfig.getUntrackedParameter("ChargeConjugation", true)),
ndaughters(iConfig.getUntrackedParameter("NumberDaughters", 0)),
minptcut(iConfig.getUntrackedParameter("MinPt", 0.)),
maxptcut(iConfig.getUntrackedParameter("MaxPt", 14000.)),
minetacut(iConfig.getUntrackedParameter("MinEta", -10.)),
maxetacut(iConfig.getUntrackedParameter("MaxEta", 10.))
{
//now do what ever initialization is needed
vector<int> defdauID;
defdauID.push_back(0);
dauIDs = iConfig.getUntrackedParameter< vector<int> >("DaughterIDs",defdauID);
}
PythiaDauFilter::~PythiaDauFilter()
{
// do anything here that needs to be done at desctruction time
// (e.g. close files, deallocate resources etc.)
}
//
// member functions
//
// ------------ method called to produce the data ------------
bool PythiaDauFilter::filter(edm::Event& iEvent, const edm::EventSetup& iSetup)
{
using namespace edm;
bool accepted = false;
Handle<HepMCProduct> evt;
iEvent.getByToken(token_, evt);
const HepMC::GenEvent * myGenEvent = evt->GetEvent();
for ( HepMC::GenEvent::particle_const_iterator p = myGenEvent->particles_begin();
p != myGenEvent->particles_end(); ++p ) {
if( (*p)->pdg_id() != particleID ) continue ;
int ndauac = 0;
int ndau = 0;
if ( (*p)->end_vertex() ) {
for ( HepMC::GenVertex::particle_iterator
des=(*p)->end_vertex()->particles_begin(HepMC::children);
des != (*p)->end_vertex()->particles_end(HepMC::children);
++des ) {
++ndau;
for( unsigned int i=0; i<dauIDs.size(); ++i) {
if( (*des)->pdg_id() != dauIDs[i] ) continue ;
if( (*des)->momentum().perp() > minptcut &&
(*des)->momentum().perp() < maxptcut &&
(*des)->momentum().eta() > minetacut &&
(*des)->momentum().eta() < maxetacut ) {
++ndauac;
break;
}
}
}
}
if( ndau == ndaughters && ndauac == ndaughters ) {
accepted = true;
break;
}
}
if( !accepted && chargeconju ) {
for ( HepMC::GenEvent::particle_const_iterator p = myGenEvent->particles_begin();
p != myGenEvent->particles_end(); ++p ) {
if( (*p)->pdg_id() != -particleID ) continue ;
int ndauac = 0;
int ndau = 0;
if ( (*p)->end_vertex() ) {
for ( HepMC::GenVertex::particle_iterator
des=(*p)->end_vertex()->particles_begin(HepMC::children);
des != (*p)->end_vertex()->particles_end(HepMC::children);
++des ) {
++ndau;
for( unsigned int i=0; i<dauIDs.size(); ++i) {
int IDanti = -dauIDs[i];
int pythiaCode = PYCOMP(dauIDs[i]);
int has_antipart = pydat2.kchg[3-1][pythiaCode-1];
if( has_antipart == 0 ) IDanti = dauIDs[i];
if( (*des)->pdg_id() != IDanti ) continue ;
if( (*des)->momentum().perp() > minptcut &&
(*des)->momentum().perp() < maxptcut &&
(*des)->momentum().eta() > minetacut &&
(*des)->momentum().eta() < maxetacut ) {
++ndauac;
break;
}
}
}
}
if( ndau == ndaughters && ndauac == ndaughters ) {
accepted = true;
break;
}
}
}
if (accepted){
return true; } else {return false;}
}
| 29.671875 | 134 | 0.603739 | [
"vector"
] |
b76a2bf3b4888983b2547c0fcb611f1e8ef14dac | 3,338 | cc | C++ | onnxruntime/core/providers/armnn/activation/activations.cc | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 2 | 2021-07-24T01:13:36.000Z | 2021-11-17T11:03:52.000Z | onnxruntime/core/providers/armnn/activation/activations.cc | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 4 | 2020-12-04T21:00:38.000Z | 2022-01-22T12:49:30.000Z | onnxruntime/core/providers/armnn/activation/activations.cc | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 1 | 2020-06-08T19:08:12.000Z | 2020-06-08T19:08:12.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) 2020, NXP Semiconductor, Inc. All rights reserved.
// Licensed under the MIT License
#ifdef RELU_ARMNN
#ifdef _WIN32
#pragma warning(disable : 4244)
#endif
#include "core/providers/armnn/armnn_common.h"
#include "core/providers/armnn/activation/activations.h"
#include "core/providers/armnn/armnn_fwd.h"
namespace onnxruntime {
namespace armnn_ep {
template <typename T>
thread_local std::map<OpKernel*, armnn::NetworkId> Relu<T>::reluLayers;
template <typename T>
armnn::IRuntimePtr Relu<T>::run = Relu<T>::initRuntime();
template <typename T>
Status Relu<T>::Compute(OpKernelContext* context) const {
const Tensor* X = context->Input<Tensor>(0);
Tensor* Y = context->Output(0, X->Shape());
const T* src_data = X->template Data<T>();
T* dst_data = Y->template MutableData<T>();
armnn::NetworkId* pNetworkId;
ReluLayersIterator it = Relu::reluLayers.find((OpKernel*)this);
if (it == Relu::reluLayers.end()) {
armnn::NetworkId networkId;
armnn::INetworkPtr myNetwork = armnn::INetwork::Create();
armnn::TensorShape inputShape = ArmNNTensorShape(X->Shape());
armnn::TensorShape outputShape = ArmNNTensorShape(Y->Shape());
armnn::ActivationDescriptor desc;
desc.m_Function = armnn::ActivationFunction::ReLu;
armnn::IConnectableLayer* activation = myNetwork->AddActivationLayer(desc, "relu_armnn");
armnn::IConnectableLayer *InputLayer = myNetwork->AddInputLayer(0);
armnn::IConnectableLayer *OutputLayer = myNetwork->AddOutputLayer(0);
InputLayer->GetOutputSlot(0).Connect(activation->GetInputSlot(0));
activation->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));
//Set the tensors in the network.
armnn::TensorInfo inputTensorInfo(inputShape, armnn::DataType::Float32);
InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);
armnn::TensorInfo outputTensorInfo(outputShape, armnn::DataType::Float32);
activation->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
// Optimise ArmNN network
armnn::IOptimizedNetworkPtr optNet = armnn::Optimize(*myNetwork, {armnn::Compute::CpuAcc}, Relu::run->GetDeviceSpec());
if (optNet == nullptr) {
ORT_NOT_IMPLEMENTED("Something went wrong when creating the layer");
}
// Load graph into runtime
Relu::run->LoadNetwork(networkId, std::move(optNet));
std::pair<ReluLayersIterator, bool> ret;
ret = Relu::reluLayers.insert(std::pair<OpKernel*, armnn::NetworkId>((OpKernel*)this, networkId));
pNetworkId = &ret.first->second;
} else {
pNetworkId = &it->second;
}
armnn::InputTensors inputTensors{{0, armnn::ConstTensor(Relu::run->GetInputTensorInfo(*pNetworkId, 0),
src_data)}};
armnn::OutputTensors outputTensors{{0, armnn::Tensor(Relu::run->GetOutputTensorInfo(*pNetworkId, 0),
dst_data)}};
Relu::run->EnqueueWorkload(*pNetworkId, inputTensors, outputTensors);
return Status::OK();
}
ONNX_OPERATOR_KERNEL_EX(
Relu,
kOnnxDomain,
6,
kArmNNExecutionProvider,
KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
Relu<float>);
} // namespace armnn_ep
} // namespace onnxruntime
#endif
| 33.049505 | 123 | 0.699221 | [
"shape"
] |
b76a657acd76e3c7c40ea4126a72875ae12ccdbe | 7,128 | cpp | C++ | src/visitor/AvoidParamMismatchVisitor.cpp | moritzwinger/ABC | 2d1f507dc7188b13767cce8050b8aa9daa7c1625 | [
"MIT"
] | null | null | null | src/visitor/AvoidParamMismatchVisitor.cpp | moritzwinger/ABC | 2d1f507dc7188b13767cce8050b8aa9daa7c1625 | [
"MIT"
] | null | null | null | src/visitor/AvoidParamMismatchVisitor.cpp | moritzwinger/ABC | 2d1f507dc7188b13767cce8050b8aa9daa7c1625 | [
"MIT"
] | null | null | null | #include "ast_opt/ast/AbstractNode.h"
#include "ast_opt/ast/Literal.h"
#include "ast_opt/visitor/IdentifyNoisySubtreeVisitor.h"
#include "ast_opt/visitor/AvoidParamMismatchVisitor.h"
#include <utility>
#include "ast_opt/ast/AbstractExpression.h"
SpecialAvoidParamMismatchVisitor::SpecialAvoidParamMismatchVisitor(std::unordered_map<std::string,
std::vector<seal::Modulus>> coeffmodulusmap,
std::unordered_map<std::string, std::vector<seal::Modulus>> coeffmodulusmap_vars)
: coeffmodulusmap(std::move(coeffmodulusmap)), coeffmodulusmap_vars(std::move(coeffmodulusmap_vars)){}
void SpecialAvoidParamMismatchVisitor::visit(BinaryExpression &elem) {
// if binary expression's left child has children and has not been visited yet recurse into it
if (elem.hasLeft() && (elem.getLeft().begin()!=elem.getLeft().end())
&& (!isVisited[elem.getLeft().getUniqueNodeId()] || isVisited.count(elem.getLeft().getUniqueNodeId())==0)) {
elem.getLeft().accept(*this);
}
// same for right
if (elem.hasRight() && (elem.getRight().begin()!=elem.getRight().end())
&& (!isVisited[elem.getRight().getUniqueNodeId()] || isVisited.count(elem.getRight().getUniqueNodeId())==0)) {
elem.getRight().accept(*this);
}
// base case
else {
// set to 'visited'
isVisited[elem.getUniqueNodeId()] = true;
// check if modswitches need to be inserted and how many
// first we check if the operands left and right are binary expressions or variables to avoid bad casting and look up in the corresponding map
int leftindex;
int rightindex;
if (dynamic_cast<Variable *>(&elem.getLeft())) {
leftindex = coeffmodulusmap_vars[dynamic_cast<Variable &>(elem.getLeft()).getIdentifier()].size();
} else if (!dynamic_cast<Variable *>(&elem.getLeft())) {
leftindex = coeffmodulusmap[elem.getLeft().getUniqueNodeId()].size();
}
if (dynamic_cast<Variable *>(&elem.getRight())) {
rightindex = coeffmodulusmap_vars[dynamic_cast<Variable &>(elem.getRight()).getIdentifier()].size();
} else if (!dynamic_cast<Variable *>(&elem.getRight())) {
rightindex = coeffmodulusmap[elem.getRight().getUniqueNodeId()].size();
}
int diff = leftindex - rightindex;
// if not, return
if (diff==0) { return; }
else {
modSwitchNodes.push_back(&elem);
return;
}
}
}
std::unique_ptr<AbstractNode> SpecialAvoidParamMismatchVisitor::insertModSwitchInAst(std::unique_ptr<AbstractNode> *ast, BinaryExpression *binaryExpression) {
// if no binary expression specified return original ast
if (binaryExpression == nullptr) {return std::move(*ast);}
// prepare argument for 'Call' node (modswitch)
// we need to know how many modswitches to insert (will be second arg to ModSwitch call)
int leftIndex;
int rightIndex;
if (dynamic_cast<Variable *>(&binaryExpression->getLeft())) {
leftIndex = coeffmodulusmap_vars[dynamic_cast<Variable &>(binaryExpression->getLeft()).getIdentifier()].size();
}
else if (!dynamic_cast<Variable *>(&binaryExpression->getLeft())) {
leftIndex = coeffmodulusmap[binaryExpression->getLeft().getUniqueNodeId()].size();
}
if (dynamic_cast<Variable *>(&binaryExpression->getRight())) {
rightIndex = coeffmodulusmap_vars[dynamic_cast<Variable &>(binaryExpression->getRight()).getIdentifier()].size();
}
else if (!dynamic_cast<Variable *>(&binaryExpression->getRight())) {
rightIndex = coeffmodulusmap[binaryExpression->getRight().getUniqueNodeId()].size();
}
std:: cout << "Index of " << binaryExpression->getLeft().toString(false) << ": " << leftIndex << std::endl;
std:: cout << "Index of " << binaryExpression->getRight().toString(false) << ": " << rightIndex << std::endl;
int diff = leftIndex - rightIndex;
// Note: only apply modswitches to var with more primes
// if diff > 0, then the left side has more primes: need to switch left side only
// get the result variable to update the coeffmodulusmap_vars for:
std::cout << "Casting" << binaryExpression->getParent().toString(false) << std::endl;
VariableDeclaration& vd = dynamic_cast<VariableDeclaration &>(binaryExpression->getParent());
AbstractTarget& at = vd.getTarget();
Variable& v = dynamic_cast<Variable&>(at);
std::string ident = v.getIdentifier();
std::cout << "Result of the bin expr " << binaryExpression->toString(false) << " is: " << ident << std::endl;
if (diff > 0) {
// update coeffmodulus maps
for (int i = 0; i < abs(diff); i++) {
coeffmodulusmap[binaryExpression->getUniqueNodeId()].pop_back();
if (dynamic_cast<Variable *>(&binaryExpression->getLeft())) {
coeffmodulusmap_vars[dynamic_cast<Variable &>(binaryExpression->getLeft()).getIdentifier()].pop_back();
}
else if (!dynamic_cast<Variable *>(&binaryExpression->getLeft())){
coeffmodulusmap[binaryExpression->getLeft().getUniqueNodeId()].pop_back();
}
// update result index
coeffmodulusmap_vars[ident].pop_back();
}
// insert appropriate number of modswitches after left var
auto leftNumModSw = std::make_unique<LiteralInt>(abs(diff));
auto l = binaryExpression->takeLeft();
std::vector<std::unique_ptr<AbstractExpression>> vLeft;
vLeft.emplace_back(std::move(l));
vLeft.emplace_back(std::move(leftNumModSw));
auto cLeft = std::make_unique<Call>("modswitch", std::move(vLeft));
cLeft->setParent(binaryExpression);
binaryExpression->setLeft(std::move(cLeft));
}
else if(diff < 0) {
// update coeffmodulus maps
for (int i = 0; i < abs(diff); i++) {
coeffmodulusmap[binaryExpression->getUniqueNodeId()].pop_back();
if (dynamic_cast<Variable *>(&binaryExpression->getRight())) {
coeffmodulusmap_vars[dynamic_cast<Variable &>(binaryExpression->getRight()).getIdentifier()].pop_back();
}
else if (!dynamic_cast<Variable *>(&binaryExpression->getRight())) {
coeffmodulusmap[binaryExpression->getRight().getUniqueNodeId()].pop_back();
}
coeffmodulusmap_vars[ident].pop_back();
}
// insert appropriate number of modswitches after right var
auto rightNumModSw = std::make_unique<LiteralInt>(abs(diff));
auto r = binaryExpression->takeRight();
std::vector<std::unique_ptr<AbstractExpression>> vRight;
vRight.emplace_back(std::move(r));
vRight.emplace_back(std::move(rightNumModSw));
auto cRight = std::make_unique<Call>("modswitch", std::move(vRight));
cRight->setParent(binaryExpression);
binaryExpression->setRight(std::move(cRight));
}
return (std::move(*ast));
}
std::vector<BinaryExpression *> SpecialAvoidParamMismatchVisitor::getModSwitchNodes() {
return modSwitchNodes;
}
std::unordered_map<std::string, std::vector<seal::Modulus>> SpecialAvoidParamMismatchVisitor::getCoeffModulusMap() {
return coeffmodulusmap;
}
std::unordered_map<std::string, std::vector<seal::Modulus>> SpecialAvoidParamMismatchVisitor::getCoeffModulusMapVars() {
return coeffmodulusmap_vars;
};
| 45.987097 | 159 | 0.690657 | [
"vector"
] |
b7768711850341b0d117c387099d7c35c057d4c6 | 1,303 | cpp | C++ | acmicpc/14502.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/14502.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/14502.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <vector>
using namespace std;
int map[8][8];
int tmp[8][8];
int a[4] = {0, 1, 0, -1};
int b[4] = {1, 0, -1, 0};
int n, m;
void dfs(int x, int y)
{
tmp[x][y] = 2;
for (int i=0; i<4; ++i) {
int next_x = x + a[i];
int next_y = y + b[i];
if (next_x < 0 || next_y < 0 || next_x >= n || next_y >= m)
continue;
if (tmp[next_x][next_y] == 0)
dfs(next_x, next_y);
}
}
int main()
{
vector<pair<int, int>> wall;
int len, cnt, max_val = 0;
scanf("%d %d", &n, &m);
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
scanf("%d", &map[i][j]);
tmp[i][j] = map[i][j];
if (map[i][j] == 0)
wall.push_back({i, j});
}
}
len = wall.size();
for (int i=0; i<len-2; ++i) {
for (int j=i+1; j<len-1; ++j) {
for (int k=j+1; k<len; ++k) {
pair<int, int> w[3] = {wall[i], wall[j], wall[k]};
cnt = 0;
for (int x=0; x<n; ++x)
for (int y=0; y<m; ++y)
tmp[x][y] = map[x][y];
for (int x=0; x<3; ++x)
tmp[w[x].first][w[x].second] = 1;
for (int x=0; x<n; ++x)
for (int y=0; y<m; ++y)
if (tmp[x][y] == 2)
dfs(x, y);
for (int x=0; x<n; ++x)
for (int y=0; y<m; ++y)
if (tmp[x][y] == 0)
cnt++;
max_val = max(max_val, cnt);
}
}
}
printf("%d\n", max_val);
return 0;
}
| 17.608108 | 61 | 0.450499 | [
"vector"
] |
b77bfb548cd13ed058dbeadd23edb5c185c0b3e3 | 6,483 | cpp | C++ | flappy/envs/fwmav/pydart2/pydart2_dof_api.cpp | ArbalestV/flappy | 9e715cacc842fab6b9dfd4d6f0f7fb65b769204f | [
"MIT"
] | 1 | 2021-02-03T16:38:03.000Z | 2021-02-03T16:38:03.000Z | flappy/envs/fwmav/pydart2/pydart2_dof_api.cpp | ArbalestV/flappy | 9e715cacc842fab6b9dfd4d6f0f7fb65b769204f | [
"MIT"
] | null | null | null | flappy/envs/fwmav/pydart2/pydart2_dof_api.cpp | ArbalestV/flappy | 9e715cacc842fab6b9dfd4d6f0f7fb65b769204f | [
"MIT"
] | 1 | 2019-10-21T23:14:10.000Z | 2019-10-21T23:14:10.000Z | #include <iostream>
#include <string>
#include <vector>
#include <map>
using std::cout;
using std::cerr;
using std::endl;
// Boost headers
#include <boost/algorithm/string.hpp>
#include "pydart2_manager.h"
#include "pydart2_api.h"
#include "pydart2_dof_api.h"
#include "pydart2_draw.h"
using namespace pydart;
////////////////////////////////////////////////////////////////////////////////
// DegreeOfFreedom
const char* DOF(getName)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getName().c_str();
}
////////////////////////////////////////
// Dof::Index Functions
int DOF(getIndexInSkeleton)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getIndexInSkeleton();
}
int DOF(getIndexInTree)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getIndexInTree();
}
int DOF(getIndexInJoint)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getIndexInJoint();
}
int DOF(getTreeIndex)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getTreeIndex();
}
////////////////////////////////////////
// Dof::Position Functions
double DOF(getPosition)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getPosition();
}
void DOF(setPosition)(int wid, int skid, int dofid, double _position) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setPosition(_position);
}
double DOF(getInitialPosition)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getInitialPosition();
}
void DOF(setInitialPosition)(int wid, int skid, int dofid, double _initial) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setInitialPosition(_initial);
}
bool DOF(hasPositionLimit)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->hasPositionLimit();
}
double DOF(getPositionLowerLimit)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getPositionLowerLimit();
}
void DOF(setPositionLowerLimit)(int wid, int skid, int dofid, double _limit) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setPositionLowerLimit(_limit);
}
double DOF(getPositionUpperLimit)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getPositionUpperLimit();
}
void DOF(setPositionUpperLimit)(int wid, int skid, int dofid, double _limit) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setPositionUpperLimit(_limit);
}
////////////////////////////////////////
// Dof::Velocity Functions
double DOF(getVelocity)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getVelocity();
}
void DOF(setVelocity)(int wid, int skid, int dofid, double _velocity) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setVelocity(_velocity);
}
double DOF(getInitialVelocity)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getInitialVelocity();
}
void DOF(setInitialVelocity)(int wid, int skid, int dofid, double _initial) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setInitialVelocity(_initial);
}
double DOF(getVelocityLowerLimit)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getVelocityLowerLimit();
}
void DOF(setVelocityLowerLimit)(int wid, int skid, int dofid, double _limit) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setVelocityLowerLimit(_limit);
}
double DOF(getVelocityUpperLimit)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getVelocityUpperLimit();
}
void DOF(setVelocityUpperLimit)(int wid, int skid, int dofid, double _limit) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setVelocityUpperLimit(_limit);
}
////////////////////////////////////////
// Dof::Passive Force Functions
double DOF(getSpringStiffness)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getSpringStiffness();
}
void DOF(setSpringStiffness)(int wid, int skid, int dofid, double _k) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setSpringStiffness(_k);
}
double DOF(getRestPosition)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getRestPosition();
}
void DOF(setRestPosition)(int wid, int skid, int dofid, double _q0) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setRestPosition(_q0);
}
double DOF(getDampingCoefficient)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getDampingCoefficient();
}
void DOF(setDampingCoefficient)(int wid, int skid, int dofid, double _coeff) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setDampingCoefficient(_coeff);
}
double DOF(getCoulombFriction)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getCoulombFriction();
}
void DOF(setCoulombFriction)(int wid, int skid, int dofid, double _friction) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
dof->setCoulombFriction(_friction);
}
////////////////////////////////////////
// Dof::Passive Force Functions
double DOF(getConstraintImpulse)(int wid, int skid, int dofid) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->getConstraintImpulse();
}
void DOF(setConstraintImpulse)(int wid, int skid, int dofid, double _impulse) {
dart::dynamics::DegreeOfFreedom* dof = GET_DOF(wid, skid, dofid);
return dof->setConstraintImpulse(_impulse);
}
| 29.60274 | 80 | 0.681166 | [
"vector"
] |
b78a42afc2de3ee816db46e8354c098a3ef496e7 | 9,987 | cpp | C++ | AI.cpp | VukanJ/Chess | 802f223985be9890fe02ae1da2ad90708cee5d6e | [
"MIT"
] | null | null | null | AI.cpp | VukanJ/Chess | 802f223985be9890fe02ae1da2ad90708cee5d6e | [
"MIT"
] | null | null | null | AI.cpp | VukanJ/Chess | 802f223985be9890fe02ae1da2ad90708cee5d6e | [
"MIT"
] | null | null | null | #include "AI.h"
AI::AI(string FEN, color computerColor)
: aiColor(computerColor), nodesVisited(0),
currentAge(0)
{
genChessData data;
data.genMoveData(); // Generates bitboards needed for move generation
board.setupBoard(FEN);
transpositionHash = ZobristHash(static_cast<size_t>(1e7));
}
AI::AI(string FEN, color computerColor, uint hashSize)
: aiColor(computerColor)
{
genChessData data;
data.genMoveData(); // Generates bitboards needed for move generation
board.setupBoard(FEN);
transpositionHash = ZobristHash(hashSize);
}
void AI::printBoard()
{
board.print();
}
/*
string AI::boardToString() const
{
string board = string(64, '_');
int c = 0;
for (auto p : board.pieces) {
for_bits(pos, p) {
board[63 - pos] = names[c];
}
c++;
}
return board;
}
void AI::writeToHistory(const Move& move)
{
gameHistory.push_back(pair<string, Move>(boardToString(), move));
}
*/
void AI::printDebug(string showPieces)
{
board.print();
for (auto p : showPieces){
auto drawPiece = getPieceIndex(p);
///printBitboard(chessBoard.pieces[drawPiece]);
///printBitboard(chessBoard.attacks[drawPiece]);
if (board.pieces[drawPiece])
printBitboardFigAttack(board.pieces[drawPiece], board.attacks[drawPiece], p);
}
}
pair<Move, Move> AI::getBestMove(color forPlayer, int maxDepth, bool uciInfo)
{
Timer timer, infoTimer;
timer.start();
Move bestMove, ponderMove;
vector<Move> pvLine;
for (targetDepth = 1; targetDepth <= maxDepth; targetDepth++) {
infoTimer.start();
NegaMax(-oo, oo, targetDepth, 0, forPlayer);
extractPrincipalVariation(board.hashKey, pvLine, targetDepth, forPlayer);
infoTimer.stop();
if (uciInfo) {
int val = transpositionHash.getValue(board.hashKey);
cout << "info depth " << targetDepth // Search depth
<< " score cp " << val; // Score of computer
if (abs(val) > 10000) {
cout << " mate " << oo - abs(val);
}
cout << " nodes " << nodesVisited // Total visited nodes
<< " nps " << (int)((double)nodesVisited / (infoTimer.getTime()*1e-6)) // Nodes per second
<< " time " << infoTimer.getTime()*1e-3 // Computation time in milliseconds
<< " pv "; // Principal variation of specified depth
for (const auto& move : pvLine) cout << move << ' ';
cout << '\n';
nodesVisited = 0;
}
bestMove = pvLine[0];
if(targetDepth > 1 && pvLine.size() > 1)
ponderMove = pvLine[1];
pvLine.clear();
}
timer.stop();
return pair<Move, Move> (bestMove, ponderMove);
}
int AI::NegaMax(int alpha, int beta, int depth, int ply, color side)
{
// 4Rnk1/pr3ppp/1p3q2/5NQ1/2p5/8/P4PPP/6K1 w - - 1 0
// Consistency check:
// The following FEN should be recognized as Zugzwang. Search should converge after 5 half-moves
// r4r1k/1pqb1B1p/p3p2B/2bpP2Q/8/1NP5/PP4PP/5R1K w - - 1 0
int oldAlpha = alpha;
auto &entry = transpositionHash.getEntry(board.hashKey);
nodesVisited++;
// Check if move was already evaluated
if (entry.terminal == 1) {
// Checkmate / Stalemate
return entry.value;
}
if (entry.search_depth >= depth) {
if (entry.flags & EXACT_VALUE) {
return entry.value;
}
else if (entry.flags & LOWER_BOUND) {
alpha = max(alpha, entry.value);
}
else if (entry.flags & UPPER_BOUND) {
beta = min(beta, entry.value);
}
if (alpha >= beta) {
return entry.value;
}
}
if (depth == 0) {
// Evaluate board & reduce Horizon-Effekt
return QuiescenceSearch(alpha, beta, side);
}
MoveList movelist;
board.updateAllAttacks();
board.generateMoveList<ALL>(movelist, side);
sortMoves(movelist, side);
bool checkedOnThisDepth = board.wasInCheck;
U64 pinnedOnThisDepth = board.pinned;
int legalMoves = 0, score = 0;
Move bestMove;
// Get first best move (estimate)
int visited = 0;
MoveList::iterator move = movelist.begin();
for(auto& move : movelist){
board.makeMove<FULL>(move, side);
if (board.isKingLeftInCheck(side, move, checkedOnThisDepth, pinnedOnThisDepth)) {
board.unMakeMove<FULL>(move, side);
// Get next best move (estimate)
continue;
}
legalMoves++;
if (legalMoves > 4) {
score = -NegaMax(-beta, -alpha, min(4, depth - 1), ply + 1, !side);
}
else {
score = -NegaMax(-beta, -alpha, depth - 1, ply + 1, !side);
}
board.unMakeMove<FULL>(move, side);
if (score > alpha) {
if (score >= beta) {
return beta; // Beta Cutoff
}
alpha = score;
bestMove = move;
}
}
if (legalMoves == 0) {
// No legal moves found.
board.updateAllAttacks();
if ((side == white && board.pieces[wk] & board.blackAtt)
|| (side == black && board.pieces[bk] & board.whiteAtt)) {
// Checkmate, end of game path
entry.search_depth = depth;
entry.terminal = true;
score = -oo + ply;
return score;
}
else {
// Stalemate, end of game path
entry.search_depth = depth;
entry.terminal = true;
score = 0;
return 0;
}
}
if (alpha > oldAlpha) {
// Better move found
pvTable.addPVMove(board.hashKey, bestMove);
entry.value = alpha;
entry.search_depth = depth;
}
if (alpha < oldAlpha) {
entry.flags = UPPER_BOUND;
}
else if (alpha >= beta)
entry.flags = LOWER_BOUND;
else entry.flags = EXACT_VALUE;
return alpha;
}
template<bool firstVisit> void AI::getNextMove(MoveList& mlist, MoveList::iterator& current, color side)
{
int bestValue = -oo, oldBestValue = -oo;
MoveList::iterator move = current;
for (; move != mlist.end(); ++move) {
oldBestValue = bestValue;
if (firstVisit) {
board.makeMove<HASH>(*move, side);
auto& entry = transpositionHash.getEntry(board.hashKey);
board.unMakeMove<HASH>(*move, side);
if (entry.search_depth != -1) {
// I. PV + Hash moves:
bestValue = max(bestValue, entry.value);
}
else if (move->mtype() == CAPTURE) {
// II. Captures
bestValue = max(bestValue, captureScore[move->movePiece() % 6][move->targetPiece() % 6] - 100000);
}
else if (move->mtype() == PAWN2 || (move->mtype() == MOVE && move->movePiece() % 6 == 0)) {
// III. Pawn pushes
bestValue = max(bestValue, -1000000);
}
if (bestValue != oldBestValue) {
// Improvement
iter_swap(current, move);
}
}
else {
if (move->mtype() == CAPTURE) {
// II. Captures
bestValue = max(bestValue, captureScore[move->movePiece() % 6][move->targetPiece() % 6] - 100000);
}
else if (move->mtype() == PAWN2 || (move->mtype() == MOVE && move->movePiece() % 6 == 0)) {
// III. Pawn pushes
bestValue = max(bestValue, -1000000);
}
if (bestValue != oldBestValue) {
// Improvement
iter_swap(current, move);
}
}
}
}
void inline AI::sortMoves(MoveList& movelist, color side)
{
stable_sort(movelist.begin(), movelist.end(), [&, this](const Move& m1, const Move& m2) {
board.makeMove<HASH>(m1, side);
auto& e1 = transpositionHash.getEntry(board.hashKey);
board.unMakeMove<HASH>(m1, side);
board.makeMove<HASH>(m2, side);
auto& e2 = transpositionHash.getEntry(board.hashKey);
board.unMakeMove<HASH>(m2, side);
int val1 = 0, val2 = 0;
if (e1.search_depth != -1) {
val1 = e1.value;
}
else if(m1.mtype() == CAPTURE){
val1 = captureScore[m1.movePiece() % 6][m1.targetPiece() % 6] - 100000;
}
if (e2.search_depth != -1) {
val2 = e2.value;
}
else if (m2.mtype() == CAPTURE) {
val2 = captureScore[m2.movePiece() % 6][m2.targetPiece() % 6] - 100000;
}
return val1 < val2;
});
}
int AI::QuiescenceSearch(int alpha, int beta, color side)
{
// Plays all (relevant) captures from current position
// Reduces Horizon Effect
nodesVisited++;
int standingPat = board.evaluate(side);
if (standingPat >= beta)
return beta;
if (alpha < standingPat)
alpha = standingPat;
MoveList mlist;
board.updateAllAttacks();
board.generateMoveList<CAPTURES_ONLY>(mlist, side);
// MVA-LLV scheme (search best captures first)
stable_sort(mlist.begin(), mlist.end(), [](const Move& m1, const Move& m2) {
return captureScore[m1.movePiece() % 6][m1.targetPiece() % 6]
> captureScore[m2.movePiece() % 6][m2.targetPiece() % 6];
});
bool checkOnThisDepth = board.wasInCheck;
U64 pinnedOnThisDepth = board.pinned;
for (const auto& capture : mlist) {
board.makeMove<FULL>(capture, side);
if (board.isKingLeftInCheck(side, capture, checkOnThisDepth, pinnedOnThisDepth)) {
board.unMakeMove<FULL>(capture, side);
continue;
}
int score = -QuiescenceSearch(-beta, -alpha, !side);
board.unMakeMove<FULL>(capture, side);
if (score >= beta)
return beta;
if (score > alpha)
alpha = score;
}
return alpha;
}
void AI::extractPrincipalVariation(const U64& key, vector<Move>& pvLine, int maxPrintDepth, color side)
{
const auto& entry = pvTable[key];
if (maxPrintDepth == 0 || entry.bestmove.invalid()) return;
board.makeMove<FULL>(entry.bestmove, side);
pvLine.push_back(entry.bestmove);
extractPrincipalVariation(board.hashKey, pvLine, maxPrintDepth - 1, !side);
board.unMakeMove<FULL>(entry.bestmove, side);
}
void AI::reset()
{
// Time consuming. Only call when ucinewgame is passed to engine
transpositionHash.clear();
pvTable.clear();
board.setupBoard("*");
aiColor = black;
}
void AI::setFen(string fenstring)
{
board.setupBoard(fenstring);
}
void AI::printAscii()
{
board.print();
}
void AI::playStringMoves(const vector<string>& moves, color side)
{
board.playStringMoves(moves, side);
sideToMove = moves.size() % 2 == 0 ? sideToMove : !sideToMove;
}
void AI::resetHash()
{
// Only use when "ucinewgame" is passed
transpositionHash.clear();
pvTable.clear();
}
bool AI::isUserMoveValid(const string& usermove, color side)
{
MoveList possibleMoves;
board.generateMoveList<ALL>(possibleMoves, side);
return any_of(possibleMoves.begin(), possibleMoves.end(), [&, this](const Move& move) {
return shortNotation(move) == usermove;
}) ? true : false;
} | 27.138587 | 117 | 0.649745 | [
"vector"
] |
b78c00a3c43ff2dacb8475c1c6540e6125c69e66 | 6,293 | cpp | C++ | DEM/Src/L2/Game/Mgr/StaticEnvManager.cpp | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | 2 | 2017-04-30T20:24:29.000Z | 2019-02-12T08:36:26.000Z | DEM/Src/L2/Game/Mgr/StaticEnvManager.cpp | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | DEM/Src/L2/Game/Mgr/StaticEnvManager.cpp | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | #include "StaticEnvManager.h"
#include <Physics/Level.h>
#include <Physics/Event/SetTransform.h>
#include <Gfx/GfxServer.h>
#include <Gfx/ShapeEntity.h>
#include <Data/DataServer.h>
#include <Data/DataArray.h>
#include <Game/Mgr/EntityManager.h>
#include <DB/ValueTable.h>
namespace Attr
{
DeclareAttr(GUID);
DeclareAttr(Physics);
DeclareAttr(Graphics);
DeclareAttr(Transform);
DeclareAttr(AnimPath);
}
namespace Game
{
__ImplementClass(CStaticEnvManager, 'MENV', Game::CManager);
__ImplementSingleton(CStaticEnvManager);
using namespace Physics;
CStaticEnvManager::CStaticEnvManager()
{
__ConstructSingleton;
}
//---------------------------------------------------------------------
CStaticEnvManager::~CStaticEnvManager()
{
__DestructSingleton;
}
//---------------------------------------------------------------------
bool CStaticEnvManager::AddEnvObject(const DB::PValueTable& Table, int RowIdx)
{
n_assert(Table.isvalid());
n_assert(RowIdx != INVALID_INDEX);
// If the AnimPath attribute exists, create an animated entity
if (Table->Get<nString>(Attr::AnimPath, RowIdx).IsValid()) FAIL;
CEnvObject* pObj = NULL;
const matrix44& EntityTfm = Table->Get<matrix44>(Attr::Transform, RowIdx);
const nString& CompositeName = Table->Get<nString>(Attr::Physics, RowIdx);
if (CompositeName.IsValid())
{
PParams Desc = DataSrv->LoadPRM(nString("physics:") + CompositeName + ".prm");
int Idx = Desc->IndexOf(CStrID("Bodies"));
// If is not a pure collide object, load as a physics entity
if (Idx != INVALID_INDEX && Desc->Get<PDataArray>(Idx)->Size() > 0) FAIL;
Idx = Desc->IndexOf(CStrID("Shapes"));
if (Idx != INVALID_INDEX)
{
CDataArray& Shapes = *Desc->Get<PDataArray>(Idx);
if (Shapes.Size() > 0)
{
CStrID UID = Table->Get<CStrID>(Attr::GUID, RowIdx);
EnvObjects.Add(UID, CEnvObject()); //!!!unnecessary copying!
pObj = &EnvObjects[UID];
//InvEntityTfm.invert();
for (int i = 0; i < Shapes.Size(); i++)
{
PParams ShapeDesc = Shapes[i];
PShape pShape = (CShape*)CoreFct->Create("Physics::C" + ShapeDesc->Get<nString>(CStrID("Type")));
pShape->Init(ShapeDesc);
pObj->CollLocalTfm.Append(pShape->GetTransform());// * InvEntityTfm);
pShape->SetTransform(pShape->GetTransform() * EntityTfm);
pObj->Collision.Append(pShape);
PhysicsSrv->GetLevel()->AttachShape(pShape);
}
}
}
}
const nString& GfxResName = Table->Get<nString>(Attr::Graphics, RowIdx);
if (GfxResName.IsValid())
{
nArray<Graphics::PShapeEntity> GfxEntities;
GfxSrv->CreateGfxEntities(GfxResName, EntityTfm, GfxEntities);
if (GfxEntities.Size() > 0)
{
if (!pObj)
{
CStrID UID = Table->Get<CStrID>(Attr::GUID, RowIdx);
EnvObjects.Add(UID, CEnvObject()); //!!!unnecessary copying!
pObj = &EnvObjects[UID];
}
matrix44 InvEntityTfm = EntityTfm;
InvEntityTfm.invert();
for (int i = 0; i < GfxEntities.Size(); i++)
{
Graphics::PShapeEntity pEnt = GfxEntities[i];
pObj->Gfx.Append(pEnt);
pObj->GfxLocalTfm.Append(pEnt->GetTransform() * InvEntityTfm);
GfxSrv->GetLevel()->AttachEntity(pEnt);
}
}
}
OK;
}
//---------------------------------------------------------------------
bool CStaticEnvManager::EnvObjectExists(CStrID ID) const
{
n_assert(ID.IsValid());
return EnvObjects.Contains(ID) || EntityMgr->ExistsEntityByID(ID);
}
//---------------------------------------------------------------------
bool CStaticEnvManager::IsEntityStatic(CStrID ID) const
{
n_assert(ID.IsValid());
if (EnvObjects.Contains(ID)) OK;
CEntity* pEnt = EntityMgr->GetEntityByID(ID);
return pEnt ? IsEntityStatic(*pEnt) : false;
}
//---------------------------------------------------------------------
bool CStaticEnvManager::IsEntityStatic(CEntity& Entity) const
{
//!!!unnecessary data copying!
nString Value;
if (Entity.Get<nString>(Attr::AnimPath, Value) && Value.IsValid()) FAIL;
if (Entity.Get<nString>(Attr::Physics, Value) && Value.IsValid())
{
// It uses HRD cache, so it isn't so slow
PParams Desc = DataSrv->LoadPRM(nString("physics:") + Value + ".prm");
int Idx = Desc->IndexOf(CStrID("Bodies"));
if (Idx != INVALID_INDEX && Desc->Get<PDataArray>(Idx)->Size() > 0) FAIL;
}
OK;
}
//---------------------------------------------------------------------
void CStaticEnvManager::SetEnvObjectTransform(CStrID ID, const matrix44& Tfm)
{
n_assert(ID.IsValid());
int Idx = EnvObjects.FindIndex(ID);
if (Idx != INVALID_INDEX)
{
CEnvObject& Obj = EnvObjects.ValueAtIndex(Idx);
for (int i = 0; i < Obj.Collision.Size(); i++)
Obj.Collision[i]->SetTransform(Obj.CollLocalTfm[i] * Tfm);
for (int i = 0; i < Obj.Collision.Size(); i++)
Obj.Gfx[i]->SetTransform(Obj.GfxLocalTfm[i] * Tfm);
}
else
{
// Normal entity case
Game::PEntity pEnt = EntityMgr->GetEntityByID(ID);
if (pEnt.isvalid())
pEnt->FireEvent(Event::SetTransform(Tfm));
}
}
//---------------------------------------------------------------------
void CStaticEnvManager::DeleteEnvObject(CStrID ID)
{
n_assert(ID.IsValid());
int Idx = EnvObjects.FindIndex(ID);
if (Idx != INVALID_INDEX)
{
CEnvObject& Obj = EnvObjects.ValueAtIndex(Idx);
for (int j = 0; j < Obj.Collision.Size(); j++)
PhysicsSrv->GetLevel()->RemoveShape(Obj.Collision[j]);
for (int j = 0; j < Obj.Collision.Size(); j++)
GfxSrv->GetLevel()->RemoveEntity(Obj.Gfx[j]);
EnvObjects.EraseAt(Idx);
}
else
{
Game::PEntity pEnt = EntityMgr->GetEntityByID(ID);
if (pEnt.isvalid()) EntityMgr->RemoveEntity(pEnt);
}
}
//---------------------------------------------------------------------
void CStaticEnvManager::ClearStaticEnv()
{
for (int i = 0; i < EnvObjects.Size(); i++)
{
CEnvObject& Obj = EnvObjects.ValueAtIndex(i);
for (int j = 0; j < Obj.Collision.Size(); j++)
PhysicsSrv->GetLevel()->RemoveShape(Obj.Collision[j]);
for (int j = 0; j < Obj.Collision.Size(); j++)
GfxSrv->GetLevel()->RemoveEntity(Obj.Gfx[j]);
}
EnvObjects.Clear();
}
//---------------------------------------------------------------------
} // namespace Game
| 29.824645 | 103 | 0.588749 | [
"object",
"transform"
] |
b78ea06af5f6b51a24b7773ac750c75b973b79a1 | 5,607 | cxx | C++ | src/Cxx/Visualization/BlobbyLogo.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Visualization/BlobbyLogo.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Visualization/BlobbyLogo.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | //
// use implicit modeller to create the VTK logo
//
#include <vtkActor.h>
#include <vtkAppendPolyData.h>
#include <vtkContourFilter.h>
#include <vtkImplicitModeller.h>
#include <vtkNamedColors.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyDataReader.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>
int main( int argc, char *argv[] )
{
if (argc < 4)
{
std::cout << "Usage: " << argv[0] << " v.vtk t.vtk k.vtk" << std::endl;
return EXIT_FAILURE;
}
vtkSmartPointer<vtkRenderer> aRenderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> aRenderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
aRenderWindow->AddRenderer(aRenderer);
vtkSmartPointer<vtkRenderWindowInteractor> anInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
anInteractor->SetRenderWindow(aRenderWindow);
aRenderWindow->SetSize( 300, 300 );
// read the geometry file containing the letter v
vtkSmartPointer<vtkPolyDataReader> letterV =
vtkSmartPointer<vtkPolyDataReader>::New();
letterV->SetFileName (argv[1]);
// read the geometry file containing the letter t
vtkSmartPointer<vtkPolyDataReader> letterT =
vtkSmartPointer<vtkPolyDataReader>::New();
letterT->SetFileName (argv[2]);
// read the geometry file containing the letter k
vtkSmartPointer<vtkPolyDataReader> letterK =
vtkSmartPointer<vtkPolyDataReader>::New();
letterK->SetFileName (argv[3]);
// create a transform and transform filter for each letter
vtkSmartPointer<vtkTransform> VTransform =
vtkSmartPointer<vtkTransform>::New();
vtkSmartPointer<vtkTransformPolyDataFilter> VTransformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
VTransformFilter->SetInputConnection(letterV->GetOutputPort());
VTransformFilter->SetTransform (VTransform);
vtkSmartPointer<vtkTransform> TTransform =
vtkSmartPointer<vtkTransform>::New();
vtkSmartPointer<vtkTransformPolyDataFilter> TTransformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
TTransformFilter->SetInputConnection (letterT->GetOutputPort());
TTransformFilter->SetTransform (TTransform);
vtkSmartPointer<vtkTransform> KTransform =
vtkSmartPointer<vtkTransform>::New();
vtkSmartPointer<vtkTransformPolyDataFilter> KTransformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
KTransformFilter->SetInputConnection(letterK->GetOutputPort());
KTransformFilter->SetTransform (KTransform);
// now append them all
vtkSmartPointer<vtkAppendPolyData> appendAll =
vtkSmartPointer<vtkAppendPolyData>::New();
appendAll->AddInputConnection (VTransformFilter->GetOutputPort());
appendAll->AddInputConnection (TTransformFilter->GetOutputPort());
appendAll->AddInputConnection (KTransformFilter->GetOutputPort());
// create normals
vtkSmartPointer<vtkPolyDataNormals> logoNormals =
vtkSmartPointer<vtkPolyDataNormals>::New();
logoNormals->SetInputConnection (appendAll->GetOutputPort());
logoNormals->SetFeatureAngle (60);
// map to rendering primitives
vtkSmartPointer<vtkPolyDataMapper> logoMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
logoMapper->SetInputConnection (logoNormals->GetOutputPort());
// now an actor
vtkSmartPointer<vtkActor> logo =
vtkSmartPointer<vtkActor>::New();
logo->SetMapper (logoMapper);
// now create an implicit model of the same letter
vtkSmartPointer<vtkImplicitModeller> blobbyLogoImp =
vtkSmartPointer<vtkImplicitModeller>::New();
blobbyLogoImp->SetInputConnection(appendAll->GetOutputPort());
blobbyLogoImp->SetMaximumDistance (.075);
blobbyLogoImp->SetSampleDimensions (64,64,64);
blobbyLogoImp->SetAdjustDistance (0.05);
// extract an iso surface
vtkSmartPointer<vtkContourFilter> blobbyLogoIso =
vtkSmartPointer<vtkContourFilter>::New();
blobbyLogoIso->SetInputConnection (blobbyLogoImp->GetOutputPort());
blobbyLogoIso->SetValue (1, 1.5);
// map to rendering primitives
vtkSmartPointer<vtkPolyDataMapper> blobbyLogoMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
blobbyLogoMapper->SetInputConnection (blobbyLogoIso->GetOutputPort());
blobbyLogoMapper->ScalarVisibilityOff ();
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
vtkSmartPointer<vtkProperty> tomato =
vtkSmartPointer<vtkProperty>::New();
tomato->SetDiffuseColor(colors->GetColor3d("tomato").GetData());
tomato->SetSpecular(.3);
tomato->SetSpecularPower(20);
vtkSmartPointer<vtkProperty> banana =
vtkSmartPointer<vtkProperty>::New();
banana->SetDiffuseColor(colors->GetColor3d("banana").GetData());
banana->SetDiffuse (.7);
banana->SetSpecular(.4);
banana->SetSpecularPower(20);
// now an actor
vtkSmartPointer<vtkActor> blobbyLogo =
vtkSmartPointer<vtkActor>::New();
blobbyLogo->SetMapper (blobbyLogoMapper);
blobbyLogo->SetProperty (banana);
// position the letters
VTransform->Translate (-16.0,0.0,12.5);
VTransform->RotateY (40);
KTransform->Translate (14.0, 0.0, 0.0);
KTransform->RotateY (-40);
// move the polygonal letters to the front
logo->SetProperty (tomato);
logo->SetPosition(0,0,6);
aRenderer->AddActor(logo);
aRenderer->AddActor(blobbyLogo);
aRenderer->SetBackground(colors->GetColor3d("SlateGray").GetData());
aRenderWindow->Render();
// interact with data
anInteractor->Start();
return EXIT_SUCCESS;
}
| 33.981818 | 75 | 0.759051 | [
"geometry",
"render",
"model",
"transform"
] |
b78eebea61fcf5ad062251065ce1b53adf2f3610 | 7,812 | cpp | C++ | Plugins/onAirVRServer/Source/onAirVRServer/Private/AirVRCameraRig.cpp | kteem/onairvr-server-for-ue4 | 169ed09d30aaf45ba0c2d7e2897052b972f619b9 | [
"MIT"
] | null | null | null | Plugins/onAirVRServer/Source/onAirVRServer/Private/AirVRCameraRig.cpp | kteem/onairvr-server-for-ue4 | 169ed09d30aaf45ba0c2d7e2897052b972f619b9 | [
"MIT"
] | null | null | null | Plugins/onAirVRServer/Source/onAirVRServer/Private/AirVRCameraRig.cpp | kteem/onairvr-server-for-ue4 | 169ed09d30aaf45ba0c2d7e2897052b972f619b9 | [
"MIT"
] | null | null | null | /***********************************************************
Copyright (c) 2017-2018 Clicked, Inc.
Licensed under the MIT license found in the LICENSE file
in the Docs folder of the distributed package.
***********************************************************/
#include "AirVRCameraRig.h"
#include "AirVRServerPrivate.h"
#include "AirVRServerHMD.h"
FAirVRCameraRig::FAirVRCameraRig(class FAirVREventDispatcher* InEventDispatcher)
: PlayerID(-1), EventDispatcher(InEventDispatcher), LastTrackingTimeStamp(0.0), InputStream(this), bIsActivated(false), bEncodeRequested(false)
{
TrackingModel = FAirVRTrackingModel::CreateTrackingModel(FAirVRTrackingModelType::Head, this);
EventDispatcher->AddListener(this);
}
FAirVRCameraRig::~FAirVRCameraRig()
{
EventDispatcher->RemoveListener(this);
assert(TrackingModel);
delete TrackingModel;
}
void FAirVRCameraRig::SetTrackingModel(FAirVRTrackingModelType Type)
{
if (TrackingModel) {
delete TrackingModel;
}
TrackingModel = FAirVRTrackingModel::CreateTrackingModel(Type, this);
}
void FAirVRCameraRig::UpdateExternalTrackerLocationAndRotation(const FVector& Location, const FQuat& Rotation)
{
assert(TrackingModel);
TrackingModel->UpdateExternalTrackerLocationAndRotation(Location, Rotation);
}
FMatrix FAirVRCameraRig::GetLeftEyeProjectionMatrix() const
{
return MakeProjectionMatrix(LeftEyeCameraNearPlane[0] * GNearClippingPlane,
LeftEyeCameraNearPlane[1] * GNearClippingPlane,
LeftEyeCameraNearPlane[2] * GNearClippingPlane,
LeftEyeCameraNearPlane[3] * GNearClippingPlane,
GNearClippingPlane);
}
FMatrix FAirVRCameraRig::GetRightEyeProjectionMatrix() const
{
FMatrix Result = GetLeftEyeProjectionMatrix();
Result.M[2][0] = -Result.M[2][0];
return Result;
}
FQuat FAirVRCameraRig::GetHeadOrientation(bool bInHMDSpace) const
{
assert(TrackingModel);
return TrackingModel->GetHeadOrientation(bInHMDSpace);
}
FVector FAirVRCameraRig::GetCenterEyePosition() const
{
assert(TrackingModel);
return TrackingModel->GetCenterEyePosition();
}
FVector FAirVRCameraRig::GetLeftEyePosition() const
{
assert(TrackingModel);
return TrackingModel->GetLeftEyePosition();
}
FVector FAirVRCameraRig::GetRightEyePosition() const
{
assert(TrackingModel);
return TrackingModel->GetRightEyePosition();
}
FVector FAirVRCameraRig::GetLeftEyeOffset() const
{
assert(TrackingModel);
return TrackingModel->GetLeftEyeOffset();
}
FVector FAirVRCameraRig::GetRightEyeOffset() const
{
assert(TrackingModel);
return TrackingModel->GetRightEyeOffset();
}
FMatrix FAirVRCameraRig::GetHMDToPlayerSpaceMatrix() const
{
assert(TrackingModel);
return TrackingModel->GetHMDToPlayerSpaceMatrix();
}
void FAirVRCameraRig::UpdateViewInfo(const FIntRect& ScreenViewport, bool& OutShouldEncode, bool& OutIsStereoscopic)
{
if (IsBound()) {
OutShouldEncode = bEncodeRequested;
bEncodeRequested = false;
OutIsStereoscopic = true;
}
else {
VideoWidth = ScreenViewport.Width();
VideoHeight = ScreenViewport.Height();
float AspectRatio = ScreenViewport.Width() > 0 && ScreenViewport.Height() > 0 ? (float)VideoWidth / VideoHeight : 1.0f;
LeftEyeCameraNearPlane[0] = 1.0f * AspectRatio;
LeftEyeCameraNearPlane[1] = 1.0f;
LeftEyeCameraNearPlane[2] = -1.0f * AspectRatio;
LeftEyeCameraNearPlane[3] = -1.0f;
OutShouldEncode = false;
OutIsStereoscopic = false;
}
}
void FAirVRCameraRig::BindPlayer(int InPlayerID, const ONAIRVR_CLIENT_CONFIG& Config)
{
PlayerID = InPlayerID;
VideoWidth = Config.videoWidth;
VideoHeight = Config.videoHeight;
for (int i = 0; i < 4; i++) {
LeftEyeCameraNearPlane[i] = Config.leftEyeCameraNearPlane[i];
}
LastTrackingTimeStamp = 0.0;
}
void FAirVRCameraRig::UnbindPlayer()
{
PlayerID = -1;
}
void FAirVRCameraRig::Update()
{
if (IsBound()) {
InputStream.Update();
ONAIRVR_CLIENT_CONFIG Config;
onairvr_GetConfig(PlayerID, &Config);
ONAIRVR_VECTOR3D Position;
ONAIRVR_QUATERNION Orientation;
InputStream.GetTransform(ONAIRVR_INPUT_DEVICE_HEADTRACKER, (uint8)AirVRHeadTrackerKey::Transform, LastTrackingTimeStamp, &Position, &Orientation);
TrackingModel->UpdateEyePose(Config, Position, Orientation);
}
}
void FAirVRCameraRig::Reset()
{
UnbindPlayer();
InputStream.Reset();
bIsActivated = false;
bEncodeRequested = false;
}
void FAirVRCameraRig::EnableNetworkTimeWarp(bool bEnable)
{
if (IsBound()) {
onairvr_EnableNetworkTimeWarp(PlayerID, bEnable);
}
}
void FAirVRCameraRig::AirVRTrackingModelContextRecenterCameraRigPose()
{
if (IsBound()) {
onairvr_RecenterPose(PlayerID);
}
}
void FAirVRCameraRig::AirVREventMediaStreamInitialized(int InPlayerID)
{
if (PlayerID == InPlayerID) {
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
onairvr_InitStreams_RenderThread,
int, PlayerID, PlayerID,
{
onairvr_InitStreams_RenderThread(PlayerID);
}
);
InputStream.Init();
}
}
void FAirVRCameraRig::AirVREventMediaStreamStarted(int InPlayerID)
{
if (PlayerID == InPlayerID) {
bIsActivated = true;
assert(TrackingModel);
TrackingModel->StartTracking();
InputStream.Start();
}
}
void FAirVRCameraRig::AirVREventMediaStreamEncodeVideoFrame(int InPlayerID)
{
if (PlayerID == InPlayerID) {
bEncodeRequested = true;
// FAirVRServerHMD::RenderTexture_RenderThread will enqueue encoding events for all camera rigs.
}
}
void FAirVRCameraRig::AirVREventMediaStreamStopped(int InPlayerID)
{
if (PlayerID == InPlayerID) {
bIsActivated = false;
bEncodeRequested = false;
assert(TrackingModel);
TrackingModel->StopTracking();
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
onairvr_ResetStreams_RenderThread,
int, PlayerID, PlayerID,
{
onairvr_ResetStreams_RenderThread(PlayerID);
}
);
FlushRenderingCommands();
InputStream.Stop();
}
}
void FAirVRCameraRig::AirVREventMediaStreamCleanedUp(int InPlayerID)
{
if (PlayerID == InPlayerID) {
InputStream.Cleanup();
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
onairvr_CleanupStreams_RenderThread,
int, PlayerID, PlayerID,
{
onairvr_CleanupStreams_RenderThread(PlayerID);
}
);
FlushRenderingCommands();
}
}
void FAirVRCameraRig::AirVREventInputStreamRemoteInputDeviceRegistered(int InPlayerID, const FString& DeviceName, uint8 DeviceID)
{
if (PlayerID == InPlayerID) {
InputStream.HandleRemoteInputDeviceRegistered(DeviceName, DeviceID);
}
}
void FAirVRCameraRig::AirVREventInputStreamRemoteInputDeviceUnregistered(int InPlayerID, uint8 DeviceID)
{
if (PlayerID == InPlayerID) {
InputStream.HandleRemoteInputDeviceUnregistered(DeviceID);
}
}
FMatrix FAirVRCameraRig::MakeProjectionMatrix(float Left, float Top, float Right, float Bottom, float Near) const
{
return FMatrix(FPlane( 2.0f * Near / (Left - Right), 0.0f, 0.0f, 0.0f),
FPlane( 0.0f, 2.0f * Near / (Top - Bottom), 0.0f, 0.0f),
FPlane((Left + Right) / (Left - Right), (Top + Bottom) / (Top - Bottom), 0.0f, 1.0f),
FPlane( 0.0f, 0.0f, Near, 0.0f));
}
| 28.202166 | 154 | 0.670891 | [
"transform"
] |
b794b0ef0a83b07f04cfa35d8203ae188a42aaf6 | 1,478 | cpp | C++ | NeuroData/model/JavascriptProducerModel.cpp | lesit/NeuroStudio | f505065d694a8614587e7cc243ede72c141bd80b | [
"W3C"
] | 21 | 2018-11-15T08:23:14.000Z | 2022-03-30T15:44:59.000Z | NeuroData/model/JavascriptProducerModel.cpp | lesit/NeuroStudio | f505065d694a8614587e7cc243ede72c141bd80b | [
"W3C"
] | null | null | null | NeuroData/model/JavascriptProducerModel.cpp | lesit/NeuroStudio | f505065d694a8614587e7cc243ede72c141bd80b | [
"W3C"
] | 1 | 2021-12-08T01:17:27.000Z | 2021-12-08T01:17:27.000Z | #include "stdafx.h"
#include "JavascriptProducerModel.h"
#include "ModuleInterface/JSRunner/JavaScriptRunner.h"
using namespace np::ndr;
using namespace np::ndr::model;
JavascriptProducerModel::JavascriptProducerModel(neuro_u32 uid, const char* body)
: DynamicProducerModel(uid)
{
if (body)
m_js_body = body;
else
m_js_body = "var ret = [];\r\n\r\n"
"if(output_array.length!=4)\r\n"
" return ret;\r\n"
"\r\n"
"ret = new Array(output_array.length);\r\n"
"\r\n"
"// edit contents to make ret array "
"\r\n"
"\r\n"
"return ret";
}
JavascriptProducerModel::~JavascriptProducerModel()
{
}
const char* JavascriptProducerModel::GetHeader()
{
return "function target(seq, input_array, output_array, param_array)";
}
const char* JavascriptProducerModel::GetBody() const
{
return m_js_body.c_str();
}
bool JavascriptProducerModel::SetBody(const char* body, std::string& js_err)
{
m_js_body = body;
return Test(body, js_err);
}
bool JavascriptProducerModel::Test(const char* body, std::string& js_err)
{
std::string script = MakeScript(body);
np::js::JavaScriptRunner* test_script = np::js::JavaScriptRunner::Create(L"./", script.c_str(), js_err);
if (test_script)
{
delete test_script;
return true;
}
else
{
return false;
}
}
std::string JavascriptProducerModel::MakeScript(const char* body)
{
std::string script = GetHeader();
script.append("{\n");
script.append(body);
script.append("\n}");
return script;
}
| 20.246575 | 105 | 0.698917 | [
"model"
] |
b7999892e476ec3074f4325313a1f0585a47f38a | 1,561 | hpp | C++ | libs/image/include/sge/image/pixel/object.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/image/include/sge/image/pixel/object.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/image/include/sge/image/pixel/object.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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 SGE_IMAGE_PIXEL_OBJECT_HPP_INCLUDED
#define SGE_IMAGE_PIXEL_OBJECT_HPP_INCLUDED
#include <sge/image/has_format.hpp>
#include <sge/image/mizuiro_color_traits.hpp>
#include <sge/image/detail/instantiate/symbol.hpp>
#include <sge/image/pixel/elements.hpp>
#include <sge/image/pixel/mizuiro_type_fwd.hpp>
#include <sge/image/pixel/object_fwd.hpp>
#include <fcppt/variant/from_list.hpp>
namespace sge::image::pixel
{
template <typename Tag>
class object
{
public:
using elements = sge::image::pixel::elements<Tag>;
using variant = fcppt::variant::from_list<elements>;
template <typename Format>
explicit object(sge::image::pixel::mizuiro_type<Format> const &_color) : object(variant{_color})
{
static_assert(sge::image::has_format<Tag, Format>::value, "Invalid format.");
}
SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL
explicit object(variant const &);
SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL
object(object const &);
SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL
object(object &&) noexcept;
SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL
object &operator=(object const &);
SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL
object &operator=(object &&) noexcept;
SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL
~object();
[[nodiscard]] SGE_IMAGE_DETAIL_INSTANTIATE_SYMBOL variant const &get() const;
private:
variant variant_;
};
}
#endif
| 25.590164 | 98 | 0.759769 | [
"object"
] |
b79afba6c13a506d48c3de977ad4a95ac3efeff6 | 832 | cpp | C++ | 279.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | 279.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | 279.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | //
// Created by pzz on 2022/3/8.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int numSquares(int n) {
vector<int> nums = generateNumSquares(n);
vector<int> dp(n + 1, n);
dp[0] = 0;
for (int i = 0; i < nums.size(); i++) {
for (int j = nums[i]; j <= n; j++) {
if (dp[j - nums[i]] != n)
dp[j] = min(dp[j], dp[j - nums[i]] + 1);
}
}
return dp[n] ;
}
vector<int> generateNumSquares(int n) {
vector<int> result;
for (int i = 1;; i++) {
if (i * i > n)
break;
result.push_back(i * i);
}
return result;
}
};
int main() {
Solution solution;
cout << solution.numSquares(5);
return 0;
} | 19.809524 | 60 | 0.44351 | [
"vector"
] |
b79b686145496dc527ae39561957ca2ada6d79cb | 13,106 | cpp | C++ | src/evb/SFPPlotter.cpp | sesps/SPS_SABRE_EventBuilder | c044eed7cb10e31e76c13213e8bb5aef50391bba | [
"MIT"
] | null | null | null | src/evb/SFPPlotter.cpp | sesps/SPS_SABRE_EventBuilder | c044eed7cb10e31e76c13213e8bb5aef50391bba | [
"MIT"
] | null | null | null | src/evb/SFPPlotter.cpp | sesps/SPS_SABRE_EventBuilder | c044eed7cb10e31e76c13213e8bb5aef50391bba | [
"MIT"
] | null | null | null | /*SFPPlotter.h
*Class for generating histogram files for SPS-SABRE data
*Intended use case is generating a TChain of multiple analyzed files and making
*histograms of the larger data set.
*
*Created Jan 2020 by GWM
*/
#include "EventBuilder.h"
#include "SFPPlotter.h"
#include <TSystem.h>
/*Generates storage and initializes pointers*/
SFPPlotter::SFPPlotter() {
rootObj = new THashTable();
rootObj->SetOwner(false);//THashTable doesnt own members; avoid double delete
event_address = new ProcessedEvent();
chain = new TChain("SPSTree");
m_pb = NULL;
}
SFPPlotter::~SFPPlotter() {
delete event_address;
}
/*2D histogram fill wrapper*/
void SFPPlotter::MyFill(const string& name, int binsx, double minx, double maxx, double valuex,
int binsy, double miny, double maxy, double valuey) {
TH2F *histo = (TH2F*) rootObj->FindObject(name.c_str());
if(histo != NULL) {
histo->Fill(valuex, valuey);
} else {
TH2F *h = new TH2F(name.c_str(), name.c_str(), binsx, minx, maxx, binsy, miny, maxy);
h->Fill(valuex, valuey);
rootObj->Add(h);
}
}
/*1D histogram fill wrapper*/
void SFPPlotter::MyFill(const string& name, int binsx, double minx, double maxx, double valuex) {
TH1F *histo = (TH1F*) rootObj->FindObject(name.c_str());
if(histo != NULL) {
histo->Fill(valuex);
} else {
TH1F *h = new TH1F(name.c_str(), name.c_str(), binsx, minx, maxx);
h->Fill(valuex);
rootObj->Add(h);
}
}
void SFPPlotter::ApplyCutlist(const string& listname) {
cutter.SetCuts(listname);
}
/*Makes histograms where only rejection is unset data*/
void SFPPlotter::MakeUncutHistograms(ProcessedEvent ev) {
MyFill("x1NoCuts_bothplanes",600,-300,300,ev.x2);
MyFill("x2NoCuts_bothplanes",600,-300,300,ev.x2);
MyFill("xavgNoCuts_bothplanes",600,-300,300,ev.xavg);
MyFill("xavgNoCuts_theta_bothplanes",600,-300,300,ev.xavg,100,0,TMath::Pi()/2.,ev.theta);
MyFill("x1_delayBackRightE_NoCuts",600,-300,300,ev.x1,512,0,4096,ev.delayBackRightE);
MyFill("x2_delayBackRightE_NoCuts",600,-300,300,ev.x2,512,0,4096,ev.delayBackRightE);
MyFill("xavg_delayBackRightE_NoCuts",600,-300,300,ev.xavg,512,0,4096,ev.delayBackRightE);
MyFill("x1_x2_NoCuts",600,-300,300,ev.x1,600,-300,300,ev.x2);
Double_t delayBackAvgE = (ev.delayBackRightE+ev.delayBackLeftE)/2.0;
MyFill("x1_delayBackAvgE_NoCuts",600,-300,300,ev.x1,512,0,4096,delayBackAvgE);
MyFill("x2_delayBackAvgE_NoCuts",600,-300,300,ev.x2,512,0,4096,delayBackAvgE);
MyFill("xavg_delayBackAvgE_NoCuts",600,-300,300,ev.xavg,512,0,4096,delayBackAvgE);
Double_t delayFrontAvgE = (ev.delayFrontRightE+ev.delayFrontLeftE)/2.0;
MyFill("x1_delayFrontAvgE_NoCuts",600,-300,300,ev.x1,512,0,4096,delayFrontAvgE);
MyFill("x2_delayFrontAvgE_NoCuts",600,-300,300,ev.x2,512,0,4096,delayFrontAvgE);
MyFill("xavg_delayFrontAvgE_NoCuts",600,-300,300,ev.xavg,512,0,4096,delayFrontAvgE);
MyFill("scintLeft_anodeBack_NoCuts",512,0,4096,ev.scintLeft,512,0,4096,ev.anodeBack);
MyFill("scintLeft_anodeFront_NoCuts",512,0,4096,ev.scintLeft,512,0,4096,ev.anodeFront);
MyFill("scintLeft_cathode_NoCuts",512,0,4096,ev.scintLeft,512,0,4096,ev.cathode);
MyFill("x1_scintLeft_NoCuts",600,-300,300,ev.x1,512,0,4096,ev.scintLeft);
MyFill("x2_scintLeft_NoCuts",600,-300,300,ev.x2,512,0,4096,ev.scintLeft);
MyFill("xavg_scintLeft_NoCuts",600,-300,300,ev.xavg,512,0,4096,ev.scintLeft);
MyFill("x1_anodeBack_NoCuts",600,-300,300,ev.x1,512,0,4096,ev.anodeBack);
MyFill("x2_anodeBack_NoCuts",600,-300,300,ev.x2,512,0,4096,ev.anodeBack);
MyFill("xavg_anodeBack_NoCuts",600,-300,300,ev.xavg,512,0,4096,ev.anodeBack);
MyFill("x1_anodeFront_NoCuts",600,-300,300,ev.x1,512,0,4096,ev.anodeFront);
MyFill("x2_anodeFront_NoCuts",600,-300,300,ev.x2,512,0,4096,ev.anodeFront);
MyFill("xavg_anodeFront_NoCuts",600,-300,300,ev.xavg,512,0,4096,ev.anodeFront);
MyFill("x1_cathode_NoCuts",600,-300,300,ev.x1,512,0,4096,ev.cathode);
MyFill("x2_cathode_NoCuts",600,-300,300,ev.x2,512,0,4096,ev.cathode);
MyFill("xavg_cathode_NoCuts",600,-300,300,ev.xavg,512,0,4096,ev.cathode);
/****Timing relative to back anode****/
if(ev.anodeBackTime != -1 && ev.scintLeftTime != -1) {
Double_t anodeRelFT = ev.anodeFrontTime - ev.anodeBackTime;
Double_t delayRelFT = ev.delayFrontMaxTime - ev.anodeBackTime;
Double_t delayRelBT = ev.delayBackMaxTime - ev.anodeBackTime;
Double_t anodeRelBT = ev.anodeBackTime - ev.scintLeftTime;
Double_t delayRelFT_toScint = ev.delayFrontMaxTime - ev.scintLeftTime;
Double_t delayRelBT_toScint = ev.delayBackMaxTime - ev.scintLeftTime;
MyFill("anodeRelFrontTime_NoCuts",1000,-3000,3500, anodeRelFT);
MyFill("delayRelFrontTime_NoCuts",1000,-3000,-3500,delayRelFT);
MyFill("delayRelBackTime_NoCuts",1000,-3000,-3500,delayRelBT);
for(int i=0; i<5; i++) {
if(ev.sabreRingE[i] != -1) {
Double_t sabreRelRT = ev.sabreRingTime[i] - ev.anodeBackTime;
Double_t sabreRelWT = ev.sabreWedgeTime[i] - ev.anodeBackTime;
Double_t sabreRelRT_toScint = ev.sabreRingTime[i] - ev.scintLeftTime;
Double_t sabreRelWT_toScint = ev.sabreWedgeTime[i] - ev.scintLeftTime;
MyFill("xavg_sabrefcoinc_NoCuts",600,-300,300, ev.xavg);
MyFill("sabreRelRingTime_NoCuts",1000,-3000,3500, sabreRelRT);
MyFill("sabreRelWedgeTime_NoCuts",1000,-3000,3500, sabreRelWT);
MyFill("sabreRelRingTime_toScint",1000,-3000,3500,sabreRelRT_toScint);
MyFill("sabreRelWedgeTime_toScint",1000,-3000,3500,sabreRelWT_toScint);
MyFill("sabreRelRTScint_sabreRelRTAnode",500,-3000,3500,sabreRelRT_toScint,500,-3000,3500,sabreRelRT);
MyFill("sabreRelRTScint_sabreRingChannel",500,-3000,3500,sabreRelRT_toScint,144,0,144,ev.sabreRingChannel[i]);
MyFill("sabreRelRTAnode_sabreRingChannel",500,-3000,3500,sabreRelRT,144,0,144,ev.sabreRingChannel[i]);
MyFill("sabreRelWTScint_sabreWedgeChannel",500,-3000,3500,sabreRelWT_toScint,144,0,144,ev.sabreWedgeChannel[i]);
MyFill("sabreRelRT_sabreRelWT",500,-3000,3500,sabreRelRT,500,-3000,3500,sabreRelWT);
MyFill("sabreRelRT_sabreRelWT_scint",500,-3000,3500,sabreRelRT_toScint,500,-3000,3500,sabreRelWT_toScint);
MyFill("sabreRelRTScint_anodeRelT",500,-3000,3500,sabreRelRT_toScint,500,-3000,3500,anodeRelBT);
}
}
MyFill("anodeBackRelTime_toScint",1000,-3000,3500,anodeRelBT);
MyFill("delayRelBackTime_toScint",1000,-3000,3500,delayRelBT_toScint);
MyFill("delayRelFrontTime_toScint",1000,-3000,3500,delayRelFT_toScint);
} else {
MyFill("noscinttime_counter_NoCuts",2,0,1,1);
}
int count = 0;
for(int i=0; i<5; i++) {
if(ev.sabreRingE[i] != -1) { //Again, at this point front&back are required
MyFill("sabreRingE_NoCuts",2000,0,20,ev.sabreRingE[i]);
MyFill("sabreRingChannel_sabreRingE_NoCuts",144,0,144,ev.sabreRingChannel[i],200,0,20,ev.sabreRingE[i]);
MyFill("sabreWedgeE_NoCuts",2000,0,20,ev.sabreWedgeE[i]);
MyFill("sabreWedgeChannel_sabreWedgeE_NoCuts",144,0,144,ev.sabreWedgeChannel[i],200,0,20,ev.sabreWedgeE[i]);
} else {
count++;
}
}
if(count == 80) {
MyFill("xavg_bothplanes_sabreanticoinc_NoCuts",600,-300,300,ev.xavg);
}
if(ev.x1 != -1e6 && ev.x2 == -1e6) {
MyFill("x1NoCuts_only1plane",600,-300,300,ev.x1);
} else if(ev.x2 != -1e6 && ev.x1 == -1e6) {
MyFill("x2NoCuts_only1plane",600,-300,300,ev.x2);
} else if(ev.x1 == -1e6 && ev.x2 == -1e6) {
MyFill("nopos_counter",2,0,1,1);
}
}
/*Makes histograms with cuts & gates implemented*/
void SFPPlotter::MakeCutHistograms(ProcessedEvent ev) {
if(cutter.IsInside(&ev)) {
MyFill("x1_bothplanes_Cut",600,-300,300,ev.x1);
MyFill("x2_bothplanes_Cut",600,-300,300,ev.x2);
MyFill("xavg_bothplanes_Cut",600,-300,300,ev.xavg);
MyFill("x1_x2_Cut",600,-300,300,ev.x1, 600,-300,300,ev.x2);
MyFill("xavg_theta_Cut_bothplanes",600,-300,300,ev.xavg,100,0,TMath::Pi()/2.,ev.theta);
MyFill("x1_delayBackRightE_Cut",600,-300,300,ev.x1,512,0,4096,ev.delayBackRightE);
MyFill("x2_delayBackRightE_Cut",600,-300,300,ev.x2,512,0,4096,ev.delayBackRightE);
MyFill("xavg_delayBackRightE_Cut",600,-300,300,ev.xavg,512,0,4096,ev.delayBackRightE);
Double_t delayBackAvgE = (ev.delayBackRightE+ev.delayBackLeftE)/2.0;
MyFill("x1_delayBackAvgE_Cut",600,-300,300,ev.x1,512,0,4096,delayBackAvgE);
MyFill("x2_delayBackAvgE_Cut",600,-300,300,ev.x2,512,0,4096,delayBackAvgE);
MyFill("xavg_delayBackAvgE_Cut",600,-300,300,ev.xavg,512,0,4096,delayBackAvgE);
Double_t delayFrontAvgE = (ev.delayFrontRightE+ev.delayFrontLeftE)/2.0;
MyFill("x1_delayFrontAvgE_Cut",600,-300,300,ev.x1,512,0,4096,delayFrontAvgE);
MyFill("x2_delayFrontAvgE_Cut",600,-300,300,ev.x2,512,0,4096,delayFrontAvgE);
MyFill("xavg_delayFrontAvgE_Cut",600,-300,300,ev.xavg,512,0,4096,delayFrontAvgE);
MyFill("scintLeft_anodeBack_Cut",512,0,4096,ev.scintLeft,512,0,4096,ev.anodeBack);
MyFill("scintLeft_anodeFront_Cut",512,0,4096,ev.scintLeft,512,0,4096,ev.anodeFront);
MyFill("scintLeft_cathode_Cut",512,0,4096,ev.scintLeft,512,0,4096,ev.cathode);
MyFill("x1_scintLeft_Cut",600,-300,300,ev.x1,512,0,4096,ev.scintLeft);
MyFill("x2_scintLeft_Cut",600,-300,300,ev.x2,512,0,4096,ev.scintLeft);
MyFill("xavg_scintLeft_Cut",600,-300,300,ev.xavg,512,0,4096,ev.scintLeft);
MyFill("x1_anodeBack_Cut",600,-300,300,ev.x1,512,0,4096,ev.anodeBack);
MyFill("x2_anodeBack_Cut",600,-300,300,ev.x2,512,0,4096,ev.anodeBack);
MyFill("xavg_anodeBack_Cut",600,-300,300,ev.xavg,512,0,4096,ev.anodeBack);
MyFill("x1_anodeFront_Cut",600,-300,300,ev.x1,512,0,4096,ev.anodeFront);
MyFill("x2_anodeFront_Cut",600,-300,300,ev.x2,512,0,4096,ev.anodeFront);
MyFill("xavg_anodeFront_Cut",600,-300,300,ev.xavg,512,0,4096,ev.anodeFront);
MyFill("x1_cathode_Cut",600,-300,300,ev.x1,512,0,4096,ev.cathode);
MyFill("x2_cathode_Cut",600,-300,300,ev.x2,512,0,4096,ev.cathode);
MyFill("xavg_cathode_Cut",600,-300,300,ev.xavg,512,0,4096,ev.cathode);
/****Timing relative to back anode****/
if(ev.anodeBackTime != -1 && ev.scintLeftTime != -1) {
Double_t anodeRelFT = ev.anodeFrontTime - ev.anodeBackTime;
Double_t anodeRelBT = ev.anodeBackTime - ev.anodeBackTime;
Double_t anodeRelFT_toScint = ev.anodeFrontTime-ev.scintLeftTime;
MyFill("anodeRelBackTime_Cut",1000,-3000,3500, anodeRelBT);
MyFill("anodeRelFrontTime_Cut",1000,-3000,3500, anodeRelFT);
MyFill("anodeRelTime_toScint_Cut",1000,-3000,3500,anodeRelFT_toScint);
for(int i=0; i<5; i++) {
if(ev.sabreRingE[i] != -1) {
Double_t sabreRelRT = ev.sabreRingTime[i] - ev.anodeBackTime;
Double_t sabreRelWT = ev.sabreWedgeTime[i] - ev.anodeBackTime;
MyFill("sabreRelRingTime_Cut",1000,-3000,3500, sabreRelRT);
MyFill("sabreRelWedgeTime_Cut",1000,-3000,3500, sabreRelWT);
}
}
} else {
MyFill("noscinttime_counter_Cut",2,0,1,1);
}
int count = 0;
for(int i=0; i<5; i++) {
if(ev.sabreRingE[i] != -1) {
MyFill("sabreRingE_Cut",2000,0,20,ev.sabreRingE[i]);
MyFill("xavg_Cut_sabrefcoinc",600,-300,300,ev.xavg);
MyFill("xavg_sabreRingE_Cut",600,-300,300,ev.xavg,200,0,20,ev.sabreRingE[i]);
MyFill("sabreWedgeE_Cut",2000,0,20,ev.sabreWedgeE[i]);
MyFill("xavg_sabreWedgeE_Cut",600,-300,300,ev.xavg,200,0,20,ev.sabreWedgeE[i]);
} else {
count++;
}
}
if(count == 80) {
MyFill("xavg_bothplanes_sabreanticoinc_Cut",600,-300,300,ev.xavg);
}
}
}
/*Runs a list of files given from a RunMusher/Collector class*/
void SFPPlotter::Run(vector<TString> files, const string& output) {
Chain(files);
chain->SetBranchAddress("event", &event_address);
TFile *outfile = new TFile(output.c_str(), "RECREATE");
long blentries = chain->GetEntries();
if(m_pb) SetProgressBar(blentries);
cout<<"Total number of events: "<<blentries<<endl;
long count=0, flush=blentries*0.01, nflushes=0;
if(flush == 0) flush = 1;
for(long double i=0; i<chain->GetEntries(); i++) {
count++;
if(count == flush) {
if(m_pb) {
m_pb->Increment(count);
gSystem->ProcessEvents();
count = 0;
} else {
nflushes++;
count=0;
std::cout<<"\rPercent of data processed: "<<nflushes*10<<"%"<<std::flush;
}
}
chain->GetEntry(i);
MakeUncutHistograms(*event_address);
if(cutter.IsValid()) MakeCutHistograms(*event_address);
}
cout<<endl;
outfile->cd();
rootObj->Write();
if(cutter.IsValid()) {
auto clist = cutter.GetCuts();
for(unsigned int i=0; i<clist.size(); i++) {
clist[i]->Write();
}
}
delete rootObj;
outfile->Close();
delete outfile;
}
/*Link all files*/
void SFPPlotter::Chain(vector<TString> files) {
for(unsigned int i=0; i<files.size(); i++) {
chain->Add(files[i]);
}
}
void SFPPlotter::SetProgressBar(long total) {
m_pb->SetMax(total);
m_pb->SetMin(0);
m_pb->SetPosition(0);
gSystem->ProcessEvents();
}
| 44.427119 | 120 | 0.701206 | [
"vector"
] |
b79f972b48b01e572a9cd233757ec383f343ee2b | 3,417 | cpp | C++ | shift/render.vk/private/shift/render/vk/smart_ptr.cpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | 2 | 2018-11-28T18:14:08.000Z | 2020-08-06T07:44:36.000Z | shift/render.vk/private/shift/render/vk/smart_ptr.cpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | 4 | 2018-11-06T21:01:05.000Z | 2019-02-19T07:52:52.000Z | shift/render.vk/private/shift/render/vk/smart_ptr.cpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | null | null | null | #include "shift/render/vk/smart_ptr.hpp"
namespace shift::render::vk
{
releaseable_wrapper::~releaseable_wrapper() = default;
thread_local std::unique_ptr<shared_object_queue>
shared_object_queue::_local_queue;
void shared_object_queue::initialize()
{
_local_queue = std::make_unique<shared_object_queue>();
}
void shared_object_queue::finalize()
{
_local_queue.reset();
}
shared_object_queue& shared_object_queue::local_queue()
{
BOOST_ASSERT(_local_queue != nullptr);
return *_local_queue;
}
void shared_object_queue::queue(releaseable_wrapper& object)
{
/// ToDo: Benchmark locking.
std::lock_guard lock(_queue_mutex);
_queue.push(&object);
}
bool shared_object_queue::collect()
{
auto* object_queue = _local_queue.get();
BOOST_ASSERT(object_queue != nullptr);
/// ToDo: Benchmark locking.
std::lock_guard lock(object_queue->_queue_mutex);
bool collected = false;
while (!object_queue->_queue.empty())
{
object_queue->_queue.front()->release();
object_queue->_queue.pop();
collected = true;
}
return collected;
}
thread_local std::unique_ptr<framed_object_queue>
framed_object_queue::_local_queue;
void framed_object_queue::initialize()
{
_local_queue = std::make_unique<framed_object_queue>();
}
void framed_object_queue::finalize()
{
_local_queue.reset();
}
framed_object_queue& framed_object_queue::local_queue()
{
BOOST_ASSERT(_local_queue != nullptr);
return *_local_queue;
}
void framed_object_queue::queue(releaseable_wrapper& object)
{
/// ToDo: Benchmark locking.
std::lock_guard lock(_queue_mutex);
_queues[_swapchain_index].push(&object);
}
bool framed_object_queue::collect(std::uint32_t swapchain_index)
{
auto* object_queue = _local_queue.get();
BOOST_ASSERT(object_queue != nullptr);
/// ToDo: Benchmark locking.
std::lock_guard lock(object_queue->_queue_mutex);
object_queue->_swapchain_index = swapchain_index;
auto& queue = object_queue->_queues[swapchain_index];
bool collected = false;
// We must not simply loop until the queue is empty because releasing objects
// might queue new sub-objects.
auto elements_to_delete = queue.size();
while (elements_to_delete > 0)
{
queue.front()->release();
queue.pop();
collected = true;
--elements_to_delete;
}
return collected;
}
thread_local std::unique_ptr<fenced_object_queue>
fenced_object_queue::_local_queue;
void fenced_object_queue::initialize()
{
_local_queue = std::make_unique<fenced_object_queue>();
}
void fenced_object_queue::finalize()
{
_local_queue.reset();
}
fenced_object_queue& fenced_object_queue::local_queue()
{
BOOST_ASSERT(_local_queue != nullptr);
return *_local_queue;
}
void fenced_object_queue::queue(vk::layer1::fence& fence,
releaseable_wrapper& object)
{
/// ToDo: Benchmark locking.
std::lock_guard lock(_queue_mutex);
_queue.push(std::make_pair(&fence, &object));
}
bool fenced_object_queue::collect()
{
auto* object_queue = _local_queue.get();
BOOST_ASSERT(object_queue != nullptr);
/// ToDo: Benchmark locking.
std::lock_guard lock(object_queue->_queue_mutex);
bool collected = false;
while (!object_queue->_queue.empty())
{
auto [fence, object] = object_queue->_queue.front();
if (!fence->status())
break;
object->release();
object_queue->_queue.pop();
collected = true;
}
return collected;
}
}
| 23.087838 | 79 | 0.729002 | [
"render",
"object"
] |
b7a1ad20700ccd9cdf16cfdf33596ff3ab4406a9 | 511 | cpp | C++ | eagleeye/processnode/ConstNode.cpp | MirrorYu/eagleeye | c251e7b3bc919673b41360212c38d5fda85bbe2f | [
"Apache-2.0"
] | 12 | 2020-09-21T02:24:11.000Z | 2022-03-10T03:02:03.000Z | eagleeye/processnode/ConstNode.cpp | MirrorYu/eagleeye | c251e7b3bc919673b41360212c38d5fda85bbe2f | [
"Apache-2.0"
] | 1 | 2020-11-30T08:22:50.000Z | 2020-11-30T08:22:50.000Z | eagleeye/processnode/ConstNode.cpp | MirrorYu/eagleeye | c251e7b3bc919673b41360212c38d5fda85bbe2f | [
"Apache-2.0"
] | 3 | 2020-03-16T12:10:55.000Z | 2021-07-20T09:58:15.000Z | #include "eagleeye/processnode/ConstNode.h"
namespace eagleeye
{
ConstNode::ConstNode(int input_port_num, std::vector<AnySignal*> output_const_sigs){
this->setNumberOfInputSignals(input_port_num);
// no input ports
this->setNumberOfOutputSignals(output_const_sigs.size());
for(int i=0; i<output_const_sigs.size(); ++i){
this->setOutputPort(output_const_sigs[i], i);
}
}
ConstNode::~ConstNode(){
}
void ConstNode::executeNodeInfo(){
// do nothing
}
} // namespace eagleeye
| 24.333333 | 84 | 0.712329 | [
"vector"
] |
b7aaf6d80fa2f3911bfb095fbda9f49ca7b0751c | 17,680 | cpp | C++ | sp/src/materialsystem/stdshaders/worldtwotextureblend.cpp | map-labs-source/Map-Labs | 29f60485c219dd8b4b0b4a7343c85ccad8ad1685 | [
"Unlicense"
] | 137 | 2019-07-13T03:40:58.000Z | 2022-03-17T21:53:10.000Z | sp/src/materialsystem/stdshaders/worldtwotextureblend.cpp | map-labs-source/Map-Labs | 29f60485c219dd8b4b0b4a7343c85ccad8ad1685 | [
"Unlicense"
] | 140 | 2019-10-24T16:48:00.000Z | 2022-03-27T06:17:50.000Z | sp/src/materialsystem/stdshaders/worldtwotextureblend.cpp | map-labs-source/Map-Labs | 29f60485c219dd8b4b0b4a7343c85ccad8ad1685 | [
"Unlicense"
] | 108 | 2019-09-30T22:00:56.000Z | 2022-03-30T00:14:58.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Header: $
// $NoKeywords: $
//===========================================================================//
#include "BaseVSShader.h"
#include "convar.h"
#include "SDK_lightmappedgeneric_vs20.inc"
#include "SDK_worldtwotextureblend_ps20.inc"
#include "SDK_worldtwotextureblend_ps20b.inc"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar r_flashlight_version2;
// FIXME: Need to make a dx9 version so that "CENTROID" works.
BEGIN_VS_SHADER( SDK_WorldTwoTextureBlend,
"Help for SDK_WorldTwoTextureBlend" )
BEGIN_SHADER_PARAMS
SHADER_PARAM_OVERRIDE( BASETEXTURE, SHADER_PARAM_TYPE_TEXTURE, "shadertest/WorldTwoTextureBlend", "iris texture", 0 )
SHADER_PARAM( ALBEDO, SHADER_PARAM_TYPE_TEXTURE, "shadertest/WorldTwoTextureBlend", "albedo (Base texture with no baked lighting)" )
SHADER_PARAM( SELFILLUMTINT, SHADER_PARAM_TYPE_COLOR, "[1 1 1]", "Self-illumination tint" )
SHADER_PARAM( DETAIL, SHADER_PARAM_TYPE_TEXTURE, "shadertest/WorldTwoTextureBlend_detail", "detail texture" )
SHADER_PARAM( DETAILFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "frame number for $detail" )
SHADER_PARAM( DETAILSCALE, SHADER_PARAM_TYPE_FLOAT, "1.0", "scale of the detail texture" )
SHADER_PARAM( DETAIL_ALPHA_MASK_BASE_TEXTURE, SHADER_PARAM_TYPE_BOOL, "0",
"If this is 1, then when detail alpha=0, no base texture is blended and when "
"detail alpha=1, you get detail*base*lightmap" )
SHADER_PARAM( BUMPMAP, SHADER_PARAM_TYPE_TEXTURE, "models/shadertest/shader1_normal", "bump map" )
SHADER_PARAM( BUMPFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "frame number for $bumpmap" )
SHADER_PARAM( BUMPTRANSFORM, SHADER_PARAM_TYPE_MATRIX, "center .5 .5 scale 1 1 rotate 0 translate 0 0", "$bumpmap texcoord transform" )
SHADER_PARAM( NODIFFUSEBUMPLIGHTING, SHADER_PARAM_TYPE_INTEGER, "0", "0 == Use diffuse bump lighting, 1 = No diffuse bump lighting" )
SHADER_PARAM( SEAMLESS_SCALE, SHADER_PARAM_TYPE_FLOAT, "0", "Scale factor for 'seamless' texture mapping. 0 means to use ordinary mapping" )
END_SHADER_PARAMS
SHADER_FALLBACK
{
if( g_pHardwareConfig->GetDXSupportLevel() < 80 )
return "WorldTwoTextureBlend_DX6";
if( g_pHardwareConfig->GetDXSupportLevel() < 90 )
return "WorldTwoTextureBlend_DX8";
return 0;
}
SHADER_INIT_PARAMS()
{
if( !params[DETAIL_ALPHA_MASK_BASE_TEXTURE]->IsDefined() )
{
params[DETAIL_ALPHA_MASK_BASE_TEXTURE]->SetIntValue( 0 );
}
if ( g_pHardwareConfig->SupportsBorderColor() )
{
params[FLASHLIGHTTEXTURE]->SetStringValue( "effects/flashlight_border" );
}
else
{
params[FLASHLIGHTTEXTURE]->SetStringValue( "effects/flashlight001" );
}
// Write over $basetexture with $albedo if we are going to be using diffuse normal mapping.
if( g_pConfig->UseBumpmapping() && params[BUMPMAP]->IsDefined() && params[ALBEDO]->IsDefined() &&
params[BASETEXTURE]->IsDefined() &&
!( params[NODIFFUSEBUMPLIGHTING]->IsDefined() && params[NODIFFUSEBUMPLIGHTING]->GetIntValue() ) )
{
params[BASETEXTURE]->SetStringValue( params[ALBEDO]->GetStringValue() );
}
if( !params[NODIFFUSEBUMPLIGHTING]->IsDefined() )
{
params[NODIFFUSEBUMPLIGHTING]->SetIntValue( 0 );
}
if( !params[SELFILLUMTINT]->IsDefined() )
{
params[SELFILLUMTINT]->SetVecValue( 1.0f, 1.0f, 1.0f );
}
if( !params[DETAILSCALE]->IsDefined() )
{
params[DETAILSCALE]->SetFloatValue( 4.0f );
}
if( !params[BUMPFRAME]->IsDefined() )
{
params[BUMPFRAME]->SetIntValue( 0 );
}
if( !params[DETAILFRAME]->IsDefined() )
{
params[DETAILFRAME]->SetIntValue( 0 );
}
// No texture means no self-illum or env mask in base alpha
if ( !params[BASETEXTURE]->IsDefined() )
{
CLEAR_FLAGS( MATERIAL_VAR_SELFILLUM );
CLEAR_FLAGS( MATERIAL_VAR_BASEALPHAENVMAPMASK );
}
// If in decal mode, no debug override...
if (IS_FLAG_SET(MATERIAL_VAR_DECAL))
{
SET_FLAGS( MATERIAL_VAR_NO_DEBUG_OVERRIDE );
}
SET_FLAGS2( MATERIAL_VAR2_LIGHTING_LIGHTMAP );
if( g_pConfig->UseBumpmapping() && params[BUMPMAP]->IsDefined() && (params[NODIFFUSEBUMPLIGHTING]->GetIntValue() == 0) )
{
SET_FLAGS2( MATERIAL_VAR2_LIGHTING_BUMPED_LIGHTMAP );
}
}
SHADER_INIT
{
if( g_pConfig->UseBumpmapping() && params[BUMPMAP]->IsDefined() )
{
LoadBumpMap( BUMPMAP );
}
if (params[BASETEXTURE]->IsDefined())
{
LoadTexture( BASETEXTURE, TEXTUREFLAGS_SRGB );
if (!params[BASETEXTURE]->GetTextureValue()->IsTranslucent())
{
CLEAR_FLAGS( MATERIAL_VAR_SELFILLUM );
CLEAR_FLAGS( MATERIAL_VAR_BASEALPHAENVMAPMASK );
}
}
if (params[DETAIL]->IsDefined())
{
LoadTexture( DETAIL );
}
LoadTexture( FLASHLIGHTTEXTURE, TEXTUREFLAGS_SRGB );
// Don't alpha test if the alpha channel is used for other purposes
if (IS_FLAG_SET(MATERIAL_VAR_SELFILLUM) || IS_FLAG_SET(MATERIAL_VAR_BASEALPHAENVMAPMASK) )
{
CLEAR_FLAGS( MATERIAL_VAR_ALPHATEST );
}
// We always need this because of the flashlight.
SET_FLAGS2( MATERIAL_VAR2_NEEDS_TANGENT_SPACES );
}
void DrawPass( IMaterialVar** params, IShaderDynamicAPI *pShaderAPI,
IShaderShadow* pShaderShadow, bool hasFlashlight, VertexCompressionType_t vertexCompression )
{
bool hasBump = params[BUMPMAP]->IsTexture();
bool hasDiffuseBumpmap = hasBump && (params[NODIFFUSEBUMPLIGHTING]->GetIntValue() == 0);
bool hasBaseTexture = params[BASETEXTURE]->IsTexture();
bool hasDetailTexture = /*!hasBump && */params[DETAIL]->IsTexture();
bool hasVertexColor = IS_FLAG_SET( MATERIAL_VAR_VERTEXCOLOR ) != 0;
bool bHasDetailAlpha = params[DETAIL_ALPHA_MASK_BASE_TEXTURE]->GetIntValue() != 0;
bool bIsAlphaTested = IS_FLAG_SET( MATERIAL_VAR_ALPHATEST ) != 0;
BlendType_t nBlendType = EvaluateBlendRequirements( BASETEXTURE, true );
bool bFullyOpaque = (nBlendType != BT_BLENDADD) && (nBlendType != BT_BLEND) && !IS_FLAG_SET(MATERIAL_VAR_ALPHATEST); //dest alpha is free for special use
bool bSeamlessMapping = params[SEAMLESS_SCALE]->GetFloatValue() != 0.0;
SHADOW_STATE
{
int nShadowFilterMode = 0;
// Alpha test: FIXME: shouldn't this be handled in Shader_t::SetInitialShadowState
pShaderShadow->EnableAlphaTest( bIsAlphaTested );
if( hasFlashlight )
{
if ( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
nShadowFilterMode = g_pHardwareConfig->GetShadowFilterMode(); // Based upon vendor and device dependent formats
}
SetAdditiveBlendingShadowState( BASETEXTURE, true );
pShaderShadow->EnableDepthWrites( false );
// Be sure not to write to dest alpha
pShaderShadow->EnableAlphaWrites( false );
}
else
{
SetDefaultBlendingShadowState( BASETEXTURE, true );
}
unsigned int flags = VERTEX_POSITION;
if( hasBaseTexture )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, true );
}
// if( hasLightmap )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true );
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER1, g_pHardwareConfig->GetHDRType() == HDR_TYPE_NONE );
}
if( hasFlashlight )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER2, true );
pShaderShadow->EnableTexture( SHADER_SAMPLER7, true );
pShaderShadow->SetShadowDepthFiltering( SHADER_SAMPLER7 );
flags |= VERTEX_TANGENT_S | VERTEX_TANGENT_T | VERTEX_NORMAL;
}
if( hasDetailTexture )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER3, true );
}
if( hasBump )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER4, true );
}
if( hasVertexColor )
{
flags |= VERTEX_COLOR;
}
// Normalizing cube map
pShaderShadow->EnableTexture( SHADER_SAMPLER6, true );
// texcoord0 : base texcoord
// texcoord1 : lightmap texcoord
// texcoord2 : lightmap texcoord offset
int numTexCoords = 2;
if( hasBump )
{
numTexCoords = 3;
}
pShaderShadow->VertexShaderVertexFormat( flags, numTexCoords, 0, 0 );
// Pre-cache pixel shaders
bool hasSelfIllum = IS_FLAG_SET( MATERIAL_VAR_SELFILLUM );
pShaderShadow->EnableSRGBWrite( true );
DECLARE_STATIC_VERTEX_SHADER( sdk_lightmappedgeneric_vs20 );
SET_STATIC_VERTEX_SHADER_COMBO( ENVMAP_MASK, false );
SET_STATIC_VERTEX_SHADER_COMBO( BUMPMASK, false );
SET_STATIC_VERTEX_SHADER_COMBO( TANGENTSPACE, hasFlashlight );
SET_STATIC_VERTEX_SHADER_COMBO( BUMPMAP, hasBump );
SET_STATIC_VERTEX_SHADER_COMBO( DIFFUSEBUMPMAP, hasDiffuseBumpmap );
SET_STATIC_VERTEX_SHADER_COMBO( VERTEXCOLOR, hasVertexColor );
SET_STATIC_VERTEX_SHADER_COMBO( VERTEXALPHATEXBLENDFACTOR, false );
SET_STATIC_VERTEX_SHADER_COMBO( RELIEF_MAPPING, 0 ); //( bumpmap_variant == 2 )?1:0);
SET_STATIC_VERTEX_SHADER_COMBO( SEAMLESS, bSeamlessMapping ); //( bumpmap_variant == 2 )?1:0);
#ifdef _X360
SET_STATIC_VERTEX_SHADER_COMBO( FLASHLIGHT, hasFlashlight );
#endif
#ifdef MAPBASE
SET_STATIC_VERTEX_SHADER_COMBO( BASETEXTURETRANSFORM2, false );
#endif
SET_STATIC_VERTEX_SHADER( sdk_lightmappedgeneric_vs20 );
if ( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_STATIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20b );
SET_STATIC_PIXEL_SHADER_COMBO( DETAILTEXTURE, hasDetailTexture );
SET_STATIC_PIXEL_SHADER_COMBO( BUMPMAP, hasBump );
SET_STATIC_PIXEL_SHADER_COMBO( DIFFUSEBUMPMAP, hasDiffuseBumpmap );
SET_STATIC_PIXEL_SHADER_COMBO( VERTEXCOLOR, hasVertexColor );
SET_STATIC_PIXEL_SHADER_COMBO( SELFILLUM, hasSelfIllum );
SET_STATIC_PIXEL_SHADER_COMBO( DETAIL_ALPHA_MASK_BASE_TEXTURE, bHasDetailAlpha );
SET_STATIC_PIXEL_SHADER_COMBO( FLASHLIGHT, hasFlashlight );
SET_STATIC_PIXEL_SHADER_COMBO( SEAMLESS, bSeamlessMapping );
SET_STATIC_PIXEL_SHADER_COMBO( FLASHLIGHTDEPTHFILTERMODE, nShadowFilterMode );
SET_STATIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20b );
}
else
{
DECLARE_STATIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20 );
SET_STATIC_PIXEL_SHADER_COMBO( DETAILTEXTURE, hasDetailTexture );
SET_STATIC_PIXEL_SHADER_COMBO( BUMPMAP, hasBump );
SET_STATIC_PIXEL_SHADER_COMBO( DIFFUSEBUMPMAP, hasDiffuseBumpmap );
SET_STATIC_PIXEL_SHADER_COMBO( VERTEXCOLOR, hasVertexColor );
SET_STATIC_PIXEL_SHADER_COMBO( SELFILLUM, hasSelfIllum );
SET_STATIC_PIXEL_SHADER_COMBO( DETAIL_ALPHA_MASK_BASE_TEXTURE, bHasDetailAlpha );
SET_STATIC_PIXEL_SHADER_COMBO( FLASHLIGHT, hasFlashlight );
SET_STATIC_PIXEL_SHADER_COMBO( SEAMLESS, bSeamlessMapping );
SET_STATIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20 );
}
// HACK HACK HACK - enable alpha writes all the time so that we have them for
// underwater stuff.
// But only do it if we're not using the alpha already for translucency
pShaderShadow->EnableAlphaWrites( bFullyOpaque );
if( hasFlashlight )
{
FogToBlack();
}
else
{
DefaultFog();
}
}
DYNAMIC_STATE
{
if( hasBaseTexture )
{
BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME );
}
else
{
pShaderAPI->BindStandardTexture( SHADER_SAMPLER0, TEXTURE_WHITE );
}
// if( hasLightmap )
{
pShaderAPI->BindStandardTexture( SHADER_SAMPLER1, TEXTURE_LIGHTMAP );
}
bool bFlashlightShadows = false;
if( hasFlashlight )
{
VMatrix worldToTexture;
ITexture *pFlashlightDepthTexture;
FlashlightState_t state = pShaderAPI->GetFlashlightStateEx( worldToTexture, &pFlashlightDepthTexture );
bFlashlightShadows = state.m_bEnableShadows && ( pFlashlightDepthTexture != NULL );
SetFlashLightColorFromState( state, pShaderAPI );
BindTexture( SHADER_SAMPLER2, state.m_pSpotlightTexture, state.m_nSpotlightTextureFrame );
if( pFlashlightDepthTexture && g_pConfig->ShadowDepthTexture() )
{
BindTexture( SHADER_SAMPLER7, pFlashlightDepthTexture );
}
}
if( hasDetailTexture )
{
BindTexture( SHADER_SAMPLER3, DETAIL, DETAILFRAME );
}
if( hasBump )
{
if( !g_pConfig->m_bFastNoBump )
{
BindTexture( SHADER_SAMPLER4, BUMPMAP, BUMPFRAME );
}
else
{
pShaderAPI->BindStandardTexture( SHADER_SAMPLER4, TEXTURE_NORMALMAP_FLAT );
}
}
pShaderAPI->BindStandardTexture( SHADER_SAMPLER6, TEXTURE_NORMALIZATION_CUBEMAP_SIGNED );
// If we don't have a texture transform, we don't have
// to set vertex shader constants or run vertex shader instructions
// for the texture transform.
bool bHasTextureTransform =
!( params[BASETEXTURETRANSFORM]->MatrixIsIdentity() &&
params[BUMPTRANSFORM]->MatrixIsIdentity() );
bool bVertexShaderFastPath = !bHasTextureTransform;
if( params[DETAIL]->IsTexture() )
{
bVertexShaderFastPath = false;
}
if( pShaderAPI->GetIntRenderingParameter(INT_RENDERPARM_ENABLE_FIXED_LIGHTING)!=0 )
{
bVertexShaderFastPath = false;
}
float color[4] = { 1.0, 1.0, 1.0, 1.0 };
ComputeModulationColor( color );
if( !( bVertexShaderFastPath && color[0] == 1.0f && color[1] == 1.0f && color[2] == 1.0f && color[3] == 1.0f ) )
{
bVertexShaderFastPath = false;
s_pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_MODULATION_COLOR, color );
if (! bSeamlessMapping)
SetVertexShaderTextureTransform( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, BASETEXTURETRANSFORM );
if( hasBump && !bHasDetailAlpha )
{
SetVertexShaderTextureTransform( VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, BUMPTRANSFORM );
Assert( !hasDetailTexture );
}
}
MaterialFogMode_t fogType = pShaderAPI->GetSceneFogMode();
DECLARE_DYNAMIC_VERTEX_SHADER( sdk_lightmappedgeneric_vs20 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( DOWATERFOG, fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z );
SET_DYNAMIC_VERTEX_SHADER_COMBO( FASTPATH, bVertexShaderFastPath );
SET_DYNAMIC_VERTEX_SHADER_COMBO(
LIGHTING_PREVIEW, pShaderAPI->GetIntRenderingParameter(INT_RENDERPARM_ENABLE_FIXED_LIGHTING)!=0);
SET_DYNAMIC_VERTEX_SHADER( sdk_lightmappedgeneric_vs20 );
bool bWriteDepthToAlpha;
bool bWriteWaterFogToAlpha;
if( bFullyOpaque )
{
bWriteDepthToAlpha = pShaderAPI->ShouldWriteDepthToDestAlpha();
bWriteWaterFogToAlpha = (fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z);
AssertMsg( !(bWriteDepthToAlpha && bWriteWaterFogToAlpha), "Can't write two values to alpha at the same time." );
}
else
{
//can't write a special value to dest alpha if we're actually using as-intended alpha
bWriteDepthToAlpha = false;
bWriteWaterFogToAlpha = false;
}
if ( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_DYNAMIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20b );
// Don't write fog to alpha if we're using translucency
SET_DYNAMIC_PIXEL_SHADER_COMBO( WRITEWATERFOGTODESTALPHA, bWriteWaterFogToAlpha );
SET_DYNAMIC_PIXEL_SHADER_COMBO( WRITE_DEPTH_TO_DESTALPHA, bWriteDepthToAlpha );
SET_DYNAMIC_PIXEL_SHADER_COMBO( PIXELFOGTYPE, pShaderAPI->GetPixelFogCombo() );
SET_DYNAMIC_PIXEL_SHADER_COMBO( FLASHLIGHTSHADOWS, bFlashlightShadows );
SET_DYNAMIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20b );
}
else
{
DECLARE_DYNAMIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20 );
// Don't write fog to alpha if we're using translucency
SET_DYNAMIC_PIXEL_SHADER_COMBO( WRITEWATERFOGTODESTALPHA, (fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z) &&
(nBlendType != BT_BLENDADD) && (nBlendType != BT_BLEND) && !bIsAlphaTested );
SET_DYNAMIC_PIXEL_SHADER_COMBO( PIXELFOGTYPE, pShaderAPI->GetPixelFogCombo() );
SET_DYNAMIC_PIXEL_SHADER( sdk_worldtwotextureblend_ps20 );
}
// always set the transform for detail textures since I'm assuming that you'll
// always have a detailscale.
if( hasDetailTexture )
{
SetVertexShaderTextureScaledTransform( VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, BASETEXTURETRANSFORM, DETAILSCALE );
Assert( !( hasBump && !bHasDetailAlpha ) );
}
SetPixelShaderConstantGammaToLinear( 7, SELFILLUMTINT );
float eyePos[4];
pShaderAPI->GetWorldSpaceCameraPosition( eyePos );
pShaderAPI->SetPixelShaderConstant( 10, eyePos, 1 );
pShaderAPI->SetPixelShaderFogParams( 11 );
if ( bSeamlessMapping )
{
float map_scale[4]={ params[SEAMLESS_SCALE]->GetFloatValue(),0,0,0};
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, map_scale );
}
if( hasFlashlight )
{
VMatrix worldToTexture;
const FlashlightState_t &flashlightState = pShaderAPI->GetFlashlightState( worldToTexture );
// Set the flashlight attenuation factors
float atten[4];
atten[0] = flashlightState.m_fConstantAtten;
atten[1] = flashlightState.m_fLinearAtten;
atten[2] = flashlightState.m_fQuadraticAtten;
atten[3] = flashlightState.m_FarZ;
pShaderAPI->SetPixelShaderConstant( 20, atten, 1 );
// Set the flashlight origin
float pos[4];
pos[0] = flashlightState.m_vecLightOrigin[0];
pos[1] = flashlightState.m_vecLightOrigin[1];
pos[2] = flashlightState.m_vecLightOrigin[2];
pos[3] = 1.0f;
pShaderAPI->SetPixelShaderConstant( 15, pos, 1 );
pShaderAPI->SetPixelShaderConstant( 16, worldToTexture.Base(), 4 );
}
}
Draw();
}
SHADER_DRAW
{
//ConVarRef r_flashlight_version2 = ConVarRef( "r_flashlight_version2" );
bool bHasFlashlight = UsingFlashlight( params );
if ( bHasFlashlight /*&& ( IsX360() || r_flashlight_version2.GetInt() )*/ )
{
DrawPass( params, pShaderAPI, pShaderShadow, false, vertexCompression );
SHADOW_STATE
{
SetInitialShadowState( );
}
}
DrawPass( params, pShaderAPI, pShaderShadow, bHasFlashlight, vertexCompression );
}
END_SHADER
| 34.940711 | 155 | 0.732466 | [
"transform"
] |
b7b2d9355e466f604992fe771b7bcac428e89632 | 1,307 | hpp | C++ | src/Magma/Framework/Thread/Mutex.hpp | RiscadoA/Magma | ea025e6762366d59b4841d174076c5aed3156623 | [
"MIT"
] | 1 | 2018-06-27T19:51:40.000Z | 2018-06-27T19:51:40.000Z | src/Magma/Framework/Thread/Mutex.hpp | RiscadoA/Simple-Game | ea025e6762366d59b4841d174076c5aed3156623 | [
"MIT"
] | 30 | 2018-08-19T15:42:59.000Z | 2018-09-09T19:09:34.000Z | src/Magma/Framework/Thread/Mutex.hpp | RiscadoA/Simple-Game | ea025e6762366d59b4841d174076c5aed3156623 | [
"MIT"
] | null | null | null | #pragma once
#include "../Memory/Handle.hpp"
#include "../Memory/Allocator.hpp"
#include "Mutex.h"
namespace Magma
{
namespace Framework
{
namespace Thread
{
/// <summary>
/// Mutex handle.
/// </summary>
class HMutex : public Memory::Handle
{
public:
using Handle::Handle;
using Handle::operator=;
inline HMutex(const Memory::Handle& object) : Memory::Handle(object) {}
/// <summary>
/// Locks the mutex (if already locked wait until it is unlocked).
/// </summary>
/// <param name="timeOut">Wait timeout in milliseconds (set to 0 to be infinite)</param>
/// <returns>True if locked the mutex, otherwise false</returns>
bool Lock(mfmU64 timeOut = 0);
/// <summary>
/// Unlocks the mutex.
/// </summary>
void Unlock();
/// <summary>
/// Tries to lock the mutex. If it was already locked, returns false, otherwise returns true.
/// </summary>
/// <returns>True if locked the mutex, otherwise false</returns>
bool TryLock();
};
/// <summary>
/// Creates a mutex.
/// </summary>
/// <param name="allocator">Allocator used to allocate the mutex object</param>
/// <returns>Mutex handle</returns>
HMutex CreateMutex(Memory::HAllocator allocator = Memory::StandardAllocator);
}
}
}
| 25.627451 | 98 | 0.629686 | [
"object"
] |
5d9f27a69419a6ab38025d5d427567d83eb10df7 | 1,187 | cpp | C++ | atcoder/agc009/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | atcoder/agc009/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | 19 | 2016-05-04T02:46:31.000Z | 2021-11-27T06:18:33.000Z | atcoder/agc009/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q>
ostream& operator << (ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
const int N = 100000 + 10;
int a[N];
vector<int> g[N];
int rec(int curr)
{
vector<int> v;
each (next, g[curr]) {
// cout << curr+1 << " -> " << next+1 << endl;
v.push_back(rec(next) + 1);
}
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
int mx = -1;
for (int i = 0; i < v.size(); ++i) {
mx = max(mx, v[i] + i);
}
// cout << curr+1 << ": " ; each (i, v) cout << i+1 << ' '; cout << endl;
return v.size() ? mx : 0;
}
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
while (cin >> n) {
fill(g, g + N, vector<int>());
for (int i = 1; i < n; ++i) {
int a;
cin >> a;
// cout << make_pair(a - 1 + 1, i + 1) << endl;
g[a - 1].push_back(i);
}
cout << rec(0) << endl;
// cout << endl;
}
return 0;
}
| 19.783333 | 75 | 0.506318 | [
"vector"
] |
5da28ac63f05c0e90d83f50fbc3bc5542068bb2a | 2,024 | hpp | C++ | include/bdlearn/SAMMEEnsemble.hpp | billythedummy/bdlearn | bdb7b22c326f8057ec3ec06a701d00885e801bfd | [
"MIT"
] | 2 | 2019-12-04T08:24:17.000Z | 2020-01-31T23:29:52.000Z | include/bdlearn/SAMMEEnsemble.hpp | billythedummy/bdlearn | bdb7b22c326f8057ec3ec06a701d00885e801bfd | [
"MIT"
] | null | null | null | include/bdlearn/SAMMEEnsemble.hpp | billythedummy/bdlearn | bdb7b22c326f8057ec3ec06a701d00885e801bfd | [
"MIT"
] | null | null | null | #ifndef _BDLEARN_SAMME_ENSEMBLE_H_
#define _BDLEARN_SAMME_ENSEMBLE_H_
#include "Halide.h"
#include "bdlearn/BufDims.hpp"
#include "bdlearn/Model.hpp"
#include "bdlearn/DataSet.hpp"
namespace bdlearn {
class SAMMEEnsemble {
public:
// constructor
SAMMEEnsemble(const bool training)
: training_(training), batch_size_(0),
current_m_i_(0) {}
// Destructor
virtual ~SAMMEEnsemble();
// public functions
float train_step(void); // trains one model of the ensemble, returns error rate
void forward_i(Halide::Buffer<float> out, Halide::Buffer<float> in); // inference
void forward_batch(float* out, Halide::Buffer<float> in);
void add_model(Model* model);
float eval(DataSet* dataset);
// getter setters
void set_lr(const float lr) {for (auto& model_ptr: model_ptrs_) model_ptr->set_lr(lr);}
void set_batch_size(const int batch_size);
void set_dataset(DataSet* dataset);
int get_n_models(void) {return model_ptrs_.size();}
// for debugging
float* get_w(void) {return w_.get();}
std::vector<float> get_alphas(void) {return alphas_;} // copies?
// friend operators
//friend std::ostream& operator<<(std::ostream& os, const Layer& l);
private:
// delete assigment
Model& operator=(const Model& ref) = delete;
// private fields
std::vector< std::unique_ptr<Model> > model_ptrs_;
std::vector<float> alphas_; // weights for each model
bufdims in_dims_;
int classes_;
// training params
std::unique_ptr<float[]> w_; // weights for each training example
DataSet* dataset_;
bool training_;
int batch_size_;
float lr_;
int current_m_i_; // index of model currently being trained
};
}
#endif | 36.142857 | 99 | 0.590909 | [
"vector",
"model"
] |
5da5738b433f66b709984e8985a7cdde647cbd8f | 1,401 | hpp | C++ | src/entities/items/Ghost.hpp | lonnort/thga | 22cc8868ec8bf9cee195771f0a88bef4d1fa1013 | [
"BSL-1.0"
] | 1 | 2022-02-14T12:32:23.000Z | 2022-02-14T12:32:23.000Z | src/entities/items/Ghost.hpp | lonnort/thga | 22cc8868ec8bf9cee195771f0a88bef4d1fa1013 | [
"BSL-1.0"
] | 16 | 2022-02-04T14:26:25.000Z | 2022-02-04T14:27:18.000Z | src/entities/items/Ghost.hpp | lonnort/thga | 22cc8868ec8bf9cee195771f0a88bef4d1fa1013 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include "Item.hpp"
namespace Pacenstein {
/**
* Ghosts are item that move around on their own volition.
*
* Every ghost has a different AI for attacking the Player. Every ghost is capable of deducting
* a life from the player, unless the player has eaten a PowerPellet, then the ghosts will
* scatter and flee from the player. If the player were to eat a ghost in this state points are
* awarded based on how many ghosts were eaten: 200 for the first, then 400, 800, and 1600 last.
*/
class Ghost : public Item {
public:
/**
* Constructor of the Ghost class.
*
* \param x The x position as a float of a ghost.
* \param y The y position as a float of a ghost.
*/
Ghost(float x, float y);
/**
* Constructor of the Ghost class.
*
* \param xy The position of a ghost as a sf::Vector2f.
*/
explicit Ghost(sf::Vector2f xy);
/**
* Interaction of a ghost with the player.
*
* Removes 1 live from the player.
*
* \param data A reference to the data object.
*/
void interact(game_data_ref_t data) override;
virtual sf::Vector2f move(const map_t & worldMap) = 0;
virtual int getDirection() = 0;
virtual bool is_collected() = 0;
};
}
| 29.808511 | 100 | 0.586724 | [
"object"
] |
5db0c20805e690d7699fc310ed83eb6c1837abae | 9,467 | cpp | C++ | test/test_cfd_transaction_controller.cpp | atomicfinance/cfd | 6e1ed9901be749408ec9b886973ce1e7f9a395ab | [
"MIT"
] | 4 | 2019-10-12T11:05:15.000Z | 2020-11-06T16:09:54.000Z | test/test_cfd_transaction_controller.cpp | atomicfinance/cfd | 6e1ed9901be749408ec9b886973ce1e7f9a395ab | [
"MIT"
] | 133 | 2019-10-04T05:36:15.000Z | 2022-02-07T04:02:39.000Z | test/test_cfd_transaction_controller.cpp | atomicfinance/cfd | 6e1ed9901be749408ec9b886973ce1e7f9a395ab | [
"MIT"
] | 2 | 2019-11-08T06:43:13.000Z | 2019-11-15T16:14:10.000Z | #include "gtest/gtest.h"
#include <vector>
#include "cfdcore/cfdcore_amount.h"
#include "cfdcore/cfdcore_bytedata.h"
#include "cfdcore/cfdcore_coin.h"
#include "cfdcore/cfdcore_exception.h"
#include "cfdcore/cfdcore_key.h"
#include "cfdcore/cfdcore_transaction_common.h"
#include "cfd/cfd_transaction.h"
using cfd::core::Amount;
using cfd::core::ByteData;
using cfd::core::ByteData256;
using cfd::core::CfdException;
using cfd::core::Privkey;
using cfd::core::Pubkey;
using cfd::core::Script;
using cfd::core::ScriptBuilder;
using cfd::core::ScriptOperator;
using cfd::core::SigHashAlgorithm;
using cfd::core::SigHashType;
using cfd::core::SignatureUtil;
using cfd::core::Txid;
using cfd::core::WitnessVersion;
using cfd::TransactionController;
TEST(TransactionController, Constructor) {
// input-only transaction
std::string expect_tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
std::string expect_tx2 = "02000000000101aca6c902e9569c99e172c22182f943e4ab15f28602ab248f65c864874a9ddc860000000000ffffffff01005ed0b20000000017a914eca3232c3a28a4d0c03b374d0f6053e9e546e997870247304402205c8a6b770633449f129579776dfd0a839c9749860e17f7a2bde7927e4b9a8c7202205c5a10a57acef9cadd37d72fece91821db547e9c3447f2b1071f664d393b7a5c012102f56451fc1fd9040652ff9a700cf914ad1df1c8f9e82f3fe96ca01b6cd47293ef00000000";
TransactionController txc1(expect_tx);
TransactionController txc2(expect_tx2);
struct TransactionControllerTest_struct {
TransactionController txc_a;
TransactionController txc_b;
};
TransactionControllerTest_struct struct_data;
struct_data.txc_a = txc1;
struct_data.txc_b = txc2;
EXPECT_STREQ(struct_data.txc_a.GetHex().c_str(), expect_tx.c_str());
EXPECT_STREQ(struct_data.txc_b.GetHex().c_str(), expect_tx2.c_str());
}
TEST(TransactionController, GetVsizeIgnoreTxIn) {
std::string expect_tx = "02000000000101aca6c902e9569c99e172c22182f943e4ab15f28602ab248f65c864874a9ddc860000000000ffffffff01005ed0b20000000017a914eca3232c3a28a4d0c03b374d0f6053e9e546e997870247304402205c8a6b770633449f129579776dfd0a839c9749860e17f7a2bde7927e4b9a8c7202205c5a10a57acef9cadd37d72fece91821db547e9c3447f2b1071f664d393b7a5c012102f56451fc1fd9040652ff9a700cf914ad1df1c8f9e82f3fe96ca01b6cd47293ef00000000";
TransactionController txc(expect_tx);
EXPECT_EQ(txc.GetSizeIgnoreTxIn(), 42);
EXPECT_EQ(txc.GetVsizeIgnoreTxIn(), 42);
}
TEST(TransactionController, CreateP2wpkhSignatureHash_Test) {
// input-only transaction
std::string tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
Txid txid("0000000000000000000000000000000000000000000000000123456789abcdef");
uint32_t vout = 0;
Pubkey pubkey("023e5e7a4a435f526a8b34d54c7355c8e57392b591b5a189ec88731953c568f8da");
SigHashType sighash_type(SigHashAlgorithm::kSigHashAll);
Amount amount = Amount::CreateBySatoshiAmount(21000000);
std::string expect_sighash = "a3f0fa9b3e727bb746509b40a7cac316bf36685d55bebd6c7271d6e3a976f12d";
TransactionController txc(tx);
ByteData sighash;
EXPECT_NO_THROW(sighash = txc.CreateSignatureHash(txid, vout, pubkey, sighash_type, amount, WitnessVersion::kVersion0));
EXPECT_STREQ(sighash.GetHex().c_str(), expect_sighash.c_str());
}
TEST(TransactionController, CreateP2wshSignatureHash_Test) {
// input-only transaction
std::string tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
Txid txid("0000000000000000000000000000000000000000000000000123456789abcdef");
uint32_t vout = 0;
Script witness_script("0020aa7566645d0bce0682dca7086e103f00147bb3f4fb4e3f2e6113cb6f485e6789");
SigHashType sighash_type(SigHashAlgorithm::kSigHashAll);
Amount amount = Amount::CreateBySatoshiAmount(21000000);
std::string expect_sighash = "4a9fc1813c51bdf4f14020c7ae570b22d9005da65a37cbf9cf10b79712a8dcc9";
TransactionController txc(tx);
ByteData sighash;
EXPECT_NO_THROW(sighash = txc.CreateSignatureHash(txid, vout, witness_script, sighash_type, amount, WitnessVersion::kVersion0));
EXPECT_STREQ(sighash.GetHex().c_str(), expect_sighash.c_str());
}
TEST(TransactionController, VerifyInputSignature_TEST_PKH) {
// input-only transaction
std::string tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
TransactionController txc(tx);
Privkey privkey = Privkey::GenerageRandomKey();
// create sighash
Txid txid("0000000000000000000000000000000000000000000000000123456789abcdef");
uint32_t vout = 0;
Pubkey pubkey = privkey.GeneratePubkey();
SigHashType sighash_type(SigHashAlgorithm::kSigHashAll);
ByteData sighash;
EXPECT_NO_THROW(sighash = txc.CreateSignatureHash(txid, vout, pubkey,
sighash_type));
ByteData signature;
EXPECT_NO_THROW(signature = SignatureUtil::CalculateEcSignature(
ByteData256(sighash.GetBytes()), privkey));
EXPECT_TRUE(txc.VerifyInputSignature(signature, pubkey, txid, vout,
sighash_type));
// check signature another pubkey
Privkey dummy;
while(privkey.GetHex() == (dummy = Privkey::GenerageRandomKey()).GetHex()) {
// do nothing
}
EXPECT_FALSE(txc.VerifyInputSignature(signature, dummy.GeneratePubkey(), txid, vout, sighash_type));
}
TEST(TransactionController, VerifyInputSignature_TEST_SH) {
// input-only transaction
std::string tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
TransactionController txc(tx);
Privkey privkey = Privkey::GenerageRandomKey();
ScriptBuilder sb = ScriptBuilder();
// create sighash
Txid txid("0000000000000000000000000000000000000000000000000123456789abcdef");
uint32_t vout = 0;
// create 1-of-2 multisig script
Pubkey pubkey = privkey.GeneratePubkey();
Script redeem_script = sb
.AppendOperator(ScriptOperator::OP_1)
.AppendData(pubkey)
.AppendData(Pubkey("0229ebd1cac7855ca60b0846bd179ff3d411f807f3f3a43abf498e0a415c94d622"))
.AppendOperator(ScriptOperator::OP_2)
.AppendOperator(ScriptOperator::OP_CHECKMULTISIG)
.Build();
SigHashType sighash_type(SigHashAlgorithm::kSigHashAll);
ByteData sighash;
EXPECT_NO_THROW(sighash = txc.CreateSignatureHash(txid, vout, redeem_script,
sighash_type));
ByteData signature;
EXPECT_NO_THROW(signature = SignatureUtil::CalculateEcSignature(
ByteData256(sighash.GetBytes()), privkey));
EXPECT_TRUE(txc.VerifyInputSignature(signature, pubkey, txid, vout,
redeem_script, sighash_type));
}
TEST(TransactionController, VerifyInputSignature_TEST_WPKH) {
// input-only transaction
std::string tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
TransactionController txc(tx);
Privkey privkey = Privkey::GenerageRandomKey();
// create sighash
Txid txid("0000000000000000000000000000000000000000000000000123456789abcdef");
uint32_t vout = 0;
Pubkey pubkey = privkey.GeneratePubkey();
SigHashType sighash_type(SigHashAlgorithm::kSigHashAll);
Amount amount = Amount::CreateBySatoshiAmount(21000000);
ByteData sighash;
EXPECT_NO_THROW(sighash = txc.CreateSignatureHash(txid, vout, pubkey,
sighash_type, amount, WitnessVersion::kVersion0));
ByteData signature;
EXPECT_NO_THROW(signature = SignatureUtil::CalculateEcSignature(
ByteData256(sighash.GetBytes()), privkey));
EXPECT_TRUE(txc.VerifyInputSignature(signature, pubkey, txid, vout,
sighash_type, amount, WitnessVersion::kVersion0));
}
TEST(TransactionController, VerifyInputSignature_TEST_WSH) {
// input-only transaction
std::string tx = "0200000001efcdab89674523010000000000000000000000000000000000000000000000000000000000ffffffff01406f4001000000001976a9144b8fe2da0c979ec6027dc2287e65569f41d483ec88ac00000000";
TransactionController txc(tx);
Privkey privkey = Privkey::GenerageRandomKey();
ScriptBuilder sb = ScriptBuilder();
// create sighash
Txid txid("0000000000000000000000000000000000000000000000000123456789abcdef");
uint32_t vout = 0;
// create 1-of-2 multisig script
Pubkey pubkey = privkey.GeneratePubkey();
Script redeem_script = sb
.AppendOperator(ScriptOperator::OP_1)
.AppendData(pubkey)
.AppendData(Pubkey("0229ebd1cac7855ca60b0846bd179ff3d411f807f3f3a43abf498e0a415c94d622"))
.AppendOperator(ScriptOperator::OP_2)
.AppendOperator(ScriptOperator::OP_CHECKMULTISIG)
.Build();
SigHashType sighash_type(SigHashAlgorithm::kSigHashAll);
Amount amount = Amount::CreateBySatoshiAmount(21000000);
ByteData sighash;
EXPECT_NO_THROW(sighash = txc.CreateSignatureHash(txid, vout, redeem_script,
sighash_type, amount, WitnessVersion::kVersion0));
ByteData signature;
EXPECT_NO_THROW(signature = SignatureUtil::CalculateEcSignature(
ByteData256(sighash.GetBytes()), privkey));
EXPECT_TRUE(txc.VerifyInputSignature(signature, pubkey, txid, vout,
redeem_script, sighash_type, amount, WitnessVersion::kVersion0));
} | 45.080952 | 414 | 0.820218 | [
"vector"
] |
5db4520fde7a1617f21918b57903191b9c10c200 | 2,200 | hpp | C++ | Source/AllProjects/Drivers/CQCGenDrv/Server/CQCGenDrvS.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Drivers/CQCGenDrv/Server/CQCGenDrvS.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Drivers/CQCGenDrv/Server/CQCGenDrvS.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCGenDrvS.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 04/09/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the main header of the CQCGenDrv facility. This facility defines
// the macro language level classes that are the basis of device drivers
// written in the macro language. There is one major one, which is the
// base class for the driver itself, and some helper classes. It also
// provides a derivative of the standard CQC C++ server side driver class
// that understands how to glue the C++ level driver interfaces to the
// macro level interfaces.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
#pragma once
// ---------------------------------------------------------------------------
// Set up our import/export attributes
// ---------------------------------------------------------------------------
#if defined(PROJ_CQCGENDRVS)
#define CQCGENDRVSEXPORT CID_DLLEXPORT
#else
#define CQCGENDRVSEXPORT CID_DLLIMPORT
#endif
// ---------------------------------------------------------------------------
// Include our underlying headers
// ---------------------------------------------------------------------------
#include "CIDOrbUC.hpp"
#include "CIDMacroEng.hpp"
#include "CQCKit.hpp"
#include "CQCDriver.hpp"
#include "CQCMEng.hpp"
// ---------------------------------------------------------------------------
// Include our headers, in the needed order.
// ---------------------------------------------------------------------------
#include "CQCGenDrvS_ErrorIds.hpp"
#include "CQCGenDrvS_Type.hpp"
#include "CQCGenDrvS_DriverGlue.hpp"
#include "CQCGenDrvS_DriverClass.hpp"
#include "CQCGenDrvS_ThisFacility.hpp"
// ---------------------------------------------------------------------------
// Export the facility object lazy eval method
// ---------------------------------------------------------------------------
extern CQCGENDRVSEXPORT TFacCQCGenDrvS& facCQCGenDrvS();
| 31.884058 | 78 | 0.518182 | [
"object"
] |
5dc4a9832ed162e31602199d29b5980fa01e6d4a | 1,926 | hpp | C++ | benchsuite/utils/memory.hpp | angelicadavila/UNIZAR_PHD | 532a87467ceb49d3c3851bb23e26003bfc1888d3 | [
"MIT"
] | null | null | null | benchsuite/utils/memory.hpp | angelicadavila/UNIZAR_PHD | 532a87467ceb49d3c3851bb23e26003bfc1888d3 | [
"MIT"
] | null | null | null | benchsuite/utils/memory.hpp | angelicadavila/UNIZAR_PHD | 532a87467ceb49d3c3851bb23e26003bfc1888d3 | [
"MIT"
] | null | null | null | #ifndef ENGINECL_MEMORY_HPP
#define ENGINECL_MEMORY_HPP
#include <cstdint>
#include <iostream>
#include <type_traits>
#include <vector>
template<typename T, std::size_t N = alignof(T)>
class aligned_allocator
{
// helper type with the alignment we want
typedef typename std::aligned_storage<sizeof(T), N>::type aligned_type;
public:
// type to allocate
using value_type = T;
// ensure basic special class methods are enabled
aligned_allocator() = default;
aligned_allocator(const aligned_allocator&) = default;
aligned_allocator& operator=(const aligned_allocator&) = default;
aligned_allocator(aligned_allocator&&) noexcept = default;
aligned_allocator& operator=(aligned_allocator&&) noexcept = default;
// allow construction from an allocator for another type
// (with the same alignment)
template<typename U>
aligned_allocator(const aligned_allocator<U>&)
{
}
// implementations may derive from the allocator polymorphically
virtual ~aligned_allocator() noexcept = default;
// rebinding the allocator for another type should respect the alignment
// of that other type
template<typename U>
struct rebind
{
using other = aligned_allocator<U>;
};
// allocate a type that we know will have the correct alignment
// then reinterpret the pointer
T* allocate(std::size_t n) { return reinterpret_cast<T*>(new aligned_type[n]); }
// deallocate previously allocated memory
void deallocate(T* p, std::size_t)
{ // don't care about size here
delete[] reinterpret_cast<aligned_type*>(p);
}
};
template<typename T, typename U, std::size_t N>
constexpr bool
operator==(const aligned_allocator<T, N>&, const aligned_allocator<U, N>&)
{
return true;
}
template<typename T, typename U, std::size_t N>
constexpr bool
operator!=(const aligned_allocator<T, N>&, const aligned_allocator<U, N>&)
{
return false;
}
#endif /* ENGINECL_MEMORY_HPP */
| 27.514286 | 82 | 0.734683 | [
"vector"
] |
5dc4efe7d93104b9dc2d51e2f894e479b06158b4 | 18,849 | cpp | C++ | work/desenet-sensor/src/common/platform/nucleo-stm32l476rg/board/display/eplib/paint.cpp | MacherelR/DeSemProject_20212022 | 7314e5787a3ff2ca5bf95c6de7fbbee9598b98ea | [
"MIT"
] | null | null | null | work/desenet-sensor/src/common/platform/nucleo-stm32l476rg/board/display/eplib/paint.cpp | MacherelR/DeSemProject_20212022 | 7314e5787a3ff2ca5bf95c6de7fbbee9598b98ea | [
"MIT"
] | null | null | null | work/desenet-sensor/src/common/platform/nucleo-stm32l476rg/board/display/eplib/paint.cpp | MacherelR/DeSemProject_20212022 | 7314e5787a3ff2ca5bf95c6de7fbbee9598b98ea | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <cstring> // memset()
#include <cmath>
#include "paint.h"
namespace ep {
Paint::Paint()
{
buffer = nullptr;
}
void Paint::initialize(ep::Display * epd)
{
this->epd = epd;
}
/******************************************************************************
function: Set up buffer
parameter:
buffer : Pointer to the buffer cache
width : The width of the picture
Height : The height of the picture
Color : Whether the picture is inverted
******************************************************************************/
void Paint::setBuffer(uint8_t * buffer, uint16_t Width, uint16_t Height, uint16_t Rotate, uint16_t Color)
{
this->buffer = buffer;
this->width = Width;
this->height = Height;
this->widthMemory = Width;
this->heightMemory = Height;
this->color = Color;
this->widthByte = (Width % 8 == 0) ? (Width / 8) : (Width / 8 + 1);
this->heightByte = Height;
this->rotate = Rotate;
this->mirror = MIRROR_NONE;
if (Rotate == EP_DISPLAY_ROTATE_0 || Rotate == EP_DISPLAY_ROTATE_180)
{
this->width = Width;
this->height = Height;
}
else
{
this->width = Height;
this->height = Width;
}
this->pixelCount = width * height;
this->bytesCount = pixelCount / 8;
this->buffer = buffer;
}
/******************************************************************************
function: Select buffer rotate
parameter:
Rotate : 0,90,180,270
******************************************************************************/
void Paint::setRotate(Rotation Rotate)
{
if (Rotate == EP_DISPLAY_ROTATE_0 || Rotate == EP_DISPLAY_ROTATE_90 || Rotate == EP_DISPLAY_ROTATE_180 || Rotate == EP_DISPLAY_ROTATE_270)
{
this->rotate = Rotate;
}
}
/******************************************************************************
function: Select buffer mirror
parameter:
mirror : Not mirror,Horizontal mirror,Vertical mirror,Origin mirror
******************************************************************************/
void Paint::setMirroring(uint8_t mirror)
{
if (mirror == MIRROR_NONE || mirror == MIRROR_HORIZONTAL ||
mirror == MIRROR_VERTICAL || mirror == MIRROR_ORIGIN)
{
this->mirror = mirror;
}
}
/******************************************************************************
function: Draw Pixels
parameter:
Xpoint : At point X
Ypoint : At point Y
Color : Painted colors
******************************************************************************/
void Paint::setPixel(uint16_t Xpoint, uint16_t Ypoint, uint16_t Color, bool refresh)
{
uint16_t X, Y;
uint32_t Addr;
uint8_t Rdata;
if (Xpoint > this->width || Ypoint > this->height)
{
return;
}
switch (this->rotate)
{
case 0:
X = Xpoint;
Y = Ypoint;
break;
case 90:
X = this->widthMemory - Ypoint - 1;
Y = Xpoint;
break;
case 180:
X = this->widthMemory - Xpoint - 1;
Y = this->heightMemory - Ypoint - 1;
break;
case 270:
X = Ypoint;
Y = this->heightMemory - Xpoint - 1;
break;
default:
assert(false);
return;
}
switch (this->mirror)
{
case MIRROR_NONE:
break;
case MIRROR_HORIZONTAL:
X = this->widthMemory - X - 1;
break;
case MIRROR_VERTICAL:
Y = this->heightMemory - Y - 1;
break;
case MIRROR_ORIGIN:
X = this->widthMemory - X - 1;
Y = this->heightMemory - Y - 1;
break;
default:
return;
}
if (X > this->widthMemory || Y > this->heightMemory)
{
return;
}
Addr = X / 8 + Y * this->widthByte;
Rdata = this->buffer[Addr];
if (Color == EP_DISPLAY_BLACK)
this->buffer[Addr] = Rdata & ~(0x80 >> (X % 8));
else
this->buffer[Addr] = Rdata | (0x80 >> (X % 8));
if (refresh)
{
update();
}
}
/******************************************************************************
function: Clear the color of the picture
parameter:
Color : Painted colors
******************************************************************************/
void Paint::clear(uint8_t Color, bool refresh)
{
memset(this->buffer, Color, bytesCount);
if (refresh)
{
update();
}
}
/******************************************************************************
function: Clear the color of a window
parameter:
Xstart : x starting point
Ystart : Y starting point
Xend : x end point
Yend : y end point
******************************************************************************/
void Paint::clearWindows(uint16_t Xstart, uint16_t Ystart, uint16_t Xend, uint16_t Yend, uint16_t Color)
{
uint16_t X, Y;
for (Y = Ystart; Y < Yend; Y++)
{
for (X = Xstart; X < Xend; X++)
{ //8 pixel = 1 byte
setPixel(X, Y, Color);
}
}
update();
}
void Paint::update()
{
epd->display(buffer);
}
/******************************************************************************
function: Draw Point(Xpoint, Ypoint) Fill the color
parameter:
Xpoint : The Xpoint coordinate of the point
Ypoint : The Ypoint coordinate of the point
Color : Set color
Dot_Pixel : point size
refresh : Send or not refresh command
******************************************************************************/
void Paint::drawPoint(uint16_t Xpoint, uint16_t Ypoint, uint16_t Color,
DOT_PIXEL Dot_Pixel, DOT_STYLE DOT_STYLE, bool refresh)
{
int16_t XDir_Num, YDir_Num;
if (Xpoint > this->width || Ypoint > this->height)
{
return;
}
if (DOT_STYLE == DOT_FILL_AROUND)
{
for (XDir_Num = 0; XDir_Num < 2 * Dot_Pixel - 1; XDir_Num++)
{
for (YDir_Num = 0; YDir_Num < 2 * Dot_Pixel - 1; YDir_Num++)
{
if (Xpoint + XDir_Num - Dot_Pixel < 0 || Ypoint + YDir_Num - Dot_Pixel < 0)
break;
setPixel(Xpoint + XDir_Num - Dot_Pixel, Ypoint + YDir_Num - Dot_Pixel, Color, refresh);
}
}
}
else
{
for (XDir_Num = 0; XDir_Num < Dot_Pixel; XDir_Num++)
{
for (YDir_Num = 0; YDir_Num < Dot_Pixel; YDir_Num++)
{
setPixel(Xpoint + XDir_Num - 1, Ypoint + YDir_Num - 1, Color, refresh);
}
}
}
if (refresh)
{
update();
}
}
/******************************************************************************
function: Draw a line of arbitrary slope
parameter:
Xstart : Starting Xpoint point coordinates
Ystart : Starting Xpoint point coordinates
Xend : End point Xpoint coordinate
Yend : End point Ypoint coordinate
Color : The color of the line segment
refresh : Send or not refresh command
******************************************************************************/
void Paint::drawLine(uint16_t Xstart, uint16_t Ystart, uint16_t Xend, uint16_t Yend,
uint16_t Color, LINE_STYLE Line_Style, DOT_PIXEL Dot_Pixel, bool refresh)
{
uint16_t Xpoint, Ypoint;
int dx, dy;
int XAddway, YAddway;
int Esp;
char Dotted_Len;
if (Xstart > this->width || Ystart > this->height ||
Xend > this->width || Yend > this->height)
{
return;
}
Xpoint = Xstart;
Ypoint = Ystart;
dx = (int)Xend - (int)Xstart >= 0 ? Xend - Xstart : Xstart - Xend;
dy = (int)Yend - (int)Ystart <= 0 ? Yend - Ystart : Ystart - Yend;
// Increment direction, 1 is positive, -1 is counter;
XAddway = Xstart < Xend ? 1 : -1;
YAddway = Ystart < Yend ? 1 : -1;
//Cumulative error
Esp = dx + dy;
Dotted_Len = 0;
for (;;)
{
Dotted_Len++;
//Painted dotted line, 2 point is really virtual
if (Line_Style == LINE_STYLE_DOTTED && Dotted_Len % 3 == 0)
{
drawPoint(Xpoint, Ypoint, EP_DISPLAY_IMAGE_BACKGROUND, Dot_Pixel, DOT_STYLE_DFT, refresh);
Dotted_Len = 0;
}
else
{
drawPoint(Xpoint, Ypoint, Color, Dot_Pixel, DOT_STYLE_DFT, refresh);
}
if (2 * Esp >= dy)
{
if (Xpoint == Xend)
break;
Esp += dy;
Xpoint += XAddway;
}
if (2 * Esp <= dx)
{
if (Ypoint == Yend)
break;
Esp += dx;
Ypoint += YAddway;
}
}
if (refresh)
{
update();
}
}
/******************************************************************************
function: Draw a rectangle
parameter:
Xstart :Rectangular Starting Xpoint point coordinates
Ystart :Rectangular Starting Xpoint point coordinates
Xend :Rectangular End point Xpoint coordinate
Yend :Rectangular End point Ypoint coordinate
Color :The color of the Rectangular segment
Filled : Whether it is filled--- 1 solid 0:empty
refresh : Send or not refresh command
******************************************************************************/
void Paint::drawRectangle(uint16_t Xstart, uint16_t Ystart, uint16_t Xend, uint16_t Yend,
uint16_t Color, DRAW_FILL Filled, DOT_PIXEL Dot_Pixel,bool refresh)
{
uint16_t Ypoint;
if (Xstart > this->width || Ystart > this->height ||
Xend > this->width || Yend > this->height)
{
return;
}
if (Filled)
{
for (Ypoint = Ystart; Ypoint < Yend; Ypoint++)
{
drawLine(Xstart, Ypoint, Xend, Ypoint, Color, LINE_STYLE_SOLID, Dot_Pixel, false);
}
}
else
{
drawLine(Xstart, Ystart, Xend, Ystart, Color, LINE_STYLE_SOLID, Dot_Pixel, false);
drawLine(Xstart, Ystart, Xstart, Yend, Color, LINE_STYLE_SOLID, Dot_Pixel, false);
drawLine(Xend, Yend, Xend, Ystart, Color, LINE_STYLE_SOLID, Dot_Pixel, false);
drawLine(Xend, Yend, Xstart, Yend, Color, LINE_STYLE_SOLID, Dot_Pixel, false);
}
if (refresh)
{
update();
}
}
/******************************************************************************
function: Use the 8-point method to draw a circle of the
specified size at the specified position->
parameter:
X_Center :Center X coordinate
Y_Center :Center Y coordinate
Radius :circle Radius
Color :The color of the :circle segment
Filled : Whether it is filled: 1 filling 0:Do not
refresh : Send or not refresh command
******************************************************************************/
void Paint::drawCircle(uint16_t X_Center, uint16_t Y_Center, uint16_t Radius,
uint16_t Color, DRAW_FILL Draw_Fill, DOT_PIXEL Dot_Pixel, bool refresh)
{
int16_t Esp, sCountY;
int16_t XCurrent, YCurrent;
if (X_Center > this->width || Y_Center >= this->height)
{
return;
}
//Draw a circle from(0, R) as a starting point
XCurrent = 0;
YCurrent = Radius;
//Cumulative error,judge the next point of the logo
Esp = 3 - (Radius << 1);
if (Draw_Fill == DRAW_FILL_FULL)
{
while (XCurrent <= YCurrent)
{ //Realistic circles
for (sCountY = XCurrent; sCountY <= YCurrent; sCountY++)
{
drawPoint(X_Center + XCurrent, Y_Center + sCountY, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //1
drawPoint(X_Center - XCurrent, Y_Center + sCountY, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //2
drawPoint(X_Center - sCountY, Y_Center + XCurrent, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //3
drawPoint(X_Center - sCountY, Y_Center - XCurrent, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //4
drawPoint(X_Center - XCurrent, Y_Center - sCountY, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //5
drawPoint(X_Center + XCurrent, Y_Center - sCountY, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //6
drawPoint(X_Center + sCountY, Y_Center - XCurrent, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false); //7
drawPoint(X_Center + sCountY, Y_Center + XCurrent, Color, DOT_PIXEL_DFT, DOT_STYLE_DFT, false);
}
if (Esp < 0)
Esp += 4 * XCurrent + 6;
else
{
Esp += 10 + 4 * (XCurrent - YCurrent);
YCurrent--;
}
XCurrent++;
}
}
else
{ //Draw a hollow circle
while (XCurrent <= YCurrent)
{
drawPoint(X_Center + XCurrent, Y_Center + YCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //1
drawPoint(X_Center - XCurrent, Y_Center + YCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //2
drawPoint(X_Center - YCurrent, Y_Center + XCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //3
drawPoint(X_Center - YCurrent, Y_Center - XCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //4
drawPoint(X_Center - XCurrent, Y_Center - YCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //5
drawPoint(X_Center + XCurrent, Y_Center - YCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //6
drawPoint(X_Center + YCurrent, Y_Center - XCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //7
drawPoint(X_Center + YCurrent, Y_Center + XCurrent, Color, Dot_Pixel, DOT_STYLE_DFT, false); //0
if (Esp < 0)
Esp += 4 * XCurrent + 6;
else
{
Esp += 10 + 4 * (XCurrent - YCurrent);
YCurrent--;
}
XCurrent++;
}
}
if (refresh)
{
update();
}
}
/******************************************************************************
function: Show characters
parameter:
Xpoint :X coordinate
Ypoint :Y coordinate
Acsii_Char :To display the characters
Font :A structure pointer that displays a character size
Color_Background : Select the background color of the character
Color_Foreground : Select the foreground color of the character
refresh : Send or not refresh command
******************************************************************************/
void Paint::drawChar(uint16_t Xpoint, uint16_t Ypoint, const char Acsii_Char,
sFONT *Font, uint16_t Color_Background, uint16_t Color_Foreground, bool refresh)
{
uint16_t Page, Column;
uint32_t Char_Offset;
const unsigned char *ptr;
if (Xpoint > this->width || Ypoint > this->height)
{
return;
}
Char_Offset = (Acsii_Char - ' ') * Font->Height * (Font->Width / 8 + (Font->Width % 8 ? 1 : 0));
ptr = &Font->table[Char_Offset];
for (Page = 0; Page < Font->Height; Page++)
{
for (Column = 0; Column < Font->Width; Column++)
{
//To determine whether the font background color and screen background color is consistent
if (EP_DISPLAY_FONT_BACKGROUND == Color_Background)
{ //this process is to speed up the scan
if (*ptr & (0x80 >> (Column % 8)))
setPixel(Xpoint + Column, Ypoint + Page, Color_Foreground, refresh);
}
else
{
if (*ptr & (0x80 >> (Column % 8)))
{
setPixel(Xpoint + Column, Ypoint + Page, Color_Foreground, refresh);
}
else
{
setPixel(Xpoint + Column, Ypoint + Page, Color_Background, refresh);
}
}
//One pixel is 8 bits
if (Column % 8 == 7)
ptr++;
} // Write a line
if (Font->Width % 8 != 0)
ptr++;
} // Write all
if (refresh)
{
update();
}
}
/******************************************************************************
function: Display the string
parameter:
Xstart :X coordinate
Ystart :Y coordinate
pString :The first address of the string to be displayed
Font :A structure pointer that displays a character size
Color_Background : Select the background color of the character
Color_Foreground : Select the foreground color of the character
refresh : Send or not refresh command
******************************************************************************/
void Paint::drawString(uint16_t Xstart, uint16_t Ystart, const char *pString,
sFONT *Font, uint16_t Color_Background, uint16_t Color_Foreground, bool refresh)
{
uint16_t Xpoint = Xstart;
uint16_t Ypoint = Ystart;
if (Xstart > this->width || Ystart > this->height)
{
return;
}
while (*pString != '\0')
{
//if X direction filled , reposition to(Xstart,Ypoint),Ypoint is Y direction plus the Height of the character
if ((Xpoint + Font->Width) > this->width)
{
Xpoint = Xstart;
Ypoint += Font->Height;
}
// If the Y direction is full, reposition to(Xstart, Ystart)
if ((Ypoint + Font->Height) > this->height)
{
Xpoint = Xstart;
Ypoint = Ystart;
}
drawChar(Xpoint, Ypoint, *pString, Font, Color_Background, Color_Foreground, false);
//The next character of the address
pString++;
//The next word of the abscissa increases the font of the broadband
Xpoint += Font->Width;
}
if (refresh)
{
update();
}
}
/******************************************************************************
function: Display monochrome bitmap
parameter:
buffer :A picture data converted to a bitmap
info:
Use a computer to convert the image into a corresponding array,
and then embed the array directly into Imagedata.cpp as a .c file.
******************************************************************************/
void Paint::drawBitmap(const uint8_t * buffer)
{
memcpy(this->buffer, buffer, bytesCount);
update();
}
} // namespace ep
| 32.78087 | 143 | 0.497851 | [
"solid"
] |
5dc5073854fe36e115504d3dd8faf5cf86662c31 | 1,369 | cpp | C++ | 238.product_of_array_except_self.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | 5 | 2019-09-12T05:23:44.000Z | 2021-11-15T11:19:39.000Z | 238.product_of_array_except_self.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | 18 | 2019-09-23T13:11:06.000Z | 2019-11-09T11:20:17.000Z | 238.product_of_array_except_self.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | null | null | null | /**
* Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
*
* Example:
*
* Input: [1,2,3,4]
* Output: [24,12,8,6]
* Note: Please solve it without division and in O(n).
*
* Follow up:
* Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
*/
/**
* 对于一个数组[a, b, c, d]
*
* 如果从前计算乘积得
*
* [a, ab, abc]
*
* 从后计算乘积得
*
* [dcb , dc, d]
*
* 对于两个数组前后补1,然后对应相乘就可以得到这个问题得解
*
* [1, a, ab, abc] * [dcb, dc, d, 1] = [dcb, adc, abd, abc]
*/
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> productExceptSelf(vector<int> &nums)
{
int len = nums.size();
vector<int> ans(len, 1);
for (int i = 0; i < len - 1; i++)
{
ans[i + 1] = nums[i] * ans[i];
}
int t = 1;
for (int i = len - 2; i >= 0; i--)
{
t = t * nums[i + 1];
ans[i] = ans[i] * t;
}
return ans;
}
};
int main()
{
Solution s;
vector<int> n1 = {1, 2, 3, 4};
assert(s.productExceptSelf(n1) == vector<int>({24, 12, 8, 6}));
vector<int> n2 = {1};
assert(s.productExceptSelf(n2) == vector<int>({1}));
return 0;
} | 19.84058 | 161 | 0.527392 | [
"vector"
] |
5dc6dea83f9af22bf75a718bfb316f8a7bd53f3c | 10,318 | cpp | C++ | src/plugins/glance/glanceshower.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/glance/glanceshower.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/glance/glanceshower.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "glanceshower.h"
#include <cmath>
#include <limits>
#include <QLabel>
#include <QGraphicsItem>
#include <QGraphicsPixmapItem>
#include <QParallelAnimationGroup>
#include <QSequentialAnimationGroup>
#include <QProgressDialog>
#include <QPropertyAnimation>
#include <QKeyEvent>
#include <QApplication>
#include <QDesktopWidget>
#include <QMainWindow>
#include <QtDebug>
#include <util/sll/prelude.h>
#include <interfaces/core/icoretabwidget.h>
#include <interfaces/ihavetabs.h>
#include "core.h"
#include "glanceitem.h"
namespace LC
{
namespace Plugins
{
namespace Glance
{
GlanceShower::GlanceShower (QWidget *parent)
: QGraphicsView (parent)
, Scene_ (new QGraphicsScene)
{
setWindowFlags (Qt::Dialog |
Qt::WindowStaysOnTopHint |
Qt::FramelessWindowHint);
setAttribute (Qt::WA_TranslucentBackground);
setStyleSheet ("background: transparent");
setOptimizationFlag (DontSavePainterState);
Scene_->setItemIndexMethod (QGraphicsScene::NoIndex);
setRenderHints (QPainter::Antialiasing | QPainter::TextAntialiasing);
}
void GlanceShower::SetTabWidget (ICoreTabWidget *tw)
{
TabWidget_ = tw;
}
void GlanceShower::Start ()
{
if (!TabWidget_)
{
qWarning () << Q_FUNC_INFO
<< "no tab widget set";
return;
}
const int count = TabWidget_->WidgetCount ();
if (count < 2)
{
emit finished (true);
return;
}
QAnimationGroup *animGroup = new QParallelAnimationGroup;
const int sqr = std::sqrt (static_cast<double> (count));
int rows = sqr;
int cols = sqr;
if (rows * cols < count)
++cols;
if (rows * cols < count)
++rows;
const QRect& screenGeom = QApplication::desktop ()->
screenGeometry (Core::Instance ().GetMainWindow ());
const int width = screenGeom.width ();
const int height = screenGeom.height ();
const int singleW = width / cols;
const int singleH = height / rows;
const int wW = singleW * 4 / 5;
const int wH = singleH * 4 / 5;
qreal scaleFactor = 0;
const int animLength = 400;
QProgressDialog pg;
pg.setMinimumDuration (1000);
pg.setRange (0, count);
for (int row = 0; row < rows; ++row)
for (int column = 0;
column < cols && column + row * cols < count;
++column)
{
const int idx = column + row * cols;
pg.setValue (idx);
QWidget *w = TabWidget_->Widget (idx);
if (!SSize_.isValid ())
SSize_ = w->size () / 2;
if (SSize_ != w->size ())
w->resize (SSize_ * 2);
if (std::fabs (scaleFactor) < std::numeric_limits<qreal>::epsilon ())
scaleFactor = std::min (static_cast<qreal> (wW) / SSize_.width (),
static_cast<qreal> (wH) / SSize_.height ());
QPixmap pixmap (SSize_ * 2);
w->render (&pixmap);
pixmap = pixmap.scaled (SSize_,
Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
//Close button
const int buttonSize = 25;
const int buttonLeft = SSize_.width() - buttonSize * 2;
const int buttonTop = buttonSize;
QRect buttonRect(QPoint (buttonLeft, buttonTop), QPoint (buttonLeft + buttonSize, buttonTop + buttonSize));
{
QPainter p (&pixmap);
QPen pen (Qt::black);
pen.setWidth (2 / scaleFactor + 1);
p.setPen (pen);
p.drawRect (QRect (QPoint (0, 0), SSize_));
}
GlanceItem *item = new GlanceItem (pixmap, buttonRect);
item->SetIndex (idx);
connect (item,
SIGNAL (clicked (int, bool)),
this,
SLOT (handleClicked (int, bool)));
Scene_->addItem (item);
item->setTransformOriginPoint (SSize_.width () / 2, SSize_.height () / 2);
item->setScale (scaleFactor);
item->SetIdealScale (scaleFactor);
item->setOpacity (0);
item->moveBy (column * singleW, row * singleH);
QAnimationGroup *pair = new QParallelAnimationGroup;
QPropertyAnimation *posAnim = new QPropertyAnimation (item, "Pos");
posAnim->setDuration (animLength);
posAnim->setStartValue (QPointF (0, 0));
posAnim->setEndValue (QPointF (column * singleW, row * singleH));
posAnim->setEasingCurve (QEasingCurve::OutSine);
pair->addAnimation (posAnim);
QPropertyAnimation *opacityAnim = new QPropertyAnimation (item, "Opacity");
opacityAnim->setDuration (animLength);
opacityAnim->setStartValue (0.);
opacityAnim->setEndValue (1.);
pair->addAnimation (opacityAnim);
animGroup->addAnimation (pair);
}
setScene (Scene_);
setGeometry (screenGeom);
animGroup->start ();
for (const auto item : items ())
qgraphicsitem_cast<GlanceItem*> (item)->SetItemList (items ());
show ();
}
void GlanceShower::keyPressEvent (QKeyEvent *e)
{
if (e->key () == Qt::Key_Escape)
Finalize ();
else
{
const auto& glanceItemList = Util::Map (items (),
[] (auto item) { return qgraphicsitem_cast<GlanceItem*> (item); });
int currentItem = -1;
const int count = TabWidget_->WidgetCount ();
const int sqrt = std::sqrt (static_cast<double> (count));
int rows = sqrt;
int cols = sqrt;
if (rows * cols < count)
++cols;
if (rows * cols < count)
++rows;
for (int i = 0; i < count; ++i)
if (glanceItemList [i]->IsCurrent ())
currentItem = i;
switch (e->key ())
{
case Qt::Key_Right:
if (currentItem < 0)
glanceItemList [0]->SetCurrent (true);
else
if (currentItem < (count - 1))
{
glanceItemList [currentItem]->SetCurrent (false);
glanceItemList [currentItem + 1]->SetCurrent (true);
}
else
{
glanceItemList [currentItem]->SetCurrent (false);
glanceItemList [0]->SetCurrent (true);
}
break;
case Qt::Key_Left:
if (currentItem < 0)
glanceItemList [count - 1]->SetCurrent (true);
else
if (currentItem > 0)
{
glanceItemList [currentItem]->SetCurrent (false);
glanceItemList [currentItem - 1]->SetCurrent (true);
}
else
{
glanceItemList [currentItem]->SetCurrent (false);
glanceItemList [count - 1]->SetCurrent (true);
}
break;
case Qt::Key_Down:
if (count < 3)
{
QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier);
QCoreApplication::postEvent (this, event);
}
else
if (currentItem < 0)
glanceItemList [0]->SetCurrent (true);
else
if (currentItem + cols < count)
{
glanceItemList [currentItem]->SetCurrent (false);
glanceItemList [currentItem + cols]->SetCurrent (true);
}
else
{
glanceItemList [currentItem]->SetCurrent (false);
while ((currentItem - cols * (rows - 1)) < 0)
rows--;
glanceItemList [currentItem - cols * (rows - 1)]->SetCurrent (true);
}
break;
case Qt::Key_Up:
if (count < 3)
{
QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier);
QCoreApplication::postEvent (this, event);
}
else
if (currentItem < 0)
glanceItemList [0]->SetCurrent (true);
else
if (currentItem >= cols)
{
glanceItemList [currentItem]->SetCurrent (false);
glanceItemList [currentItem - cols]->SetCurrent (true);
}
else
{
glanceItemList [currentItem]->SetCurrent (false);
while ((currentItem + cols * (rows - 1)) > count - 1)
rows--;
glanceItemList [currentItem + cols * (rows - 1)]->SetCurrent (true);
}
break;
case Qt::Key_Return:
if (currentItem >= 0)
handleClicked (currentItem);
break;
default:
QGraphicsView::keyPressEvent (e);
}
}
}
void GlanceShower::handleClicked (int idx, bool close)
{
if (close)
{
qobject_cast<ITabWidget*> (TabWidget_->Widget (idx))->Remove ();
Scene_->removeItem (Scene_->items () [idx]);
if (Scene_->items ().size () < 2)
{
Finalize ();
return;
}
//Now rearrange and resize all the rest items
const int count = TabWidget_->WidgetCount ();
const int sqr = std::sqrt (static_cast<double> (count));
int rows = sqr;
int cols = sqr;
if (rows * cols < count)
++cols;
if (rows * cols < count)
++rows;
const QRect& screenGeom = QApplication::desktop ()->
screenGeometry (Core::Instance ().GetMainWindow ());
const int width = screenGeom.width ();
const int height = screenGeom.height ();
const int singleW = width / cols;
const int singleH = height / rows;
const int wW = singleW * 4 / 5;
const int wH = singleH * 4 / 5;
const int animLength = 400;
QParallelAnimationGroup *anim = new QParallelAnimationGroup();
qreal scaleFactor = std::min (static_cast<qreal> (wW) / SSize_.width (),
static_cast<qreal> (wH) / SSize_.height ());
for (int row = 0; row < rows; ++row)
for (int column = 0;
column < cols && column + row * cols < count;
++column)
{
const int idx = column + row * cols;
GlanceItem *item = qgraphicsitem_cast<GlanceItem*> (items ()[idx]);
item->SetIndex (idx);
item->SetIdealScale (scaleFactor);
auto pair = new QParallelAnimationGroup ();
auto posAnim = new QPropertyAnimation (item, "Pos");
posAnim->setDuration (animLength);
posAnim->setStartValue (item->pos ());
posAnim->setEndValue (QPointF (column * singleW, row * singleH));
posAnim->setEasingCurve (QEasingCurve::OutSine);
pair->addAnimation (posAnim);
auto scaleAnim = new QPropertyAnimation (item, "Scale");
scaleAnim->setDuration (animLength);
scaleAnim->setStartValue (item->scale ());
scaleAnim->setEndValue (scaleFactor);
pair->addAnimation (scaleAnim);
anim->addAnimation (pair);
}
anim->start ();
}
else
{
TabWidget_->setCurrentTab (idx);
Finalize ();
}
}
void GlanceShower::Finalize ()
{
emit finished (true);
deleteLater ();
}
void GlanceShower::mousePressEvent (QMouseEvent *e)
{
QGraphicsView::mousePressEvent (e);
e->accept ();
if (!this->itemAt (e->pos ()))
Finalize ();
}
}
}
}
| 26.8 | 111 | 0.626672 | [
"render"
] |
5dc874488f676656b6c47157f54106a8991af4a6 | 346 | cpp | C++ | DynamicProgramming/tilingmn.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | DynamicProgramming/tilingmn.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | DynamicProgramming/tilingmn.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
#define ll long long int
using namespace std ;
int main(){
int n , m ;
cin >> n >> m ;
vector<int> dp(n+1);
for(int i=0 ;i<=n ;i++){
if(i<m){
dp[i] = 1;
}else if(i==m){
dp[i] = 2;
}else{
dp[i] = dp[i-1] + dp[i-m];
}
}
cout << dp[n] << endl ;
return 0;
} | 13.84 | 31 | 0.50289 | [
"vector"
] |
5dce984a1d67a8e048549231651a93f46b9bb286 | 3,102 | cc | C++ | src/rtff/filter_impl.cc | audionamix/rtff | 1a56bb3980d167feee3778001a420ea101d497e3 | [
"MIT"
] | 6 | 2019-07-16T08:37:20.000Z | 2022-01-06T02:57:42.000Z | src/rtff/filter_impl.cc | audionamix/rtff | 1a56bb3980d167feee3778001a420ea101d497e3 | [
"MIT"
] | 1 | 2020-06-19T08:12:58.000Z | 2020-06-23T18:53:19.000Z | src/rtff/filter_impl.cc | audionamix/rtff | 1a56bb3980d167feee3778001a420ea101d497e3 | [
"MIT"
] | 2 | 2020-01-16T14:22:03.000Z | 2020-02-09T12:03:49.000Z | #include "rtff/filter_impl.h"
#include "rtff/fft/fft.h"
namespace rtff {
void FilterImpl::Init(uint32_t fft_size, uint32_t overlap,
fft_window::Type windows_type,
uint8_t channel_count, std::error_code& err) {
fft_size_ = fft_size;
overlap_ = overlap;
// init the window to an hamming
analysis_window_ = Window::Make(windows_type, fft_size);
synthesis_window_ = Window::Make(windows_type, fft_size);
unwindow_ = Window::MakeInverse(windows_type, windows_type,
fft_size, hop_size());
// init the fft
fft_ = Fft::Create(fft_size_, err);
if (err) {
return;
}
// init inverse transform temp data
previous_buffer_.resize(channel_count);
result_buffer_.resize(channel_count);
post_ifft_buffer_.resize(channel_count);
for (auto channel_idx = 0; channel_idx < channel_count; channel_idx++) {
previous_buffer_[channel_idx] =
Eigen::VectorXf::Zero(window_size() - hop_size());
post_ifft_buffer_[channel_idx].resize(window_size());
result_buffer_[channel_idx].resize(window_size());
}
}
uint32_t FilterImpl::overlap() const { return overlap_; }
uint32_t FilterImpl::fft_size() const { return fft_size_; }
uint32_t FilterImpl::window_size() const { return analysis_window().size(); }
uint32_t FilterImpl::hop_size() const { return fft_size_ - overlap_; }
const Eigen::VectorXf& FilterImpl::analysis_window() const {
return analysis_window_;
}
const Eigen::VectorXf& FilterImpl::synthesis_window() const {
return synthesis_window_;
}
void FilterImpl::Analyze(TimeAmplitudeBuffer& amplitude,
TimeFrequencyBuffer* frequential) {
for (uint8_t channel_idx = 0; channel_idx < amplitude.channel_count();
channel_idx++) {
// apply the analysis window
amplitude.channel(channel_idx).array() *= analysis_window_.array();
// compute the fft and store it into the frequential buffer
fft_->Forward(amplitude.channel(channel_idx).data(),
frequential->channel(channel_idx).data());
}
}
void FilterImpl::Synthesize(const TimeFrequencyBuffer& frequential,
TimeAmplitudeBuffer* amplitude) {
for (uint8_t channel_idx = 0; channel_idx < frequential.channel_count();
channel_idx++) {
auto& result_ = result_buffer_[channel_idx];
auto& previous_ = previous_buffer_[channel_idx];
auto& post_ifft = post_ifft_buffer_[channel_idx];
// ifft
fft_->Backward(frequential.channel(channel_idx).data(), post_ifft.data());
// apply synthesis window and sum to previous data
// sum with previous data
memset(result_.data(), 0, result_.size() * sizeof(float));
result_.head(previous_.size()) = previous_;
result_.array() +=
post_ifft.array() * synthesis_window_.array() / unwindow_.array();
// keep previous buffer for synthesis
previous_ = result_.tail(previous_.size());
// unwindow to get the right buffer
amplitude->channel(channel_idx).noalias() =
result_.head(hop_size()).transpose();
}
}
} // namespace rtff
| 35.25 | 78 | 0.690522 | [
"transform"
] |
5dd0f4ec1e3b54cdad3c78ed21597b42f3f1cd90 | 21,578 | cpp | C++ | third_party/llvm-project/raw_ostream.cpp | phated/binaryen | 50e66800dc28d67ea1cc88172f459df1ca96507d | [
"Apache-2.0"
] | 5,871 | 2015-11-13T19:06:43.000Z | 2022-03-31T17:40:21.000Z | third_party/llvm-project/raw_ostream.cpp | sthagen/binaryen | ce592cbdc8e58f36e7f39a3bd24b403f43adae34 | [
"Apache-2.0"
] | 2,743 | 2015-11-13T03:46:49.000Z | 2022-03-31T20:27:05.000Z | third_party/llvm-project/raw_ostream.cpp | sthagen/binaryen | ce592cbdc8e58f36e7f39a3bd24b403f43adae34 | [
"Apache-2.0"
] | 626 | 2015-11-23T08:00:11.000Z | 2022-03-17T01:58:18.000Z | //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This implements support for bulk buffered stream output.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/NativeFormatting.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdio>
#include <iterator>
#include <sys/stat.h>
#include <system_error>
// XXX BINARYEn
#include <iostream>
// <fcntl.h> may provide O_BINARY.
#if defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(__CYGWIN__)
#include <io.h>
#endif
#if defined(_MSC_VER)
#include <io.h>
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif
#if 0 // XXX BINARYEN def _WIN32
#include "llvm/Support/ConvertUTF.h"
#include "Windows/WindowsSupport.h"
#endif
using namespace llvm;
const raw_ostream::Colors raw_ostream::BLACK;
const raw_ostream::Colors raw_ostream::RED;
const raw_ostream::Colors raw_ostream::GREEN;
const raw_ostream::Colors raw_ostream::YELLOW;
const raw_ostream::Colors raw_ostream::BLUE;
const raw_ostream::Colors raw_ostream::MAGENTA;
const raw_ostream::Colors raw_ostream::CYAN;
const raw_ostream::Colors raw_ostream::WHITE;
const raw_ostream::Colors raw_ostream::SAVEDCOLOR;
const raw_ostream::Colors raw_ostream::RESET;
raw_ostream::~raw_ostream() {
// raw_ostream's subclasses should take care to flush the buffer
// in their destructors.
assert(OutBufCur == OutBufStart &&
"raw_ostream destructor called with non-empty buffer!");
if (BufferMode == BufferKind::InternalBuffer)
delete [] OutBufStart;
}
size_t raw_ostream::preferred_buffer_size() const {
// BUFSIZ is intended to be a reasonable default.
return BUFSIZ;
}
void raw_ostream::SetBuffered() {
// Ask the subclass to determine an appropriate buffer size.
if (size_t Size = preferred_buffer_size())
SetBufferSize(Size);
else
// It may return 0, meaning this stream should be unbuffered.
SetUnbuffered();
}
void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
BufferKind Mode) {
assert(((Mode == BufferKind::Unbuffered && !BufferStart && Size == 0) ||
(Mode != BufferKind::Unbuffered && BufferStart && Size != 0)) &&
"stream must be unbuffered or have at least one byte");
// Make sure the current buffer is free of content (we can't flush here; the
// child buffer management logic will be in write_impl).
assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
if (BufferMode == BufferKind::InternalBuffer)
delete [] OutBufStart;
OutBufStart = BufferStart;
OutBufEnd = OutBufStart+Size;
OutBufCur = OutBufStart;
BufferMode = Mode;
assert(OutBufStart <= OutBufEnd && "Invalid size!");
}
raw_ostream &raw_ostream::operator<<(unsigned long N) {
write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
return *this;
}
raw_ostream &raw_ostream::operator<<(long N) {
write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
return *this;
}
raw_ostream &raw_ostream::operator<<(unsigned long long N) {
write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
return *this;
}
raw_ostream &raw_ostream::operator<<(long long N) {
write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
return *this;
}
raw_ostream &raw_ostream::write_hex(unsigned long long N) {
llvm::write_hex(*this, N, HexPrintStyle::Lower);
return *this;
}
raw_ostream &raw_ostream::operator<<(Colors C) {
if (C == Colors::RESET)
resetColor();
else
changeColor(C);
return *this;
}
raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
for (int Idx = 0; Idx < 16; ++Idx) {
*this << format("%02" PRIX32, UUID[Idx]);
if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
*this << "-";
}
return *this;
}
raw_ostream &raw_ostream::write_escaped(StringRef Str,
bool UseHexEscapes) {
for (unsigned char c : Str) {
switch (c) {
case '\\':
*this << '\\' << '\\';
break;
case '\t':
*this << '\\' << 't';
break;
case '\n':
*this << '\\' << 'n';
break;
case '"':
*this << '\\' << '"';
break;
default:
if (isPrint(c)) {
*this << c;
break;
}
// Write out the escaped representation.
if (UseHexEscapes) {
*this << '\\' << 'x';
*this << hexdigit((c >> 4 & 0xF));
*this << hexdigit((c >> 0) & 0xF);
} else {
// Always use a full 3-character octal escape.
*this << '\\';
*this << char('0' + ((c >> 6) & 7));
*this << char('0' + ((c >> 3) & 7));
*this << char('0' + ((c >> 0) & 7));
}
}
}
return *this;
}
raw_ostream &raw_ostream::operator<<(const void *P) {
llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
return *this;
}
raw_ostream &raw_ostream::operator<<(double N) {
llvm::write_double(*this, N, FloatStyle::Exponent);
return *this;
}
void raw_ostream::flush_nonempty() {
assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
size_t Length = OutBufCur - OutBufStart;
OutBufCur = OutBufStart;
write_impl(OutBufStart, Length);
}
raw_ostream &raw_ostream::write(unsigned char C) {
// Group exceptional cases into a single branch.
if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
if (LLVM_UNLIKELY(!OutBufStart)) {
if (BufferMode == BufferKind::Unbuffered) {
write_impl(reinterpret_cast<char*>(&C), 1);
return *this;
}
// Set up a buffer and start over.
SetBuffered();
return write(C);
}
flush_nonempty();
}
*OutBufCur++ = C;
return *this;
}
raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
// Group exceptional cases into a single branch.
if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
if (LLVM_UNLIKELY(!OutBufStart)) {
if (BufferMode == BufferKind::Unbuffered) {
write_impl(Ptr, Size);
return *this;
}
// Set up a buffer and start over.
SetBuffered();
return write(Ptr, Size);
}
size_t NumBytes = OutBufEnd - OutBufCur;
// If the buffer is empty at this point we have a string that is larger
// than the buffer. Directly write the chunk that is a multiple of the
// preferred buffer size and put the remainder in the buffer.
if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
assert(NumBytes != 0 && "undefined behavior");
size_t BytesToWrite = Size - (Size % NumBytes);
write_impl(Ptr, BytesToWrite);
size_t BytesRemaining = Size - BytesToWrite;
if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
// Too much left over to copy into our buffer.
return write(Ptr + BytesToWrite, BytesRemaining);
}
copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
return *this;
}
// We don't have enough space in the buffer to fit the string in. Insert as
// much as possible, flush and start over with the remainder.
copy_to_buffer(Ptr, NumBytes);
flush_nonempty();
return write(Ptr + NumBytes, Size - NumBytes);
}
copy_to_buffer(Ptr, Size);
return *this;
}
void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
// Handle short strings specially, memcpy isn't very good at very short
// strings.
switch (Size) {
case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
case 0: break;
default:
memcpy(OutBufCur, Ptr, Size);
break;
}
OutBufCur += Size;
}
// Formatted output.
raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
// If we have more than a few bytes left in our output buffer, try
// formatting directly onto its end.
size_t NextBufferSize = 127;
size_t BufferBytesLeft = OutBufEnd - OutBufCur;
if (BufferBytesLeft > 3) {
size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
// Common case is that we have plenty of space.
if (BytesUsed <= BufferBytesLeft) {
OutBufCur += BytesUsed;
return *this;
}
// Otherwise, we overflowed and the return value tells us the size to try
// again with.
NextBufferSize = BytesUsed;
}
// If we got here, we didn't have enough space in the output buffer for the
// string. Try printing into a SmallVector that is resized to have enough
// space. Iterate until we win.
SmallVector<char, 128> V;
while (true) {
V.resize(NextBufferSize);
// Try formatting into the SmallVector.
size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
// If BytesUsed fit into the vector, we win.
if (BytesUsed <= NextBufferSize)
return write(V.data(), BytesUsed);
// Otherwise, try again with a new size.
assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
NextBufferSize = BytesUsed;
}
}
raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
SmallString<128> S;
Obj.format(*this);
return *this;
}
raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
this->operator<<(FS.Str);
return *this;
}
const size_t Difference = FS.Width - FS.Str.size();
switch (FS.Justify) {
case FormattedString::JustifyLeft:
this->operator<<(FS.Str);
this->indent(Difference);
break;
case FormattedString::JustifyRight:
this->indent(Difference);
this->operator<<(FS.Str);
break;
case FormattedString::JustifyCenter: {
int PadAmount = Difference / 2;
this->indent(PadAmount);
this->operator<<(FS.Str);
this->indent(Difference - PadAmount);
break;
}
default:
llvm_unreachable("Bad Justification");
}
return *this;
}
raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
if (FN.Hex) {
HexPrintStyle Style;
if (FN.Upper && FN.HexPrefix)
Style = HexPrintStyle::PrefixUpper;
else if (FN.Upper && !FN.HexPrefix)
Style = HexPrintStyle::Upper;
else if (!FN.Upper && FN.HexPrefix)
Style = HexPrintStyle::PrefixLower;
else
Style = HexPrintStyle::Lower;
llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
} else {
llvm::SmallString<16> Buffer;
llvm::raw_svector_ostream Stream(Buffer);
llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
if (Buffer.size() < FN.Width)
indent(FN.Width - Buffer.size());
(*this) << Buffer;
}
return *this;
}
raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
if (FB.Bytes.empty())
return *this;
size_t LineIndex = 0;
auto Bytes = FB.Bytes;
const size_t Size = Bytes.size();
HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
uint64_t OffsetWidth = 0;
if (FB.FirstByteOffset.hasValue()) {
// Figure out how many nibbles are needed to print the largest offset
// represented by this data set, so that we can align the offset field
// to the right width.
size_t Lines = Size / FB.NumPerLine;
uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
unsigned Power = 0;
if (MaxOffset > 0)
Power = llvm::Log2_64_Ceil(MaxOffset);
OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
}
// The width of a block of data including all spaces for group separators.
unsigned NumByteGroups =
alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
while (!Bytes.empty()) {
indent(FB.IndentLevel);
if (FB.FirstByteOffset.hasValue()) {
uint64_t Offset = FB.FirstByteOffset.getValue();
llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
*this << ": ";
}
auto Line = Bytes.take_front(FB.NumPerLine);
size_t CharsPrinted = 0;
// Print the hex bytes for this line in groups
for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
if (I && (I % FB.ByteGroupSize) == 0) {
++CharsPrinted;
*this << " ";
}
llvm::write_hex(*this, Line[I], HPS, 2);
}
if (FB.ASCII) {
// Print any spaces needed for any bytes that we didn't print on this
// line so that the ASCII bytes are correctly aligned.
assert(BlockCharWidth >= CharsPrinted);
indent(BlockCharWidth - CharsPrinted + 2);
*this << "|";
// Print the ASCII char values for each byte on this line
for (uint8_t Byte : Line) {
if (isPrint(Byte))
*this << static_cast<char>(Byte);
else
*this << '.';
}
*this << '|';
}
Bytes = Bytes.drop_front(Line.size());
LineIndex += Line.size();
if (LineIndex < Size)
*this << '\n';
}
return *this;
}
template <char C>
static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
// Usually the indentation is small, handle it with a fastpath.
if (NumChars < array_lengthof(Chars))
return OS.write(Chars, NumChars);
while (NumChars) {
unsigned NumToWrite = std::min(NumChars,
(unsigned)array_lengthof(Chars)-1);
OS.write(Chars, NumToWrite);
NumChars -= NumToWrite;
}
return OS;
}
/// indent - Insert 'NumSpaces' spaces.
raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
return write_padding<' '>(*this, NumSpaces);
}
/// write_zeros - Insert 'NumZeros' nulls.
raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) {
return write_padding<'\0'>(*this, NumZeros);
}
void raw_ostream::anchor() {}
//===----------------------------------------------------------------------===//
// Formatted Output
//===----------------------------------------------------------------------===//
// Out of line virtual method.
void format_object_base::home() {
}
//===----------------------------------------------------------------------===//
// raw_fd_ostream
//===----------------------------------------------------------------------===//
static int getFD(StringRef Filename, std::error_code &EC,
sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
sys::fs::OpenFlags Flags) {
// XXX BINARYEN - we only ever use IO from LLVM to log to stdout
return fileno(stdout);
}
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC)
: raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
sys::fs::OF_None) {}
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
sys::fs::CreationDisposition Disp)
: raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
sys::fs::FileAccess Access)
: raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, Access,
sys::fs::OF_None) {}
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
sys::fs::OpenFlags Flags)
: raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
Flags) {}
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
sys::fs::CreationDisposition Disp,
sys::fs::FileAccess Access,
sys::fs::OpenFlags Flags)
: raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {}
/// FD is the file descriptor that this writes to. If ShouldClose is true, this
/// closes the file when the stream is destroyed.
raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
: raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
// XXX BINARYEN: do nothing here
}
raw_fd_ostream::~raw_fd_ostream() {
// XXX BINARYEN: do nothing here
}
void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
// XXX BINARYEN: just log it out
for (size_t i = 0; i < Size; i++) {
std::cout << Ptr[i];
}
}
void raw_fd_ostream::close() {
assert(ShouldClose);
ShouldClose = false;
flush();
llvm_unreachable("close"); // XXX BINARYEN
#if 0
if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
error_detected(EC);
#endif
FD = -1;
}
uint64_t raw_fd_ostream::seek(uint64_t off) {
llvm_unreachable("seek");
}
void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
uint64_t Offset) {
uint64_t Pos = tell();
seek(Offset);
write(Ptr, Size);
seek(Pos);
}
size_t raw_fd_ostream::preferred_buffer_size() const {
return 0; // XXX BINARYEN
}
raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
bool bg) {
if (!ColorEnabled)
return *this;
llvm_unreachable("color"); // XXX BINARYEN
}
raw_ostream &raw_fd_ostream::resetColor() {
if (!ColorEnabled)
return *this;
llvm_unreachable("color"); // XXX BINARYEN
}
raw_ostream &raw_fd_ostream::reverseColor() {
if (!ColorEnabled)
return *this;
llvm_unreachable("color"); // XXX BINARYEN
}
bool raw_fd_ostream::is_displayed() const {
llvm_unreachable("is_displayed"); // XXX BINARYEN
}
bool raw_fd_ostream::has_colors() const {
llvm_unreachable("is_displayed"); // XXX BINARYEN
}
void raw_fd_ostream::anchor() {}
//===----------------------------------------------------------------------===//
// outs(), errs(), nulls()
//===----------------------------------------------------------------------===//
/// outs() - This returns a reference to a raw_ostream for standard output.
/// Use it like: outs() << "foo" << "bar";
raw_ostream &llvm::outs() {
// Set buffer settings to model stdout behavior.
std::error_code EC;
static raw_fd_ostream S("-", EC, sys::fs::OF_None);
assert(!EC);
return S;
}
/// errs() - This returns a reference to a raw_ostream for standard error.
/// Use it like: errs() << "foo" << "bar";
raw_ostream &llvm::errs() {
// Set standard error to be unbuffered by default.
const int fd = 2; // XXX BINARYEN: stderr, but it doesn't matter anyhow
static raw_fd_ostream S(fd, false, true);
return S;
}
/// nulls() - This returns a reference to a raw_ostream which discards output.
raw_ostream &llvm::nulls() {
static raw_null_ostream S;
return S;
}
//===----------------------------------------------------------------------===//
// raw_string_ostream
//===----------------------------------------------------------------------===//
raw_string_ostream::~raw_string_ostream() {
flush();
}
void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
OS.append(Ptr, Size);
}
//===----------------------------------------------------------------------===//
// raw_svector_ostream
//===----------------------------------------------------------------------===//
uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
OS.append(Ptr, Ptr + Size);
}
void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
uint64_t Offset) {
memcpy(OS.data() + Offset, Ptr, Size);
}
//===----------------------------------------------------------------------===//
// raw_null_ostream
//===----------------------------------------------------------------------===//
raw_null_ostream::~raw_null_ostream() {
#ifndef NDEBUG
// ~raw_ostream asserts that the buffer is empty. This isn't necessary
// with raw_null_ostream, but it's better to have raw_null_ostream follow
// the rules than to change the rules just for raw_null_ostream.
flush();
#endif
}
void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
}
uint64_t raw_null_ostream::current_pos() const {
return 0;
}
void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
uint64_t Offset) {}
void raw_pwrite_stream::anchor() {}
void buffer_ostream::anchor() {}
| 30.263675 | 80 | 0.614561 | [
"vector",
"model"
] |
5dd6e02b5e099093fb44d8fef18f4971cc892a6d | 72,811 | cpp | C++ | test/unit/test.unit.api.parse_format/test.unit.api.parse_format.cpp | synesissoftware/FastFormat | 53d3ccbb4313f908cb1a482372179db60e12e1a8 | [
"BSD-3-Clause"
] | 55 | 2015-10-06T21:42:05.000Z | 2022-01-21T04:14:29.000Z | test/unit/test.unit.api.parse_format/test.unit.api.parse_format.cpp | synesissoftware/FastFormat | 53d3ccbb4313f908cb1a482372179db60e12e1a8 | [
"BSD-3-Clause"
] | 2 | 2017-10-10T05:29:51.000Z | 2019-03-23T04:20:59.000Z | test/unit/test.unit.api.parse_format/test.unit.api.parse_format.cpp | synesissoftware/FastFormat | 53d3ccbb4313f908cb1a482372179db60e12e1a8 | [
"BSD-3-Clause"
] | 8 | 2016-01-02T17:47:41.000Z | 2021-09-30T21:58:36.000Z | /* /////////////////////////////////////////////////////////////////////////
* File: test.unit.api.parse_format.cpp
*
* Purpose: Implementation file for the test.unit.api.parse_format project.
*
* Created: 27th May 2008
* Updated: 26th September 2015
*
* Status: Wizard-generated
*
* License: (Licensed under the Synesis Software Open License)
*
* Copyright (c) 2008-2015, Synesis Software Pty Ltd.
* All rights reserved.
*
* www: http://www.synesis.com.au/software
*
* ////////////////////////////////////////////////////////////////////// */
#include <fastformat/test/util/compiler_warnings_suppression.first_include.h>
/* /////////////////////////////////////////////////////////////////////////
* Test component header file include(s)
*/
#include <fastformat/fastformat.h>
#include <fastformat/internal/format_element.h>
/* /////////////////////////////////////////////////////////////////////////
* Includes
*/
/* xTests header files */
#include <xtests/xtests.h>
/* STLSoft header files */
#include <stlsoft/conversion/char_conversions.hpp>
#include <stlsoft/conversion/integer_to_string.hpp>
#include <platformstl/platformstl.h>
/* Standard C++ header files */
#include <string>
#include <vector>
/* Standard C header files */
#include <stdlib.h>
#include <fastformat/test/util/compiler_warnings_suppression.last_include.h>
/* /////////////////////////////////////////////////////////////////////////////
* Macros and definitions
*/
#ifdef FASTFORMAT_USE_WIDE_STRINGS
# define XTESTS_TEST_STRING_EQUAL(x, a) XTESTS_TEST_WIDE_STRING_EQUAL(x, a)
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
# define XTESTS_TEST_STRING_EQUAL XTESTS_TEST_MULTIBYTE_STRING_EQUAL
#endif /* FASTFORMAT_USE_WIDE_STRINGS */
#ifdef FASTFORMAT_USE_WIDE_STRINGS
# define t2m stlsoft::w2m
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
# define t2m(x) x
#endif /* FASTFORMAT_USE_WIDE_STRINGS */
#define FF_STR FASTFORMAT_LITERAL_STRING
/* /////////////////////////////////////////////////////////////////////////
* Forward declarations
*/
namespace
{
static void test_good_0(void);
static void test_good_1(void);
static void test_good_2(void);
static void test_good_3(void);
static void test_good_4(void);
static void test_good_5(void);
static void test_good_6(void);
static void test_good_7(void);
static void test_good_8(void);
static void test_good_9(void);
static void test_good_10(void);
static void test_good_11(void);
static void test_good_with_qualifiers_0(void);
static void test_good_with_qualifiers_1(void);
static void test_good_with_qualifiers_2(void);
static void test_good_with_qualifiers_3(void);
static void test_good_with_qualifiers_4(void);
static void test_good_with_qualifiers_5(void);
static void test_good_with_qualifiers_6(void);
static void test_good_with_qualifiers_7(void);
static void test_good_with_qualifiers_8(void);
static void test_good_with_qualifiers_9(void);
static void test_good_with_qualifiers_10(void);
static void test_good_with_qualifiers_11(void);
static void test_good_with_qualifiers_12(void);
static void test_good_with_qualifiers_13(void);
static void test_good_with_qualifiers_14(void);
static void test_good_with_qualifiers_15(void);
static void test_good_with_qualifiers_16(void);
static void test_good_with_qualifiers_17(void);
static void test_good_with_qualifiers_18(void);
static void test_good_with_qualifiers_19(void);
static void test_illformed_cancelling_0(void);
static void test_illformed_cancelling_1(void);
static void test_illformed_cancelling_2(void);
static void test_illformed_cancelling_3(void);
static void test_illformed_cancelling_4(void);
static void test_illformed_cancelling_5(void);
static void test_illformed_cancelling_6(void);
static void test_illformed_cancelling_7(void);
static void test_illformed_cancelling_8(void);
static void test_illformed_cancelling_9(void);
static void test_illformed_continuing_0(void);
static void test_illformed_continuing_1(void);
static void test_illformed_continuing_2(void);
static void test_illformed_continuing_3(void);
static void test_illformed_continuing_4(void);
static void test_illformed_continuing_5(void);
static void test_illformed_continuing_6(void);
static void test_illformed_continuing_7(void);
static void test_illformed_continuing_8(void);
static void test_illformed_continuing_9(void);
static void test_illformed_continue_once_0(void);
static void test_illformed_continue_once_1(void);
static void test_illformed_continue_once_2(void);
static void test_illformed_continue_once_3(void);
static void test_illformed_continue_once_4(void);
static void test_illformed_continue_once_5(void);
static void test_illformed_continue_once_6(void);
static void test_illformed_continue_once_7(void);
static void test_illformed_continue_once_8(void);
static void test_illformed_continue_once_9(void);
} // anonymous namespace
/* /////////////////////////////////////////////////////////////////////////
* Main
*/
int main(int argc, char **argv)
{
int retCode = EXIT_SUCCESS;
int verbosity = 2;
XTESTS_COMMANDLINE_PARSEVERBOSITY(argc, argv, &verbosity);
if(XTESTS_START_RUNNER("test.unit.api.parse_format", verbosity))
{
XTESTS_RUN_CASE(test_good_0);
XTESTS_RUN_CASE(test_good_1);
XTESTS_RUN_CASE(test_good_2);
XTESTS_RUN_CASE(test_good_3);
XTESTS_RUN_CASE(test_good_4);
XTESTS_RUN_CASE(test_good_5);
XTESTS_RUN_CASE(test_good_6);
XTESTS_RUN_CASE(test_good_7);
XTESTS_RUN_CASE(test_good_8);
XTESTS_RUN_CASE(test_good_9);
XTESTS_RUN_CASE(test_good_10);
XTESTS_RUN_CASE(test_good_11);
XTESTS_RUN_CASE(test_good_with_qualifiers_0);
XTESTS_RUN_CASE(test_good_with_qualifiers_1);
XTESTS_RUN_CASE(test_good_with_qualifiers_2);
XTESTS_RUN_CASE(test_good_with_qualifiers_3);
XTESTS_RUN_CASE(test_good_with_qualifiers_4);
XTESTS_RUN_CASE(test_good_with_qualifiers_5);
XTESTS_RUN_CASE(test_good_with_qualifiers_6);
XTESTS_RUN_CASE(test_good_with_qualifiers_7);
XTESTS_RUN_CASE(test_good_with_qualifiers_8);
XTESTS_RUN_CASE(test_good_with_qualifiers_9);
XTESTS_RUN_CASE(test_good_with_qualifiers_10);
XTESTS_RUN_CASE(test_good_with_qualifiers_11);
XTESTS_RUN_CASE(test_good_with_qualifiers_12);
XTESTS_RUN_CASE(test_good_with_qualifiers_13);
XTESTS_RUN_CASE(test_good_with_qualifiers_14);
XTESTS_RUN_CASE(test_good_with_qualifiers_15);
XTESTS_RUN_CASE(test_good_with_qualifiers_16);
XTESTS_RUN_CASE(test_good_with_qualifiers_17);
XTESTS_RUN_CASE(test_good_with_qualifiers_18);
XTESTS_RUN_CASE(test_good_with_qualifiers_19);
#if 1
XTESTS_RUN_CASE(test_illformed_cancelling_0);
XTESTS_RUN_CASE(test_illformed_cancelling_1);
XTESTS_RUN_CASE(test_illformed_cancelling_2);
XTESTS_RUN_CASE(test_illformed_cancelling_3);
XTESTS_RUN_CASE(test_illformed_cancelling_4);
XTESTS_RUN_CASE(test_illformed_cancelling_5);
XTESTS_RUN_CASE(test_illformed_cancelling_6);
XTESTS_RUN_CASE(test_illformed_cancelling_7);
XTESTS_RUN_CASE(test_illformed_cancelling_8);
XTESTS_RUN_CASE(test_illformed_cancelling_9);
XTESTS_RUN_CASE(test_illformed_continuing_0);
XTESTS_RUN_CASE(test_illformed_continuing_1);
XTESTS_RUN_CASE(test_illformed_continuing_2);
XTESTS_RUN_CASE(test_illformed_continuing_3);
XTESTS_RUN_CASE(test_illformed_continuing_4);
XTESTS_RUN_CASE(test_illformed_continuing_5);
XTESTS_RUN_CASE(test_illformed_continuing_6);
XTESTS_RUN_CASE(test_illformed_continuing_7);
XTESTS_RUN_CASE(test_illformed_continuing_8);
XTESTS_RUN_CASE(test_illformed_continuing_9);
XTESTS_RUN_CASE(test_illformed_continue_once_0);
XTESTS_RUN_CASE(test_illformed_continue_once_1);
XTESTS_RUN_CASE(test_illformed_continue_once_2);
XTESTS_RUN_CASE(test_illformed_continue_once_3);
XTESTS_RUN_CASE(test_illformed_continue_once_4);
XTESTS_RUN_CASE(test_illformed_continue_once_5);
XTESTS_RUN_CASE(test_illformed_continue_once_6);
XTESTS_RUN_CASE(test_illformed_continue_once_7);
XTESTS_RUN_CASE(test_illformed_continue_once_8);
XTESTS_RUN_CASE(test_illformed_continue_once_9);
#endif /* 0 */
XTESTS_PRINT_RESULTS();
XTESTS_END_RUNNER_UPDATE_EXITCODE(&retCode);
}
return retCode;
}
/* /////////////////////////////////////////////////////////////////////////
* Test function implementations
*/
namespace
{
using fastformat::ff_char_t;
typedef std::basic_string<ff_char_t> string_t;
typedef std::vector<string_t> strings_t;
using fastformat::ff_char_t;
using fastformat::ff_parse_code_t;
using fastformat::fastformat_parseFormat;
using fastformat::FASTFORMAT_ALIGNMENT_NONE;
using fastformat::FASTFORMAT_ALIGNMENT_LEFT;
using fastformat::FASTFORMAT_ALIGNMENT_CENTRE;
using fastformat::FASTFORMAT_ALIGNMENT_RIGHT;
struct parse_error_t
{
string_t format;
size_t replacementIndex;
string_t defect;
int parameterIndex;
};
// NOTE: we must use error handlers here, otherwise we'll have to
// initialise the FF core (in which case this would not be a unit-test)
// This parse error handler reports the error and cancels processing.
int FASTFORMAT_CALLCONV reporting_illformed_handler(
void* /* param */
, ff_parse_code_t /* code */
, ff_char_t const* format
, size_t formatLen
, size_t /* replacementIndex */
, ff_char_t const* /* defect */
, size_t /* defectLen */
, int parameterIndex
, void* /* reserved0 */
, size_t /* reserved1 */
, void* /* reserved2 */
)
{
ff_char_t num[21];
string_t details;
details += FF_STR("format: ");
details.append(format, formatLen);
details += FF_STR("; index: ");
details += stlsoft::integer_to_string(&num[0], STLSOFT_NUM_ELEMENTS(num), parameterIndex);
XTESTS_TEST_FAIL_WITH_QUALIFIER("parsing error", t2m(details));
return 0; // Cancel processing
}
// Mock used to test the parse errors
int FASTFORMAT_CALLCONV cancelling_mock_illformed_handler(
void* param
, ff_parse_code_t /* code */
, ff_char_t const* format
, size_t formatLen
, size_t replacementIndex
, ff_char_t const* defect
, size_t defectLen
, int parameterIndex
, void* /* reserved0 */
, size_t /* reserved1 */
, void* /* reserved2 */
)
{
if(NULL == param)
{
XTESTS_TEST_FAIL("NULL param passed to handler");
return 0; // Cancel processing
}
else
{
parse_error_t& pe = *static_cast<parse_error_t*>(param);
pe.format.assign(format, formatLen);
pe.replacementIndex = replacementIndex;
pe.defect.assign(defect, defectLen);
pe.parameterIndex = parameterIndex;
return 0; // Cancel processing
}
}
// Mock used to test the parse errors
int FASTFORMAT_CALLCONV continuing_mock_illformed_handler(
void* param
, ff_parse_code_t /* code */
, ff_char_t const* format
, size_t formatLen
, size_t replacementIndex
, ff_char_t const* defect
, size_t defectLen
, int parameterIndex
, void* /* reserved0 */
, size_t /* reserved1 */
, void* /* reserved2 */
)
{
if(NULL == param)
{
XTESTS_TEST_FAIL("NULL param passed to handler");
return 0; // Cancel processing
}
else
{
parse_error_t& pe = *static_cast<parse_error_t*>(param);
pe.format.assign(format, formatLen);
pe.replacementIndex = replacementIndex;
pe.defect.assign(defect, defectLen);
pe.parameterIndex = parameterIndex;
return +1; // Continue processing, and don't invoke this again
}
}
// Mock used to test the parse errors
int FASTFORMAT_CALLCONV continue_once_mock_illformed_handler(
void* param
, ff_parse_code_t /* code */
, ff_char_t const* format
, size_t formatLen
, size_t replacementIndex
, ff_char_t const* defect
, size_t defectLen
, int parameterIndex
, void* /* reserved0 */
, size_t /* reserved1 */
, void* /* reserved2 */
)
{
if(NULL == param)
{
XTESTS_TEST_FAIL("NULL param passed to handler");
return 0; // Cancel processing
}
else
{
parse_error_t& pe = *static_cast<parse_error_t*>(param);
pe.format.assign(format, formatLen);
pe.replacementIndex = replacementIndex;
pe.defect.assign(defect, defectLen);
pe.parameterIndex = parameterIndex;
return -1; // Continue processing, and don't invoke this again
}
}
static void test_good_0()
{
const ff_char_t fmt[] = FF_STR("");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(0u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(0u, numResultElements);
}
static void test_good_1()
{
const ff_char_t fmt[] = FF_STR("a");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
}
static void test_good_2()
{
const ff_char_t fmt[] = FF_STR("abcdefghijklmnopqrstuvwxyz");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(26u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
}
static void test_good_3()
{
const ff_char_t fmt[] = FF_STR("{0}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_4()
{
const ff_char_t fmt[] = FF_STR("a{0}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[1].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[1].maxWidth));
}
static void test_good_5()
{
const ff_char_t fmt[] = FF_STR("a{0}b");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[1].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[1].maxWidth));
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2].index);
}
static void test_good_6()
{
const ff_char_t fmt[] = FF_STR("{0}a{0}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[2].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[2].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[2].maxWidth));
}
static void test_good_7()
{
const ff_char_t fmt[] = FF_STR("{0}a{0}b{0}c{0}d{0}e{0}f{0}g{0}h{0}i{0}j{0}k{0}l{0}m{0}n{0}o{0}p{0}q{0}r{0}s{0}t{0}u{0}v{0}w{0}x{0}y{0}z{0}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(53u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(53u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
{ for(size_t i = 0; i != 26; ++i)
{
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[2 * i + 1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2 * i + 1].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[2 * i + 2].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[2 * i + 2].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[2 * i + 2].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[2 * i + 2].maxWidth));
}}
}
static void test_good_8()
{
const ff_char_t fmt[] = FF_STR("{0}a{1}b{2}c{3}d{4}e{5}f{6}g{7}h{8}i{9}j{10}k{11}l{12}m{13}n{14}o{15}p{16}q{17}r{18}s{19}t{20}u{21}v{22}w{23}x{24}y{25}z{26}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(53u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(53u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
{ for(size_t i = 0; i != 26; ++i)
{
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[2 * i + 1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2 * i + 1].index);
if(i >= 9)
{
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[2 * i + 2].len);
}
else
{
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[2 * i + 2].len);
}
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[2 * i + 2].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[2 * i + 2].maxWidth));
XTESTS_TEST_INTEGER_EQUAL(int(i) + 1, replacements[2 * i + 2].index);
}}
}
static void test_good_9()
{
const ff_char_t fmt[] = FF_STR("{{55}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
}
static void test_good_10()
{
const ff_char_t fmt[] = FF_STR("{{{55}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(55, replacements[1].index);
}
static void test_good_11()
{
const ff_char_t fmt[] = FF_STR("{{}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
}
static void test_good_with_qualifiers_0()
{
const ff_char_t fmt[] = FF_STR("{0}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
}
static void test_good_with_qualifiers_1()
{
const ff_char_t fmt[] = FF_STR("{0,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_2()
{
const ff_char_t fmt[] = FF_STR("{0,,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(5u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_3()
{
const ff_char_t fmt[] = FF_STR("{0,,,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(6u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_4()
{
const ff_char_t fmt[] = FF_STR("{0,0}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(5u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_5()
{
const ff_char_t fmt[] = FF_STR("{0,0,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(6u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_6()
{
const ff_char_t fmt[] = FF_STR("{0,0,,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(7u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_7()
{
const ff_char_t fmt[] = FF_STR("{0,0,0,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(8u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_8()
{
const ff_char_t fmt[] = FF_STR("{0,1,2,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(8u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(1, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(2, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_9()
{
}
static void test_good_with_qualifiers_10()
{
const ff_char_t fmt[] = FF_STR("{23,20}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(7u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(20, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_11()
{
const ff_char_t fmt[] = FF_STR("{23,20,}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(8u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(20, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(-1, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_12()
{
const ff_char_t fmt[] = FF_STR("{23,,10}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(8u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(0, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_13()
{
const ff_char_t fmt[] = FF_STR("{23,10,20}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(10u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(20, int(replacements[0].maxWidth));
}
static void test_good_with_qualifiers_14()
{
const ff_char_t fmt[] = FF_STR("{23,10,10}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(10u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].maxWidth));
XTESTS_TEST_ENUM_EQUAL(FASTFORMAT_ALIGNMENT_NONE, replacements[0].alignment);
XTESTS_TEST_INTEGER_EQUAL(int(' '), replacements[0].fill);
}
static void test_good_with_qualifiers_15()
{
const ff_char_t fmt[] = FF_STR("{23,10,10,>}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(12u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].maxWidth));
XTESTS_TEST_ENUM_EQUAL(FASTFORMAT_ALIGNMENT_RIGHT, replacements[0].alignment);
XTESTS_TEST_INTEGER_EQUAL(int(' '), replacements[0].fill);
}
static void test_good_with_qualifiers_16()
{
const ff_char_t fmt[] = FF_STR("{23,10,10,<}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(12u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].maxWidth));
XTESTS_TEST_ENUM_EQUAL(FASTFORMAT_ALIGNMENT_LEFT, replacements[0].alignment);
XTESTS_TEST_INTEGER_EQUAL(int(' '), replacements[0].fill);
}
static void test_good_with_qualifiers_17()
{
const ff_char_t fmt[] = FF_STR("{23,10,10,^}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(12u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].maxWidth));
XTESTS_TEST_ENUM_EQUAL(FASTFORMAT_ALIGNMENT_CENTRE, replacements[0].alignment);
XTESTS_TEST_INTEGER_EQUAL(int(' '), replacements[0].fill);
}
static void test_good_with_qualifiers_18()
{
const ff_char_t fmt[] = FF_STR("{23,10,10,>#}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), reporting_illformed_handler, NULL);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(13u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(23, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].minWidth));
XTESTS_TEST_INTEGER_EQUAL(10, int(replacements[0].maxWidth));
XTESTS_TEST_ENUM_EQUAL(FASTFORMAT_ALIGNMENT_RIGHT, replacements[0].alignment);
XTESTS_TEST_INTEGER_EQUAL(int('#'), replacements[0].fill);
}
static void test_good_with_qualifiers_19()
{
}
static void test_illformed_cancelling_0()
{
const ff_char_t fmt[] = FF_STR("{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), cancelling_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(0u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(0u, numResultElements);
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(0u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_cancelling_1()
{
const ff_char_t fmt[] = FF_STR("{0"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), cancelling_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(0u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(0u, numResultElements);
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(0u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_cancelling_2()
{
const ff_char_t fmt[] = FF_STR("a{0"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), cancelling_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_cancelling_3()
{
const ff_char_t fmt[] = FF_STR("a{a}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), cancelling_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_cancelling_4()
{
const ff_char_t fmt[] = FF_STR("a{0}{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), cancelling_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(2u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_cancelling_5()
{
const ff_char_t fmt[] = FF_STR("a{0}b{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), cancelling_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(2u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_cancelling_6()
{
}
static void test_illformed_cancelling_7()
{
}
static void test_illformed_cancelling_8()
{
}
static void test_illformed_cancelling_9()
{
}
static void test_illformed_continuing_0()
{
const ff_char_t fmt[] = FF_STR("{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(0u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_1()
{
const ff_char_t fmt[] = FF_STR("{0"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(2u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{0"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(0u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_2()
{
const ff_char_t fmt[] = FF_STR("a{0"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(2u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{0"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_3()
{
const ff_char_t fmt[] = FF_STR("a{a}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_4()
{
const ff_char_t fmt[] = FF_STR("a{0}{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{"), string_t(replacements[2].ptr, replacements[2].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(2u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_5()
{
const ff_char_t fmt[] = FF_STR("a{0}b{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(2u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("b{"), string_t(replacements[2].ptr, replacements[2].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(2u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_6()
{
const ff_char_t fmt[] = FF_STR("a{a}{55}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(55, replacements[2].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_7()
{
const ff_char_t fmt[] = FF_STR("a{a}{55}{bb}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continuing_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(4u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(4u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(55, replacements[2].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[3].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[3].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{bb}"), string_t(replacements[3].ptr, replacements[3].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(3u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{bb}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continuing_8()
{
}
static void test_illformed_continuing_9()
{
}
static void test_illformed_continue_once_0()
{
const ff_char_t fmt[] = FF_STR("{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(0u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_1()
{
const ff_char_t fmt[] = FF_STR("{0"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(1u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(1u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(2u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{0"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(0u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_2()
{
const ff_char_t fmt[] = FF_STR("a{0"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(2u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{0"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_3()
{
const ff_char_t fmt[] = FF_STR("a{a}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(2u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(2u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_4()
{
const ff_char_t fmt[] = FF_STR("a{0}{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{"), string_t(replacements[2].ptr, replacements[2].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(2u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_5()
{
const ff_char_t fmt[] = FF_STR("a{0}b{"); // Missing }
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(0, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(2u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[2].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("b{"), string_t(replacements[2].ptr, replacements[2].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(2u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING(""), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_6()
{
const ff_char_t fmt[] = FF_STR("a{a}{55}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(3u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(3u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(55, replacements[2].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_7()
{
const ff_char_t fmt[] = FF_STR("a{a}{55}{bb}");
fastformat::format_element_t replacements[1 + STLSOFT_NUM_ELEMENTS(fmt) / 2];
parse_error_t pe;
size_t numFormatElements;
size_t numResultElements;
unsigned n = fastformat_parseFormat(fmt, stlsoft::c_str_len(fmt), &replacements[0], STLSOFT_NUM_ELEMENTS(replacements), continue_once_mock_illformed_handler, &pe);
numFormatElements = n & 0xffff;
numResultElements = ((n >> 16) & 0xffff);
XTESTS_TEST_INTEGER_EQUAL(4u, numFormatElements);
XTESTS_TEST_INTEGER_EQUAL(4u, numResultElements);
XTESTS_TEST_INTEGER_EQUAL(1u, replacements[0].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[0].index);
XTESTS_TEST_INTEGER_EQUAL(3u, replacements[1].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[1].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[2].len);
XTESTS_TEST_INTEGER_EQUAL(55, replacements[2].index);
XTESTS_TEST_INTEGER_EQUAL(4u, replacements[3].len);
XTESTS_TEST_INTEGER_EQUAL(-1, replacements[3].index);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("a"), string_t(replacements[0].ptr, replacements[0].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), string_t(replacements[1].ptr, replacements[1].len));
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{bb}"), string_t(replacements[3].ptr, replacements[3].len));
XTESTS_TEST_STRING_EQUAL(fmt, pe.format);
XTESTS_TEST_INTEGER_EQUAL(1u, pe.replacementIndex);
XTESTS_TEST_STRING_EQUAL(FASTFORMAT_LITERAL_STRING("{a}"), pe.defect);
XTESTS_TEST_INTEGER_EQUAL(-1, pe.parameterIndex);
}
static void test_illformed_continue_once_8()
{
}
static void test_illformed_continue_once_9()
{
}
} // anonymous namespace
/* ///////////////////////////// end of file //////////////////////////// */
| 43.185647 | 179 | 0.688399 | [
"vector"
] |
5dd9d417a48dfe964ab9ffad5d342d3d223d70af | 3,426 | cpp | C++ | oi/Contest/self/2016-12/C.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/Contest/self/2016-12/C.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/Contest/self/2016-12/C.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <cstdio>
#include <cctype>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define INPUT_BUFFERSIZE 65536
static size_t ipos = INPUT_BUFFERSIZE;
static char ibuffer[INPUT_BUFFERSIZE];
inline char _getchar() {
if (ipos == INPUT_BUFFERSIZE) {
ipos = 0;
fread(ibuffer, 1, INPUT_BUFFERSIZE, stdin);
}
return ibuffer[ipos++];
}
inline char next_char() {
char c = _getchar();
while (!isalpha(c))
c = _getchar();
return c;
}
inline int readint() {
int x = 0;
char c = _getchar();
while (!isdigit(c))
c = _getchar();
while (isdigit(c)) {
x = x * 10 + (c - '0');
c = _getchar();
}
return x;
}
#define NMAX 1000000
#define MMAX 1500000
enum CommandType {
ADD,
COPY,
QUERY
};
struct Command {
CommandType type;
int ver;
int a, b, c;
int answer;
};
struct Node {
Node ()
: left(0), right(0) {}
vector<Command *> ops;
Node *left;
Node *right;
};
static int n, m;
static Command commands[MMAX + 10];
static Node *root;
static Node *node[MMAX + 10];
static int fenwick[NMAX + 10];
inline int query(int r) {
int answer = 0;
for (; r; r -= r & (-r)) {
answer += fenwick[r];
}
return answer;
}
inline void modify(int x, int v) {
for (; x <= n; x += x & (-x)) {
fenwick[x] += v;
}
}
static void initialize() {
// scanf("%d%d", &n, &m);
n = readint();
m = readint();
node[1] = new Node;
root = node[1];
char command;
int ver = 1;
for (int i = 1; i <= m; i++) {
// scanf("%s", command);
command = next_char();
Command &comm = commands[i];
if (command == 'A') {
// scanf("%d%d%d", &comm.a, &comm.b, &comm.c);
comm.a = readint();
comm.b = readint();
comm.c = readint();
comm.type = ADD;
node[comm.a]->ops.push_back(&comm);
} else if (command == 'C') {
// scanf("%d", &comm.a);
comm.a = readint();
comm.type = COPY;
comm.ver = ++ver;
node[ver] = new Node;
Node *newnode = new Node;
node[comm.a]->left = node[ver];
node[comm.a]->right = newnode;
node[comm.a] = newnode;
} else {
// scanf("%d%d%d", &comm.a, &comm.b, &comm.c);
comm.a = readint();
comm.b = readint();
comm.c = readint();
comm.type = QUERY;
node[comm.a]->ops.push_back(&comm);
}
}
}
static void answer_all(Node *x) {
for (size_t i = 0; i < x->ops.size(); i++) {
Command *comm = x->ops[i];
if (comm->type == QUERY) {
comm->answer = query(comm->c) - query(comm->b - 1);
} else {
modify(comm->b, comm->c);
}
}
if (x->left)
answer_all(x->left);
if (x->right)
answer_all(x->right);
for (size_t i = 0; i < x->ops.size(); i++) {
Command *comm = x->ops[i];
if (comm->type == ADD) {
modify(comm->b, -comm->c);
}
}
}
int main() {
initialize();
answer_all(root);
for (int i = 1; i <= m; i++) {
Command &comm = commands[i];
if (comm.type == QUERY) {
printf("%d\n", comm.answer);
}
}
return 0;
}
| 18.928177 | 63 | 0.475773 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.