<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Query.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:41:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _XMLSEARCH_QE_QUERY_HXX_
#include <qe/Query.hxx>
#endif
#ifndef _XMLSEARCH_QE_XMLINDEX_HXX_
#include <qe/XmlIndex.hxx>
#endif
#ifndef _XMLSEARCH_QE_CONCEPTDATA_HXX_
#include <qe/ConceptData.hxx>
#endif
#ifndef _XMLSEARCH_QE_QUERYPROCESSOR_HXX_
#include <qe/QueryProcessor.hxx>
#endif
#ifndef _XMLSEARCH_QE_CONTEXTTABLES_HXX_
#include <qe/ContextTables.hxx>
#endif

using namespace xmlsearch::qe;

sal_Int32* QueryHit::getMatches( sal_Int32& matchesL )
{
    matchesL = matchesL_;
    return matches_;
}

/******************************************************************************/
/*                                                                            */
/*                     HitStore                                               */
/*                                                                            */
/******************************************************************************/

HitStore::HitStore( double initialStandard,sal_Int32 limit,sal_Int32 nColumns )
    : limit_( limit ),
      nColumns_( nColumns ),
      index_( 0 ),
      free_( 0 ),
      standard_( initialStandard ),
      heap_( limit )
{
    for( sal_uInt32 i = 0; i < heap_.size(); ++i )
        heap_[i] = 0;
}

HitStore::~HitStore()
{
    for( sal_uInt32 i = 0; i < heap_.size(); ++i )
        delete heap_[i];
}

bool HitStore::goodEnough( double penalty, sal_Int32 begin, sal_Int32 end )
{
    return free_ == limit_ ? heap_[0]->worseThan( penalty,begin,end ) : true;
}

QueryHit* HitStore::createQueryHit( double penalty,sal_Int32 doc,sal_Int32 begin,sal_Int32 end )
{
    QueryHit* hit = new QueryHit( nColumns_,penalty,doc,begin,end );
    if( free_ == limit_ )
    { // goodEnough'ness checked already
        delete heap_[0];
        heap_[0] = hit;
        heapify( 0 );
        standard_ = heap_[0]->getPenalty();
    }
    else if( free_ < limit_ )
    {
        heap_[ free_++ ] = hit;
        if( free_ == limit_ )
        { // we have the needed number
            for( sal_Int32 i = free_/2; i >= 0; --i ) // build heap
                heapify( i );
            standard_ = heap_[0]->getPenalty();
        }
    }
    return hit;
}

struct CompareQueryHit
{
    bool operator()( const QueryHit* l,const QueryHit* r )
    {
        return l->compareTo( r );
    }
};

#include <algorithm>

QueryHit* HitStore::firstBestQueryHit()
{
    if( free_ > 0)
    {
        CompareQueryHit bla;
        heap_.resize( free_ );
          std::stable_sort( heap_.begin(),heap_.end(),bla );
        index_ = 0;
        return nextBestQueryHit();
    }
    else
        return 0;
}

QueryHit* HitStore::nextBestQueryHit()
{
    return index_ < free_ ? heap_[ index_++ ] : 0;
}

void HitStore::heapify( sal_Int32 i )
{
    for( sal_Int32 r,l,worst; ; )
    {
        r = (i + 1) << 1; l = r - 1;
        worst = l < free_ && heap_[i]->betterThan( heap_[l] ) ? l : i;
        if( r < free_ && heap_[ worst ]->betterThan( heap_[r] ) )
            worst = r;
        if (worst != i)
        {
            QueryHit* temp = heap_[ worst ];
            heap_[ worst ] = heap_[ i ];
            heap_[i] = temp;
            i = worst;      // continue
        }
        else
            break;
    }
}

//  sal_Int32 HitStore::partition( sal_Int32 p,sal_Int32 r )
//  {
//      QueryHit* x = heap_[ ((p + r) >> 1) & 0x7FFFFFFF ];
//      sal_Int32 i = p - 1, j = r + 1;
//      while( true )
//      {
//          while( x->compareTo( heap_[--j] ) )
//              ;
//          while( heap_[++i]->compareTo( x ) )
//              ;
//          if( i < j )
//          {
//              QueryHit* t = heap_[i];
//              heap_[i] = heap_[j];
//              heap_[j] = t;
//          }
//          else
//              return j;
//      }
//  }

//  void HitStore::quicksort( sal_Int32 p,sal_Int32 r )
//  {
//      while( p < r )
//      {
//          sal_Int32 q = partition( p,r );
//          quicksort(p, q);
//          p = q + 1;
//      }
//  }

/******************************************************************************/
/*                                                                            */
/*                                 Query                                      */
/*                                                                            */
/******************************************************************************/

#define MissingTermPenalty 10.0

Query::Query( XmlIndex* env,
              sal_Int32 nColumns,
              sal_Int32 nHits,
              sal_Int32 missingPenaltiesL,
              double* missingPenalties )
    : env_( env ),
      ctx_( env ? env->getContextInfo() : 0 ),
      store_( nColumns * MissingTermPenalty - 0.0001,nHits,nColumns ),
      nHitsRequested_( nHits ),
      nColumns_( nColumns ),
      currentStandard_( nColumns * MissingTermPenalty - 0.0001 ),
      missingPenaltyL_( nColumns ),
      upperboundTemplateL_( nColumns ),
      penaltiesL_( missingPenaltiesL ),
      missingPenalty_( new double[ nColumns ] ),
      upperboundTemplate_( new double[ nColumns ] ),
      penalties_( missingPenalties ),
      ignoredElementsL_( 0 ),
      ignoredElements_( 0 ),
      missingTermsPenalty_( 0.0 )
{
    // for the EmptyQuery case (awaits arch improvement pass)

    if( missingPenalties )
        for( sal_Int32 i = 0;i < nColumns_; ++i )
            missingPenalty_[i] = missingPenalties[i];
    else
        for( sal_Int32 i = 0;i < nColumns_; ++i )
            missingPenalty_[i] = MissingTermPenalty;

    makePenaltiesTable();
    //  _roleFillerList = RoleFiller.STOP;
}

Query::~Query()
{
    delete[] missingPenalty_;
    delete[] upperboundTemplate_;
    delete[] penalties_;
    delete[] ignoredElements_;
}

void Query::setIgnoredElements( const sal_Int32 ignoredElementsL,const rtl::OUString* ignoredElements )
{
    if( ctx_ )
        ignoredElements_ = ctx_->getIgnoredElementsSet( ignoredElementsL_,
                                                        ignoredElementsL,ignoredElements );

    if( ! ctx_ )
    {
        ignoredElementsL_ = 0;
        ignoredElements_   = 0;
    }
}

void Query::missingTerms( sal_Int32 nMissingTerms )
{
    missingTermsPenalty_ = MissingTermPenalty * nMissingTerms;
}

ConceptData* Query::makeConceptData( sal_Int32 col,sal_Int32 concept,double penalty,sal_Int32 queryNo )
{
    return new ConceptData( concept,col,penalty,queryNo,nColumns_,env_->getContextInfo() );;
}

void Query::getHits( std::vector< QueryHitData* >& data,sal_Int32 n )
{
    if( n <= 0 )
        return;

    QueryHit* qh = store_.firstBestQueryHit();

    while( qh )
    {
        data.push_back( env_->hitToData( qh ) );
        qh = data.size() < sal_uInt32( n ) ? store_.nextBestQueryHit() : 0;
    }
}

QueryHit* Query::maybeCreateQueryHit( double penalty,
                                      sal_Int32 doc, sal_Int32 begin, sal_Int32 end, sal_Int32 parentContext )
{
    // hits are located using only terms actually present in text
    // if B is not present, the query A B C reduces to A C and penalties
    // are computed as if B did not occur in query
    // to meaningfully merge results from different servers, some of which
    // may have B, penalty has to be normalized to the common computing scheme

    QueryHit* res =
        ( store_.goodEnough( penalty += missingTermsPenalty_,begin,end )
          && ( ! ignoredElements_ || ctx_->notIgnored( parentContext,ignoredElementsL_,ignoredElements_ ) ) )
        ?
        store_.createQueryHit( penalty,doc,begin,end )
        :
        0;
    return res;
}

void Query::makePenaltiesTable()
{
    sal_Int32 nPatterns = 1 << nColumns_;
    delete[] penalties_;
    penalties_ = new double[ penaltiesL_ = nPatterns ];
    for (sal_Int32 i = 0; i < nPatterns; ++i )
        penalties_[i] = computePenalty(i);
}

double Query::computePenalty( sal_Int32 n )
{
    double penalty = 0.0;
    for( sal_Int32 i = 0; i < nColumns_; ++i )
        if( ( n & 1 << i ) == 0 )
            penalty += missingPenalty_[i];
    return penalty;
}

void Query::resetForNextDocument()
{
    currentStandard_ = store_.getCurrentStandard();
    // "everything's missing"
    for( sal_Int32 i = 0; i < nColumns_; i++ )
        upperboundTemplate_[i] = missingPenalty_[i];
    vote_ = false;
}

bool Query::vote()
{
    double sum = 0.0;
    for( sal_Int32 i = 0; i < nColumns_; i++ )
        sum += upperboundTemplate_[i];
    return vote_ = (sum <= currentStandard_ );
}

void Query::updateEstimate( sal_Int32 role,double penalty )
{
    if( penalty < upperboundTemplate_[ role ] )
        upperboundTemplate_[ role ] = penalty;
}

/******************************************************************************/
/*                                                                            */
/*                         QueryHitIterator                                   */
/*                                                                            */
/******************************************************************************/

QueryHitIterator::QueryHitIterator( const QueryResults* result )
    : index_( -1 ),
      result_( result )
{
}

QueryHitIterator::~QueryHitIterator()
{
    delete result_;
}

bool QueryHitIterator::next()
{
    return accessible_ = ( ++index_ < sal_Int32( result_->queryHits_.size() ) );
}

QueryHitData* QueryHitIterator::getHit( const PrefixTranslator* ) const
{
    if( accessible_ )
        return result_->queryHits_[index_];
    else
        return 0;
}

double QueryHitIterator::getPenalty()
{
    if( accessible_ )
        return result_->queryHits_[index_]->getPenalty();
    else
        return 1.0E30;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.10.8); FILE MERGED 2006/09/01 17:58:34 kaib 1.10.8.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Query.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:19:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlhelp.hxx"
#ifndef _XMLSEARCH_QE_QUERY_HXX_
#include <qe/Query.hxx>
#endif
#ifndef _XMLSEARCH_QE_XMLINDEX_HXX_
#include <qe/XmlIndex.hxx>
#endif
#ifndef _XMLSEARCH_QE_CONCEPTDATA_HXX_
#include <qe/ConceptData.hxx>
#endif
#ifndef _XMLSEARCH_QE_QUERYPROCESSOR_HXX_
#include <qe/QueryProcessor.hxx>
#endif
#ifndef _XMLSEARCH_QE_CONTEXTTABLES_HXX_
#include <qe/ContextTables.hxx>
#endif

using namespace xmlsearch::qe;

sal_Int32* QueryHit::getMatches( sal_Int32& matchesL )
{
    matchesL = matchesL_;
    return matches_;
}

/******************************************************************************/
/*                                                                            */
/*                     HitStore                                               */
/*                                                                            */
/******************************************************************************/

HitStore::HitStore( double initialStandard,sal_Int32 limit,sal_Int32 nColumns )
    : limit_( limit ),
      nColumns_( nColumns ),
      index_( 0 ),
      free_( 0 ),
      standard_( initialStandard ),
      heap_( limit )
{
    for( sal_uInt32 i = 0; i < heap_.size(); ++i )
        heap_[i] = 0;
}

HitStore::~HitStore()
{
    for( sal_uInt32 i = 0; i < heap_.size(); ++i )
        delete heap_[i];
}

bool HitStore::goodEnough( double penalty, sal_Int32 begin, sal_Int32 end )
{
    return free_ == limit_ ? heap_[0]->worseThan( penalty,begin,end ) : true;
}

QueryHit* HitStore::createQueryHit( double penalty,sal_Int32 doc,sal_Int32 begin,sal_Int32 end )
{
    QueryHit* hit = new QueryHit( nColumns_,penalty,doc,begin,end );
    if( free_ == limit_ )
    { // goodEnough'ness checked already
        delete heap_[0];
        heap_[0] = hit;
        heapify( 0 );
        standard_ = heap_[0]->getPenalty();
    }
    else if( free_ < limit_ )
    {
        heap_[ free_++ ] = hit;
        if( free_ == limit_ )
        { // we have the needed number
            for( sal_Int32 i = free_/2; i >= 0; --i ) // build heap
                heapify( i );
            standard_ = heap_[0]->getPenalty();
        }
    }
    return hit;
}

struct CompareQueryHit
{
    bool operator()( const QueryHit* l,const QueryHit* r )
    {
        return l->compareTo( r );
    }
};

#include <algorithm>

QueryHit* HitStore::firstBestQueryHit()
{
    if( free_ > 0)
    {
        CompareQueryHit bla;
        heap_.resize( free_ );
          std::stable_sort( heap_.begin(),heap_.end(),bla );
        index_ = 0;
        return nextBestQueryHit();
    }
    else
        return 0;
}

QueryHit* HitStore::nextBestQueryHit()
{
    return index_ < free_ ? heap_[ index_++ ] : 0;
}

void HitStore::heapify( sal_Int32 i )
{
    for( sal_Int32 r,l,worst; ; )
    {
        r = (i + 1) << 1; l = r - 1;
        worst = l < free_ && heap_[i]->betterThan( heap_[l] ) ? l : i;
        if( r < free_ && heap_[ worst ]->betterThan( heap_[r] ) )
            worst = r;
        if (worst != i)
        {
            QueryHit* temp = heap_[ worst ];
            heap_[ worst ] = heap_[ i ];
            heap_[i] = temp;
            i = worst;      // continue
        }
        else
            break;
    }
}

//  sal_Int32 HitStore::partition( sal_Int32 p,sal_Int32 r )
//  {
//      QueryHit* x = heap_[ ((p + r) >> 1) & 0x7FFFFFFF ];
//      sal_Int32 i = p - 1, j = r + 1;
//      while( true )
//      {
//          while( x->compareTo( heap_[--j] ) )
//              ;
//          while( heap_[++i]->compareTo( x ) )
//              ;
//          if( i < j )
//          {
//              QueryHit* t = heap_[i];
//              heap_[i] = heap_[j];
//              heap_[j] = t;
//          }
//          else
//              return j;
//      }
//  }

//  void HitStore::quicksort( sal_Int32 p,sal_Int32 r )
//  {
//      while( p < r )
//      {
//          sal_Int32 q = partition( p,r );
//          quicksort(p, q);
//          p = q + 1;
//      }
//  }

/******************************************************************************/
/*                                                                            */
/*                                 Query                                      */
/*                                                                            */
/******************************************************************************/

#define MissingTermPenalty 10.0

Query::Query( XmlIndex* env,
              sal_Int32 nColumns,
              sal_Int32 nHits,
              sal_Int32 missingPenaltiesL,
              double* missingPenalties )
    : env_( env ),
      ctx_( env ? env->getContextInfo() : 0 ),
      store_( nColumns * MissingTermPenalty - 0.0001,nHits,nColumns ),
      nHitsRequested_( nHits ),
      nColumns_( nColumns ),
      currentStandard_( nColumns * MissingTermPenalty - 0.0001 ),
      missingPenaltyL_( nColumns ),
      upperboundTemplateL_( nColumns ),
      penaltiesL_( missingPenaltiesL ),
      missingPenalty_( new double[ nColumns ] ),
      upperboundTemplate_( new double[ nColumns ] ),
      penalties_( missingPenalties ),
      ignoredElementsL_( 0 ),
      ignoredElements_( 0 ),
      missingTermsPenalty_( 0.0 )
{
    // for the EmptyQuery case (awaits arch improvement pass)

    if( missingPenalties )
        for( sal_Int32 i = 0;i < nColumns_; ++i )
            missingPenalty_[i] = missingPenalties[i];
    else
        for( sal_Int32 i = 0;i < nColumns_; ++i )
            missingPenalty_[i] = MissingTermPenalty;

    makePenaltiesTable();
    //  _roleFillerList = RoleFiller.STOP;
}

Query::~Query()
{
    delete[] missingPenalty_;
    delete[] upperboundTemplate_;
    delete[] penalties_;
    delete[] ignoredElements_;
}

void Query::setIgnoredElements( const sal_Int32 ignoredElementsL,const rtl::OUString* ignoredElements )
{
    if( ctx_ )
        ignoredElements_ = ctx_->getIgnoredElementsSet( ignoredElementsL_,
                                                        ignoredElementsL,ignoredElements );

    if( ! ctx_ )
    {
        ignoredElementsL_ = 0;
        ignoredElements_   = 0;
    }
}

void Query::missingTerms( sal_Int32 nMissingTerms )
{
    missingTermsPenalty_ = MissingTermPenalty * nMissingTerms;
}

ConceptData* Query::makeConceptData( sal_Int32 col,sal_Int32 concept,double penalty,sal_Int32 queryNo )
{
    return new ConceptData( concept,col,penalty,queryNo,nColumns_,env_->getContextInfo() );;
}

void Query::getHits( std::vector< QueryHitData* >& data,sal_Int32 n )
{
    if( n <= 0 )
        return;

    QueryHit* qh = store_.firstBestQueryHit();

    while( qh )
    {
        data.push_back( env_->hitToData( qh ) );
        qh = data.size() < sal_uInt32( n ) ? store_.nextBestQueryHit() : 0;
    }
}

QueryHit* Query::maybeCreateQueryHit( double penalty,
                                      sal_Int32 doc, sal_Int32 begin, sal_Int32 end, sal_Int32 parentContext )
{
    // hits are located using only terms actually present in text
    // if B is not present, the query A B C reduces to A C and penalties
    // are computed as if B did not occur in query
    // to meaningfully merge results from different servers, some of which
    // may have B, penalty has to be normalized to the common computing scheme

    QueryHit* res =
        ( store_.goodEnough( penalty += missingTermsPenalty_,begin,end )
          && ( ! ignoredElements_ || ctx_->notIgnored( parentContext,ignoredElementsL_,ignoredElements_ ) ) )
        ?
        store_.createQueryHit( penalty,doc,begin,end )
        :
        0;
    return res;
}

void Query::makePenaltiesTable()
{
    sal_Int32 nPatterns = 1 << nColumns_;
    delete[] penalties_;
    penalties_ = new double[ penaltiesL_ = nPatterns ];
    for (sal_Int32 i = 0; i < nPatterns; ++i )
        penalties_[i] = computePenalty(i);
}

double Query::computePenalty( sal_Int32 n )
{
    double penalty = 0.0;
    for( sal_Int32 i = 0; i < nColumns_; ++i )
        if( ( n & 1 << i ) == 0 )
            penalty += missingPenalty_[i];
    return penalty;
}

void Query::resetForNextDocument()
{
    currentStandard_ = store_.getCurrentStandard();
    // "everything's missing"
    for( sal_Int32 i = 0; i < nColumns_; i++ )
        upperboundTemplate_[i] = missingPenalty_[i];
    vote_ = false;
}

bool Query::vote()
{
    double sum = 0.0;
    for( sal_Int32 i = 0; i < nColumns_; i++ )
        sum += upperboundTemplate_[i];
    return vote_ = (sum <= currentStandard_ );
}

void Query::updateEstimate( sal_Int32 role,double penalty )
{
    if( penalty < upperboundTemplate_[ role ] )
        upperboundTemplate_[ role ] = penalty;
}

/******************************************************************************/
/*                                                                            */
/*                         QueryHitIterator                                   */
/*                                                                            */
/******************************************************************************/

QueryHitIterator::QueryHitIterator( const QueryResults* result )
    : index_( -1 ),
      result_( result )
{
}

QueryHitIterator::~QueryHitIterator()
{
    delete result_;
}

bool QueryHitIterator::next()
{
    return accessible_ = ( ++index_ < sal_Int32( result_->queryHits_.size() ) );
}

QueryHitData* QueryHitIterator::getHit( const PrefixTranslator* ) const
{
    if( accessible_ )
        return result_->queryHits_[index_];
    else
        return 0;
}

double QueryHitIterator::getPenalty()
{
    if( accessible_ )
        return result_->queryHits_[index_]->getPenalty();
    else
        return 1.0E30;
}

<|endoftext|>


<commit_before>// Copyright (c) Facebook, Inc. and its affiliates.
//
// 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 <folly/Portability.h>
#include <folly/io/async/EventBase.h>
#include <gtest/gtest.h>
#include <vector>

#include "yarpl/Flowable.h"
#include "yarpl/flowable/TestSubscriber.h"
#include "yarpl/flowable/ThriftStreamShim.h"

using namespace yarpl::flowable;

template <typename T>
std::vector<T> run(
    std::shared_ptr<Flowable<T>> flowable,
    int64_t requestCount = 100) {
  auto subscriber = std::make_shared<TestSubscriber<T>>(requestCount);
  flowable->subscribe(subscriber);
  subscriber->awaitTerminalEvent(std::chrono::seconds(1));
  return std::move(subscriber->values());
}
template <typename T>
std::vector<T> run(apache::thrift::ServerStream<T>&& stream) {
  std::vector<T> values;
  std::move(stream).toClientStreamUnsafeDoNotUse().subscribeInline([&](auto&& val) {
    if (val.hasValue()) {
      values.push_back(std::move(*val));
    }
  });
  return values;
}

apache::thrift::ClientBufferedStream<int> makeRange(int start, int count) {
  auto streamAndPublisher =
      apache::thrift::ServerStream<int>::createPublisher();
  for (int i = 0; i < count; ++i) {
    streamAndPublisher.second.next(i + start);
  }
  std::move(streamAndPublisher.second).complete();
  return std::move(streamAndPublisher.first).toClientStreamUnsafeDoNotUse();
}

TEST(ThriftStreamShimTest, ClientStream) {
  auto flowable = ThriftStreamShim::fromClientStream(
      makeRange(1, 5), folly::getEventBase());
  EXPECT_EQ(run(flowable), std::vector<int>({1, 2, 3, 4, 5}));
}

TEST(ThriftStreamShimTest, ServerStream) {
  auto stream = ThriftStreamShim::toServerStream(Flowable<>::range(1, 5));
  EXPECT_EQ(run(std::move(stream)), std::vector<long>({1, 2, 3, 4, 5}));

  stream = ThriftStreamShim::toServerStream(Flowable<long>::never());
  auto sub = std::move(stream).toClientStreamUnsafeDoNotUse().subscribeExTry(
      folly::getEventBase(), [](auto) {});
  sub.cancel();
  std::move(sub).join();

  ThriftStreamShim::toServerStream(Flowable<>::just(std::make_unique<int>(42)));
}
<commit_msg>Remove dead includes in yarpl<commit_after>// Copyright (c) Facebook, Inc. and its affiliates.
//
// 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 <folly/io/async/EventBase.h>
#include <gtest/gtest.h>
#include <vector>

#include "yarpl/Flowable.h"
#include "yarpl/flowable/TestSubscriber.h"
#include "yarpl/flowable/ThriftStreamShim.h"

using namespace yarpl::flowable;

template <typename T>
std::vector<T> run(
    std::shared_ptr<Flowable<T>> flowable,
    int64_t requestCount = 100) {
  auto subscriber = std::make_shared<TestSubscriber<T>>(requestCount);
  flowable->subscribe(subscriber);
  subscriber->awaitTerminalEvent(std::chrono::seconds(1));
  return std::move(subscriber->values());
}
template <typename T>
std::vector<T> run(apache::thrift::ServerStream<T>&& stream) {
  std::vector<T> values;
  std::move(stream).toClientStreamUnsafeDoNotUse().subscribeInline([&](auto&& val) {
    if (val.hasValue()) {
      values.push_back(std::move(*val));
    }
  });
  return values;
}

apache::thrift::ClientBufferedStream<int> makeRange(int start, int count) {
  auto streamAndPublisher =
      apache::thrift::ServerStream<int>::createPublisher();
  for (int i = 0; i < count; ++i) {
    streamAndPublisher.second.next(i + start);
  }
  std::move(streamAndPublisher.second).complete();
  return std::move(streamAndPublisher.first).toClientStreamUnsafeDoNotUse();
}

TEST(ThriftStreamShimTest, ClientStream) {
  auto flowable = ThriftStreamShim::fromClientStream(
      makeRange(1, 5), folly::getEventBase());
  EXPECT_EQ(run(flowable), std::vector<int>({1, 2, 3, 4, 5}));
}

TEST(ThriftStreamShimTest, ServerStream) {
  auto stream = ThriftStreamShim::toServerStream(Flowable<>::range(1, 5));
  EXPECT_EQ(run(std::move(stream)), std::vector<long>({1, 2, 3, 4, 5}));

  stream = ThriftStreamShim::toServerStream(Flowable<long>::never());
  auto sub = std::move(stream).toClientStreamUnsafeDoNotUse().subscribeExTry(
      folly::getEventBase(), [](auto) {});
  sub.cancel();
  std::move(sub).join();

  ThriftStreamShim::toServerStream(Flowable<>::just(std::make_unique<int>(42)));
}
<|endoftext|>


<commit_before>/* Copyright 2018 Kristofer Björnson
 *
 * 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.
 */

/** @file Greens.cpp
 *
 *  @author Kristofer Björnson
 */

#include "TBTK/PropertyExtractor/Greens.h"
#include "TBTK/Functions.h"
#include "TBTK/Streams.h"
#include "TBTK/TBTKMacros.h"

#include <set>

using namespace std;

namespace TBTK{
namespace PropertyExtractor{

Greens::Greens(Solver::Greens &solver){
	this->solver = &solver;
}

Greens::~Greens(){
}

void Greens::setEnergyWindow(
	double lowerBound,
	double upperBound,
	int energyResolution
){
	TBTKExit(
		"PropertyExtractor::Greens::setEnergyWindow()",
		"This function is not supported by this PropertyExtractor.",
		"The energy window is instead determined by the Green's"
		<< " function that is used by the corresponding solver. Use"
		<< " Solver::Greens::setGreensFunction() to set this Green's"
		<< " function."
	);
}

Property::Density Greens::calculateDensity(
	Index pattern,
	Index ranges
){
	ensureCompliantRanges(pattern, ranges);

	vector<int> loopRanges = getLoopRanges(pattern, ranges);
	Property::Density density(loopRanges);

	Information information;
	calculate(
		calculateDensityCallback,
		density,
		pattern,
		ranges,
		0,
		1,
		information
	);

	return density;
}

Property::Density Greens::calculateDensity(
	vector<Index> patterns
){
	validatePatternsNumComponents(
		patterns,
		1,
		"PropertyExtractor::Greens::calculateDensity()"
	);
	validatePatternsSpecifiers(
		patterns,
		{IDX_ALL, IDX_SUM_ALL},
		"PropertyExtractor::Greens::calculateDensity()"
	);

	IndexTree allIndices = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		false,
		false
	);

	IndexTree memoryLayout = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		true,
		true
	);

	Property::Density density(memoryLayout);

	Information information;
	calculate(
		calculateDensityCallback,
		allIndices,
		memoryLayout,
		density,
		information
	);

	return density;
}

Property::LDOS Greens::calculateLDOS(
	vector<Index> patterns
){
	validatePatternsNumComponents(
		patterns,
		1,
		"PropertyExtractor::Greens::calculateLDOS()"
	);
	validatePatternsSpecifiers(
		patterns,
		{IDX_ALL, IDX_SUM_ALL},
		"PropertyExtractor::Greens::calculateLDOS()"
	);

	IndexTree allIndices = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		false,
		true
	);

	IndexTree memoryLayout = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		true,
		true
	);

	Property::LDOS ldos(
		memoryLayout,
		solver->getGreensFunction().getLowerBound(),
		solver->getGreensFunction().getUpperBound(),
		solver->getGreensFunction().getResolution()
	);

	Information information;
	calculate(
		calculateLDOSCallback,
		allIndices,
		memoryLayout,
		ldos,
		information
	);

	return ldos;
}

void Greens::calculateDensityCallback(
	PropertyExtractor *cb_this,
	Property::Property &property,
	const Index &index,
	int offset,
	Information &information
){
	Greens *propertyExtractor = (Greens*)cb_this;
	Property::Density &density = (Property::Density&)property;
	vector<double> &data = density.getDataRW();

	const Property::GreensFunction &greensFunction
		= propertyExtractor->solver->getGreensFunction();

	Statistics statistics = propertyExtractor->solver->getModel().getStatistics();

	switch(greensFunction.getType()){
	case Property::GreensFunction::Type::Retarded:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int e = 0; e < energyResolution; e++){
			double E = lowerBound + e*dE;

			double weight;
			if(statistics == Statistics::FermiDirac){
				weight = Functions::fermiDiracDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel(
					).getTemperature()
				);
			}
			else{
				weight = Functions::boseEinsteinDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel().getTemperature()
				);
			}

			data[offset] += -weight*imag(
				greensFunction({index, index}, e)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Advanced:
	case Property::GreensFunction::Type::NonPrincipal:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int e = 0; e < energyResolution; e++){
			double E = lowerBound + e*dE;

			double weight;
			if(statistics == Statistics::FermiDirac){
				weight = Functions::fermiDiracDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel().getTemperature()
				);
			}
			else{
				weight = Functions::boseEinsteinDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel().getTemperature()
				);
			}

			data[offset] += weight*imag(
				greensFunction({index, index}, e)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Principal:
	default:
		TBTKExit(
			"PropertyExtractor::Greens::calculateDensityCallback()",
			"Only calculation of the Density from the Retarded,"
			<< " Advanced, and NonPrincipal Green's function"
			<< " is supported yet.",
			""
		);
	}
}

void Greens::calculateLDOSCallback(
	PropertyExtractor *cb_this,
	Property::Property &property,
	const Index &index,
	int offset,
	Information &information
){
	Greens *propertyExtractor = (Greens*)cb_this;
	Property::LDOS &ldos = (Property::LDOS&)property;
	vector<double> &data = ldos.getDataRW();

	const Property::GreensFunction &greensFunction
		= propertyExtractor->solver->getGreensFunction();

	switch(greensFunction.getType()){
	case Property::GreensFunction::Type::Retarded:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int n = 0; n < energyResolution; n++){
			data[offset + n] -= imag(
				greensFunction({index, index}, n)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Advanced:
	case Property::GreensFunction::Type::NonPrincipal:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int n = 0; n < energyResolution; n++){
			data[offset + n] += imag(
				greensFunction({index, index}, n)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Principal:
	default:
		TBTKExit(
			"PropertyExtractor::Greens::calculateDensityCallback()",
			"Only calculation of the Density from the Retarded,"
			<< " Advanced, and NonPrincipal Green's function"
			<< " is supported yet.",
			""
		);
	}
}

};	//End of namespace PropertyExtractor
};	//End of namespace TBTK
<commit_msg>Added density calculation for Matsubara Green's functions to PropertyExtractor::Greens.<commit_after>/* Copyright 2018 Kristofer Björnson
 *
 * 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.
 */

/** @file Greens.cpp
 *
 *  @author Kristofer Björnson
 */

#include "TBTK/PropertyExtractor/Greens.h"
#include "TBTK/Functions.h"
#include "TBTK/Streams.h"
#include "TBTK/TBTKMacros.h"

#include <set>

using namespace std;

namespace TBTK{
namespace PropertyExtractor{

Greens::Greens(Solver::Greens &solver){
	this->solver = &solver;
}

Greens::~Greens(){
}

void Greens::setEnergyWindow(
	double lowerBound,
	double upperBound,
	int energyResolution
){
	TBTKExit(
		"PropertyExtractor::Greens::setEnergyWindow()",
		"This function is not supported by this PropertyExtractor.",
		"The energy window is instead determined by the Green's"
		<< " function that is used by the corresponding solver. Use"
		<< " Solver::Greens::setGreensFunction() to set this Green's"
		<< " function."
	);
}

Property::Density Greens::calculateDensity(
	Index pattern,
	Index ranges
){
	ensureCompliantRanges(pattern, ranges);

	vector<int> loopRanges = getLoopRanges(pattern, ranges);
	Property::Density density(loopRanges);

	Information information;
	calculate(
		calculateDensityCallback,
		density,
		pattern,
		ranges,
		0,
		1,
		information
	);

	return density;
}

Property::Density Greens::calculateDensity(
	vector<Index> patterns
){
	validatePatternsNumComponents(
		patterns,
		1,
		"PropertyExtractor::Greens::calculateDensity()"
	);
	validatePatternsSpecifiers(
		patterns,
		{IDX_ALL, IDX_SUM_ALL},
		"PropertyExtractor::Greens::calculateDensity()"
	);

	IndexTree allIndices = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		false,
		false
	);

	IndexTree memoryLayout = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		true,
		true
	);

	Property::Density density(memoryLayout);

	Information information;
	calculate(
		calculateDensityCallback,
		allIndices,
		memoryLayout,
		density,
		information
	);

	return density;
}

Property::LDOS Greens::calculateLDOS(
	vector<Index> patterns
){
	validatePatternsNumComponents(
		patterns,
		1,
		"PropertyExtractor::Greens::calculateLDOS()"
	);
	validatePatternsSpecifiers(
		patterns,
		{IDX_ALL, IDX_SUM_ALL},
		"PropertyExtractor::Greens::calculateLDOS()"
	);

	IndexTree allIndices = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		false,
		true
	);

	IndexTree memoryLayout = generateIndexTree(
		patterns,
		solver->getModel().getHoppingAmplitudeSet(),
		true,
		true
	);

	Property::LDOS ldos(
		memoryLayout,
		solver->getGreensFunction().getLowerBound(),
		solver->getGreensFunction().getUpperBound(),
		solver->getGreensFunction().getResolution()
	);

	Information information;
	calculate(
		calculateLDOSCallback,
		allIndices,
		memoryLayout,
		ldos,
		information
	);

	return ldos;
}

void Greens::calculateDensityCallback(
	PropertyExtractor *cb_this,
	Property::Property &property,
	const Index &index,
	int offset,
	Information &information
){
	Greens *propertyExtractor = (Greens*)cb_this;
	Property::Density &density = (Property::Density&)property;
	vector<double> &data = density.getDataRW();

	const Property::GreensFunction &greensFunction
		= propertyExtractor->solver->getGreensFunction();

	Statistics statistics = propertyExtractor->solver->getModel().getStatistics();

	switch(greensFunction.getType()){
	case Property::GreensFunction::Type::Retarded:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int e = 0; e < energyResolution; e++){
			double E = lowerBound + e*dE;

			double weight;
			if(statistics == Statistics::FermiDirac){
				weight = Functions::fermiDiracDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel(
					).getTemperature()
				);
			}
			else{
				weight = Functions::boseEinsteinDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel().getTemperature()
				);
			}

			data[offset] += -weight*imag(
				greensFunction({index, index}, e)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Advanced:
	case Property::GreensFunction::Type::NonPrincipal:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int e = 0; e < energyResolution; e++){
			double E = lowerBound + e*dE;

			double weight;
			if(statistics == Statistics::FermiDirac){
				weight = Functions::fermiDiracDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel().getTemperature()
				);
			}
			else{
				weight = Functions::boseEinsteinDistribution(
					E,
					propertyExtractor->solver->getModel(
					).getChemicalPotential(),
					propertyExtractor->solver->getModel().getTemperature()
				);
			}

			data[offset] += weight*imag(
				greensFunction({index, index}, e)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Matsubara:
	{
		for(
			unsigned int e = 0;
			e < greensFunction.getNumMatsubaraEnergies();
			e++
		){
			data[offset] += real(greensFunction({index, index}, e));
		}

		data[offset]
			*= greensFunction.getFundamentalMatsubaraEnergy()/M_PI;

		data[offset] += 1/2.;

		break;
	}
	default:
		TBTKExit(
			"PropertyExtractor::Greens::calculateDensityCallback()",
			"Only calculation of the Density from the Retarded,"
			<< " Advanced, and NonPrincipal Green's function"
			<< " is supported yet.",
			""
		);
	}
}

void Greens::calculateLDOSCallback(
	PropertyExtractor *cb_this,
	Property::Property &property,
	const Index &index,
	int offset,
	Information &information
){
	Greens *propertyExtractor = (Greens*)cb_this;
	Property::LDOS &ldos = (Property::LDOS&)property;
	vector<double> &data = ldos.getDataRW();

	const Property::GreensFunction &greensFunction
		= propertyExtractor->solver->getGreensFunction();

	switch(greensFunction.getType()){
	case Property::GreensFunction::Type::Retarded:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int n = 0; n < energyResolution; n++){
			data[offset + n] -= imag(
				greensFunction({index, index}, n)
			)/M_PI*dE;
		}

		break;
	}
	case Property::GreensFunction::Type::Advanced:
	case Property::GreensFunction::Type::NonPrincipal:
	{
		double lowerBound = greensFunction.getLowerBound();
		double upperBound = greensFunction.getUpperBound();
		int energyResolution = greensFunction.getResolution();

		const double dE = (upperBound - lowerBound)/energyResolution;
		for(int n = 0; n < energyResolution; n++){
			data[offset + n] += imag(
				greensFunction({index, index}, n)
			)/M_PI*dE;
		}

		break;
	}
	default:
		TBTKExit(
			"PropertyExtractor::Greens::calculateDensityCallback()",
			"Only calculation of the Density from the Retarded,"
			<< " Advanced, and NonPrincipal Green's function"
			<< " is supported yet.",
			""
		);
	}
}

};	//End of namespace PropertyExtractor
};	//End of namespace TBTK
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "SysMenuQuick.h"
#include "ui_SysMenuQuick.h"

#include "../../LSession.h"
#include <LuminaX11.h>

LSysMenuQuick::LSysMenuQuick(QWidget *parent) : QWidget(parent), ui(new Ui::LSysMenuQuick){
  ui->setupUi(this);
  settings = new QSettings("panel-plugins","systemdashboard");
  //Now reset the initial saved settings (if any)
  LOS::setScreenBrightness( settings->value("screenbrightness",100).toInt() ); //default to 100%
  LOS::setAudioVolume( settings->value("audiovolume", 100).toInt() ); //default to 100%
  //Now setup the connections
  connect(ui->slider_volume, SIGNAL(valueChanged(int)), this, SLOT(volSliderChanged()) );
  connect(ui->slider_brightness, SIGNAL(valueChanged(int)), this, SLOT(brightSliderChanged()) );
  connect(ui->tool_wk_prev, SIGNAL(clicked()), this, SLOT(prevWorkspace()) );
  connect(ui->tool_wk_next, SIGNAL(clicked()), this, SLOT(nextWorkspace()) );
  connect(ui->tool_logout, SIGNAL(clicked()), this, SLOT(startLogout()) );
  connect(ui->tool_vol_mixer, SIGNAL(clicked()), this, SLOT(startMixer()) );
  //And setup the default icons
  ui->label_bright_icon->setPixmap( LXDG::findIcon("preferences-system-power-management","").pixmap(ui->label_bright_icon->maximumSize()) );
  ui->tool_wk_prev->setIcon( LXDG::findIcon("go-previous-view",""));
  ui->tool_wk_next->setIcon( LXDG::findIcon("go-next-view","") );
  ui->tool_logout->setIcon( LXDG::findIcon("system-log-out","") );
}

LSysMenuQuick::~LSysMenuQuick(){

}

void LSysMenuQuick::UpdateMenu(){
  //Audio Volume
  int val = LOS::audioVolume();
  QIcon ico;
  if(val > 66){ ico= LXDG::findIcon("audio-volume-high",""); }
  else if(val > 33){ ico= LXDG::findIcon("audio-volume-medium",""); }
  else if(val > 0){ ico= LXDG::findIcon("audio-volume-low",""); }
  else{ ico= LXDG::findIcon("audio-volume-muted",""); }
  bool hasMixer = LOS::hasMixerUtility();
  ui->label_vol_icon->setVisible(!hasMixer);
  ui->tool_vol_mixer->setVisible(hasMixer);
  if(!hasMixer){ ui->label_vol_icon->setPixmap( ico.pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->tool_vol_mixer->setIcon(ico); }
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText(txt);
  if(ui->slider_volume->value()!= val){ ui->slider_volume->setValue(val); }
  //Screen Brightness
  val = LOS::ScreenBrightness();
  txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_bright_text->setText(txt);
  if(ui->slider_brightness->value()!=val){ ui->slider_brightness->setValue(val); }
  //Battery Status
  if(LOS::hasBattery()){
    ui->group_battery->setVisible(true);
    val = LOS::batteryCharge();
    if(LOS::batteryIsCharging()){
      if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), tr("connected")) );
    }else{
      if(val < 1){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-missing","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-100","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), getRemainingTime()) );
    }
  }else{
    ui->group_battery->setVisible(false);
  }
  //Workspace
  val = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  ui->group_workspace->setVisible(val>=0 && tot>1);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(val+1), QString::number(tot)) );
}

void LSysMenuQuick::volSliderChanged(){
  int val = ui->slider_volume->value();
  LOS::setAudioVolume(val);
  settings->setValue("audiovolume",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText( txt );
  if(val > 66){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-high","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 33){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-medium","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 0){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-low","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-muted","").pixmap(ui->label_vol_icon->maximumSize()) ); }
}

void LSysMenuQuick::startMixer(){
  emit CloseMenu();
  LOS::startMixerUtility();
}

void LSysMenuQuick::brightSliderChanged(){
  int val = ui->slider_brightness->value();
  LOS::setScreenBrightness(val);
  settings->setValue("screenbrightness",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_bright_text->setText( txt );
}

void LSysMenuQuick::nextWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur++;
  if(cur>=tot){ cur = 0; } //back to beginning
  LX11::SetCurrentDesktop(cur);
ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

void LSysMenuQuick::prevWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur--;
  if(cur<0){ cur = tot-1; } //back to last
  LX11::SetCurrentDesktop(cur);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

QString LSysMenuQuick::getRemainingTime(){
  int secs = LOS::batterySecondsLeft();
  if(secs < 0){ return "??"; }
  QString rem; //remaining
  if(secs > 3600){
    int hours = secs/3600;
    rem.append( QString::number(hours)+"h ");
    secs = secs - (hours*3600);
  }
  if(secs > 60){
    int min = secs/60;
    rem.append( QString::number(min)+"m ");
    secs = secs - (min*60);
  }
  if(secs > 0){
    rem.append( QString::number(secs)+"s");
  }else{
    rem.append( "0s" );
  }
  return rem;
}

void LSysMenuQuick::startLogout(){
  emit CloseMenu();
  LSession::handle()->systemWindow();
}
<commit_msg>Oops, make sure that if brightness controls are not available, that the system dashboard hides that control option.<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "SysMenuQuick.h"
#include "ui_SysMenuQuick.h"

#include "../../LSession.h"
#include <LuminaX11.h>

LSysMenuQuick::LSysMenuQuick(QWidget *parent) : QWidget(parent), ui(new Ui::LSysMenuQuick){
  ui->setupUi(this);
  settings = new QSettings("panel-plugins","systemdashboard");
  //Now reset the initial saved settings (if any)
  LOS::setScreenBrightness( settings->value("screenbrightness",100).toInt() ); //default to 100%
  LOS::setAudioVolume( settings->value("audiovolume", 100).toInt() ); //default to 100%
  //Now setup the connections
  connect(ui->slider_volume, SIGNAL(valueChanged(int)), this, SLOT(volSliderChanged()) );
  connect(ui->slider_brightness, SIGNAL(valueChanged(int)), this, SLOT(brightSliderChanged()) );
  connect(ui->tool_wk_prev, SIGNAL(clicked()), this, SLOT(prevWorkspace()) );
  connect(ui->tool_wk_next, SIGNAL(clicked()), this, SLOT(nextWorkspace()) );
  connect(ui->tool_logout, SIGNAL(clicked()), this, SLOT(startLogout()) );
  connect(ui->tool_vol_mixer, SIGNAL(clicked()), this, SLOT(startMixer()) );
  //And setup the default icons
  ui->label_bright_icon->setPixmap( LXDG::findIcon("preferences-system-power-management","").pixmap(ui->label_bright_icon->maximumSize()) );
  ui->tool_wk_prev->setIcon( LXDG::findIcon("go-previous-view",""));
  ui->tool_wk_next->setIcon( LXDG::findIcon("go-next-view","") );
  ui->tool_logout->setIcon( LXDG::findIcon("system-log-out","") );
}

LSysMenuQuick::~LSysMenuQuick(){

}

void LSysMenuQuick::UpdateMenu(){
  //Audio Volume
  int val = LOS::audioVolume();
  QIcon ico;
  if(val > 66){ ico= LXDG::findIcon("audio-volume-high",""); }
  else if(val > 33){ ico= LXDG::findIcon("audio-volume-medium",""); }
  else if(val > 0){ ico= LXDG::findIcon("audio-volume-low",""); }
  else{ ico= LXDG::findIcon("audio-volume-muted",""); }
  bool hasMixer = LOS::hasMixerUtility();
  ui->label_vol_icon->setVisible(!hasMixer);
  ui->tool_vol_mixer->setVisible(hasMixer);
  if(!hasMixer){ ui->label_vol_icon->setPixmap( ico.pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->tool_vol_mixer->setIcon(ico); }
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText(txt);
  if(ui->slider_volume->value()!= val){ ui->slider_volume->setValue(val); }
  //Screen Brightness
  val = LOS::ScreenBrightness();
  if(val < 0){
    //No brightness control - hide it
    ui->group_brightness->setVisible(false);
  }else{
    ui->group_brightness->setVisible(true);
    txt = QString::number(val)+"%";
    if(val<100){ txt.prepend(" "); } //make sure no widget resizing
    ui->label_bright_text->setText(txt);
    if(ui->slider_brightness->value()!=val){ ui->slider_brightness->setValue(val); }
  }
  //Battery Status
  if(LOS::hasBattery()){
    ui->group_battery->setVisible(true);
    val = LOS::batteryCharge();
    if(LOS::batteryIsCharging()){
      if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), tr("connected")) );
    }else{
      if(val < 1){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-missing","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-100","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), getRemainingTime()) );
    }
  }else{
    ui->group_battery->setVisible(false);
  }
  //Workspace
  val = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  ui->group_workspace->setVisible(val>=0 && tot>1);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(val+1), QString::number(tot)) );
}

void LSysMenuQuick::volSliderChanged(){
  int val = ui->slider_volume->value();
  LOS::setAudioVolume(val);
  settings->setValue("audiovolume",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText( txt );
  if(val > 66){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-high","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 33){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-medium","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 0){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-low","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-muted","").pixmap(ui->label_vol_icon->maximumSize()) ); }
}

void LSysMenuQuick::startMixer(){
  emit CloseMenu();
  LOS::startMixerUtility();
}

void LSysMenuQuick::brightSliderChanged(){
  int val = ui->slider_brightness->value();
  LOS::setScreenBrightness(val);
  settings->setValue("screenbrightness",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_bright_text->setText( txt );
}

void LSysMenuQuick::nextWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur++;
  if(cur>=tot){ cur = 0; } //back to beginning
  LX11::SetCurrentDesktop(cur);
ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

void LSysMenuQuick::prevWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur--;
  if(cur<0){ cur = tot-1; } //back to last
  LX11::SetCurrentDesktop(cur);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

QString LSysMenuQuick::getRemainingTime(){
  int secs = LOS::batterySecondsLeft();
  if(secs < 0){ return "??"; }
  QString rem; //remaining
  if(secs > 3600){
    int hours = secs/3600;
    rem.append( QString::number(hours)+"h ");
    secs = secs - (hours*3600);
  }
  if(secs > 60){
    int min = secs/60;
    rem.append( QString::number(min)+"m ");
    secs = secs - (min*60);
  }
  if(secs > 0){
    rem.append( QString::number(secs)+"s");
  }else{
    rem.append( "0s" );
  }
  return rem;
}

void LSysMenuQuick::startLogout(){
  emit CloseMenu();
  LSession::handle()->systemWindow();
}
<|endoftext|>


<commit_before>// RUN: %clang -target x86_64-unknown-unknown -fverbose-asm -g -O0 -S %s -o - | FileCheck %s
// <rdar://problem/12566646>

class A {
  int x[];
};
A a;

// CHECK:      Abbrev [3] 0x2d:0x3 DW_TAG_base_type
// CHECK-NEXT:   DW_AT_byte_size
// CHECK-NEXT:     DW_AT_encoding
// CHECK-NEXT:   Abbrev [4] 0x30:0xb DW_TAG_array_type
// CHECK-NEXT:     DW_AT_type
// CHECK-NEXT:     Abbrev [5] 0x35:0x5 DW_TAG_subrange_type
// CHECK-NEXT:       DW_AT_type
// CHECK-NEXT:   End Of Children Mark
<commit_msg>Don't test for ASM output but for IR output.<commit_after>// RUN: %clang -target x86_64-unknown-unknown -fverbose-asm -g -O0 -S -emit-llvm %s -o - | FileCheck %s
// <rdar://problem/12566646>

class A {
  int x[];
};
A a;

// CHECK: !9 = metadata !{i32 {{.*}}, metadata {{.*}}, metadata !"x", metadata {{.*}}, i32 5, i64 0, i64 0, i64 0, i32 1, metadata [[ARRAY_TYPE:.*]]} ; [ DW_TAG_member ]
// CHECK: [[ARRAY_TYPE]] = metadata !{i32 {{.*}}, null, metadata !"", null, i32 0, i64 0, i64 32, i32 0, i32 0, metadata [[BASE_TYPE:.*]], metadata [[ELEM_TYPE:.*]], i32 0, i32 0} ; [ DW_TAG_array_type ]
// CHECK: [[BASE_TYPE]] = metadata !{i32 {{.*}}, null, metadata !"int", null, i32 0, i64 32, i64 32, i64 0, i32 0, i32 5} ; [ DW_TAG_base_type ]
// CHECK: [[ELEM_TYPE]] = metadata !{metadata [[SUBRANGE:.*]]}
// CHECK: [[SUBRANGE]] = metadata !{i32 786465, i64 1, i64 0, i64 -1} ; [ DW_TAG_subrange_type ] [1, 0]
<|endoftext|>


<commit_before>/*!
 * @file poa.cpp
 *
 * @brief Poa source file which encapsulates the implementation
 */

#include <stdlib.h>
#include <stdint.h>
#include <algorithm>

#include "graph.hpp"
#include "spoa.hpp"

void prepare_indices(std::vector<uint32_t>& dst, const std::vector<std::string>& sequences, bool sorted) {
    dst.resize(sequences.size());
    std::iota(dst.begin(), dst.end(), static_cast<uint32_t>(0));

    if (sorted) {
        std::sort(dst.begin(), dst.end(),
            [&](uint32_t lhs, uint32_t rhs) {
                return sequences[lhs].size() > sequences[rhs].size();
            }
        );
    }
}

namespace SPOA {

std::shared_ptr<Graph> construct_partial_order_graph(const std::vector<std::string>& sequences,
    AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    std::shared_ptr<Graph> graph = createGraph(sequences[indices.front()]);

    for (uint32_t i = 1; i < sequences.size(); ++i) {
        auto alignment = Alignment::createAlignment(sequences[indices[i]], graph, params);
        alignment->align_sequence_to_graph();
        graph->add_alignment(std::move(alignment), sequences[indices[i]]);
    }

    return graph;
}

std::shared_ptr<Graph> construct_partial_order_graph(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    std::shared_ptr<Graph> graph = createGraph(sequences[indices.front()], qualities[indices.front()]);

    for (uint32_t i = 1; i < sequences.size(); ++i) {
        auto alignment = Alignment::createAlignment(sequences[indices[i]], graph, params);
        alignment->align_sequence_to_graph();
        graph->add_alignment(std::move(alignment), sequences[indices[i]], qualities[indices[i]]);
    }

    return graph;
}

std::shared_ptr<Graph> construct_partial_order_graph(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, const std::vector<uint32_t>& begin_positions,
    const std::vector<uint32_t>& end_positions, AlignmentParams params) {

    std::shared_ptr<Graph> graph = createGraph(sequences.front(), qualities.front());
    uint32_t offset = 0.01 * sequences.front().size();
    for (uint32_t i = 1; i < sequences.size(); ++i) {
        bool adjust = false;
        std::vector<int32_t> mapping;
        std::shared_ptr<Graph> subgraph = nullptr;
        if (begin_positions[i] < offset && end_positions[i] > sequences.front().size() - offset) {
            subgraph = graph;
        } else {
            subgraph = graph->subgraph(begin_positions[i], end_positions[i], mapping);
            adjust = true;
        }

        auto alignment = Alignment::createAlignment(sequences[i], subgraph, params);
        alignment->align_sequence_to_graph();
        if (adjust) alignment->adjust_node_ids(mapping);

        graph->add_alignment(std::move(alignment), sequences[i], qualities[i]);
    }

    return graph;
}

std::string generate_consensus(const std::vector<std::string>& sequences,
    AlignmentParams params, bool sorted) {

    auto graph = construct_partial_order_graph(sequences, params, sorted);
    return graph->generate_consensus();
}

std::string generate_consensus(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, AlignmentParams params, bool sorted) {

    auto graph = construct_partial_order_graph(sequences, qualities, params, sorted);
    return graph->generate_consensus();
}

std::string generate_consensus(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, const std::vector<uint32_t>& begin_positions,
    const std::vector<uint32_t>& end_positions, AlignmentParams params) {

    auto graph = construct_partial_order_graph(sequences, qualities, begin_positions,
        end_positions, params);
    return graph->generate_consensus();
}

void generate_msa(std::vector<std::string>& dst, const std::vector<std::string>& sequences,
    AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    auto graph = construct_partial_order_graph(sequences, params, sorted);
    graph->generate_msa(dst);
    graph->check_msa(dst, sequences, indices);
}

void generate_msa(std::vector<std::string>& dst, const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    auto graph = construct_partial_order_graph(sequences, qualities, params, sorted);
    graph->generate_msa(dst);
    graph->check_msa(dst, sequences, indices);
}

}
<commit_msg>Added missing header<commit_after>/*!
 * @file poa.cpp
 *
 * @brief Poa source file which encapsulates the implementation
 */

#include <stdlib.h>
#include <stdint.h>
#include <algorithm>
#include <numeric>

#include "graph.hpp"
#include "spoa.hpp"

void prepare_indices(std::vector<uint32_t>& dst, const std::vector<std::string>& sequences, bool sorted) {
    dst.resize(sequences.size());
    std::iota(dst.begin(), dst.end(), static_cast<uint32_t>(0));

    if (sorted) {
        std::sort(dst.begin(), dst.end(),
            [&](uint32_t lhs, uint32_t rhs) {
                return sequences[lhs].size() > sequences[rhs].size();
            }
        );
    }
}

namespace SPOA {

std::shared_ptr<Graph> construct_partial_order_graph(const std::vector<std::string>& sequences,
    AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    std::shared_ptr<Graph> graph = createGraph(sequences[indices.front()]);

    for (uint32_t i = 1; i < sequences.size(); ++i) {
        auto alignment = Alignment::createAlignment(sequences[indices[i]], graph, params);
        alignment->align_sequence_to_graph();
        graph->add_alignment(std::move(alignment), sequences[indices[i]]);
    }

    return graph;
}

std::shared_ptr<Graph> construct_partial_order_graph(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    std::shared_ptr<Graph> graph = createGraph(sequences[indices.front()], qualities[indices.front()]);

    for (uint32_t i = 1; i < sequences.size(); ++i) {
        auto alignment = Alignment::createAlignment(sequences[indices[i]], graph, params);
        alignment->align_sequence_to_graph();
        graph->add_alignment(std::move(alignment), sequences[indices[i]], qualities[indices[i]]);
    }

    return graph;
}

std::shared_ptr<Graph> construct_partial_order_graph(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, const std::vector<uint32_t>& begin_positions,
    const std::vector<uint32_t>& end_positions, AlignmentParams params) {

    std::shared_ptr<Graph> graph = createGraph(sequences.front(), qualities.front());
    uint32_t offset = 0.01 * sequences.front().size();
    for (uint32_t i = 1; i < sequences.size(); ++i) {
        bool adjust = false;
        std::vector<int32_t> mapping;
        std::shared_ptr<Graph> subgraph = nullptr;
        if (begin_positions[i] < offset && end_positions[i] > sequences.front().size() - offset) {
            subgraph = graph;
        } else {
            subgraph = graph->subgraph(begin_positions[i], end_positions[i], mapping);
            adjust = true;
        }

        auto alignment = Alignment::createAlignment(sequences[i], subgraph, params);
        alignment->align_sequence_to_graph();
        if (adjust) alignment->adjust_node_ids(mapping);

        graph->add_alignment(std::move(alignment), sequences[i], qualities[i]);
    }

    return graph;
}

std::string generate_consensus(const std::vector<std::string>& sequences,
    AlignmentParams params, bool sorted) {

    auto graph = construct_partial_order_graph(sequences, params, sorted);
    return graph->generate_consensus();
}

std::string generate_consensus(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, AlignmentParams params, bool sorted) {

    auto graph = construct_partial_order_graph(sequences, qualities, params, sorted);
    return graph->generate_consensus();
}

std::string generate_consensus(const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, const std::vector<uint32_t>& begin_positions,
    const std::vector<uint32_t>& end_positions, AlignmentParams params) {

    auto graph = construct_partial_order_graph(sequences, qualities, begin_positions,
        end_positions, params);
    return graph->generate_consensus();
}

void generate_msa(std::vector<std::string>& dst, const std::vector<std::string>& sequences,
    AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    auto graph = construct_partial_order_graph(sequences, params, sorted);
    graph->generate_msa(dst);
    graph->check_msa(dst, sequences, indices);
}

void generate_msa(std::vector<std::string>& dst, const std::vector<std::string>& sequences,
    const std::vector<std::string>& qualities, AlignmentParams params, bool sorted) {

    std::vector<uint32_t> indices;
    prepare_indices(indices, sequences, sorted);

    auto graph = construct_partial_order_graph(sequences, qualities, params, sorted);
    graph->generate_msa(dst);
    graph->check_msa(dst, sequences, indices);
}

}
<|endoftext|>


<commit_before>// State.cc
//
// Description:
// Implementation of the State class
//
// Author(s):
// Clancy Rowley
//
// Date: 1 Sep 2008
//
// $Revision$
// $LastChangedDate$
// $LastChangedBy$
// $HeadURL$

#include "State.h"
#include <string>
#include <stdio.h>

using namespace ibpm;

namespace ibpm {

State::State() {
    timestep = 0;
    time = 0.;
}

State::State(const Grid& grid, int numPoints ) {
    timestep = 0;
    time = 0.;
    resize( grid, numPoints );
}

void State::resize( const Grid& grid, int numPoints ) {
    q.resize( grid );
    omega.resize( grid );
    f.resize( numPoints );
}

State::State( string filename ) {
    timestep = 0;
    time = 0.;
    load( filename );
}

State::~State() {}

// Routine for computing X & Y forces
// Note that f is actually a body force (force per unit mass), so the net
// force is the integral over the domain.  By a property of the discrete
// delta function, this equals a sum of the BoundaryVector values times dx^2
void State::computeNetForce( double& xforce, double& yforce) const {
    xforce = 0;
    yforce = 0;
    for( int i=0; i<f.getNumPoints(); i++ ) {
        xforce += f(X,i);
        yforce += f(Y,i);
    }
    double dx2 = omega.Dx() * omega.Dx();
    xforce *= dx2;
    yforce *= dx2;
}

bool State::load(const std::string& filename) {

    cerr << "Reading restart file " << filename << "..." << flush;
    FILE* fp = fopen( filename.c_str(), "rb" );
    if ( fp == NULL ) return false;

    // read Grid info
    int nx;
    int ny;
    int ngrid;
    double dx;
    double x0;
    double y0;

    fread( &nx, sizeof( int ), 1, fp );
    fread( &ny, sizeof( int ), 1, fp );
    fread( &ngrid, sizeof( int ), 1, fp );
    fread( &dx, sizeof( double ), 1, fp );
    fread( &x0, sizeof( double ), 1, fp );
    fread( &y0, sizeof( double ), 1, fp );

    int numPoints;
    // read Geometry info
    fread( &numPoints, sizeof( int ), 1, fp );

    // check that Grid and Geometry in file match those expected
    bool success = true;
    if ( nx != q.Nx() ||
        ny != q.Ny() ||
        ngrid != q.Ngrid() ||
        dx != q.Dx() ||
        x0 != q.getXEdge(0,0) ||
        y0 != q.getYEdge(0,0) ||
        numPoints != f.getNumPoints() ) {

        // If old grid was previously allocated, print a warning and set
        // the return value to false
        if ( q.Nx() > 0 ) {
            cerr << "Warning: grids do not match.  Resizing grid." << endl;
            success = false;
        }
        Grid newgrid( nx, ny, 1, dx * nx, x0, y0 );
        resize( newgrid, numPoints );
    }

    // read Flux q
    Flux::index qind;
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for ( qind = q.begin(); qind != q.end(); ++qind ) {
            success = success && fread( &( q(lev,qind) ), sizeof( double ), 1, fp );
        }
    }

    // read Scalar omega
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for (int i=1; i<nx; ++i ) {
            for ( int j=1; j<ny; ++j ) {
                success = success && fread( &( omega(lev,i,j) ), sizeof( double ), 1, fp );
            }
        }
    }

    // read BoundaryVector f
    for ( int i=0; i < numPoints; ++i ) {
        success = success && fread( &( f(X,i) ), sizeof( double ), 1, fp );
        success = success && fread( &( f(Y,i) ), sizeof( double ), 1, fp );
    }

    // read timestep and time
    success = success && fread( &timestep, sizeof(int), 1, fp );
    success = success && fread( &time, sizeof(double), 1, fp );

    // close file
    fclose( fp );
    cerr << "done" << endl;
    return success;
}

bool State::save(std::string filename) const {
    cerr << "Writing restart file " << filename << "..." << flush;
    // open file
    FILE* fp = fopen( filename.c_str(), "wb" );
    if ( fp == NULL ) return false;

    // write Grid info
    const Grid& grid = q.getGrid();
    int nx = grid.Nx();
    int ny = grid.Ny();
    int ngrid = grid.Ngrid();
    double dx = grid.Dx();
    double x0 = grid.getXEdge(0,0);
    double y0 = grid.getYEdge(0,0);

    fwrite( &nx, sizeof( int ), 1, fp );
    fwrite( &ny, sizeof( int ), 1, fp );
    fwrite( &ngrid, sizeof( int ), 1, fp );
    fwrite( &dx, sizeof( double ), 1, fp );
    fwrite( &x0, sizeof( double ), 1, fp );
    fwrite( &y0, sizeof( double ), 1, fp );

    // write Geometry info
    int numPoints = f.getNumPoints();
    fwrite( &numPoints, sizeof( int ), 1, fp );

    // write Flux q
    Flux::index qind;
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for ( qind = q.begin(); qind != q.end(); ++qind ) {
            double qq = q(lev,qind);
            fwrite( &qq, sizeof( double ), 1, fp );
        }
    }

    // write Scalar omega
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for (int i=1; i<nx; ++i ) {
            for ( int j=1; j<ny; ++j ) {
                double g = omega(lev,i,j);
                fwrite( &g, sizeof( double ), 1, fp );
            }
        }
    }

    // write BoundaryVector f
    for ( int i=0; i < numPoints; ++i ) {
        double fx = f(X,i);
        double fy = f(Y,i);
        fwrite( &fx, sizeof( double ), 1, fp );
        fwrite( &fy, sizeof( double ), 1, fp );
    }

    // write timestep and time
    fwrite( &timestep, sizeof(int), 1, fp );
    fwrite( &time, sizeof(double), 1, fp );

    // close file
    fclose( fp );
    cerr << "done" << endl;
    return true;
}

} // namespace ibpm
<commit_msg>a bug fixed in State::load(): Grid newgrid(nx, ny, 1, ...) replaced by Grid newgrid(nx, ny, ngrid))<commit_after>// State.cc
//
// Description:
// Implementation of the State class
//
// Author(s):
// Clancy Rowley
//
// Date: 1 Sep 2008
//
// $Revision$
// $LastChangedDate$
// $LastChangedBy$
// $HeadURL$

#include "State.h"
#include <string>
#include <stdio.h>

using namespace ibpm;

namespace ibpm {

State::State() {
    timestep = 0;
    time = 0.;
}

State::State(const Grid& grid, int numPoints ) {
    timestep = 0;
    time = 0.;
    resize( grid, numPoints );
}

void State::resize( const Grid& grid, int numPoints ) {
    q.resize( grid );
    omega.resize( grid );
    f.resize( numPoints );
}

State::State( string filename ) {
    timestep = 0;
    time = 0.;
    load( filename );
}

State::~State() {}

// Routine for computing X & Y forces
// Note that f is actually a body force (force per unit mass), so the net
// force is the integral over the domain.  By a property of the discrete
// delta function, this equals a sum of the BoundaryVector values times dx^2
void State::computeNetForce( double& xforce, double& yforce) const {
    xforce = 0;
    yforce = 0;
    for( int i=0; i<f.getNumPoints(); i++ ) {
        xforce += f(X,i);
        yforce += f(Y,i);
    }
    double dx2 = omega.Dx() * omega.Dx();
    xforce *= dx2;
    yforce *= dx2;
}

bool State::load(const std::string& filename) {

    cerr << "Reading restart file " << filename << "..." << flush;
    FILE* fp = fopen( filename.c_str(), "rb" );
    if ( fp == NULL ) return false;

    // read Grid info
    int nx;
    int ny;
    int ngrid;
    double dx;
    double x0;
    double y0;

    fread( &nx, sizeof( int ), 1, fp );
    fread( &ny, sizeof( int ), 1, fp );
    fread( &ngrid, sizeof( int ), 1, fp );
    fread( &dx, sizeof( double ), 1, fp );
    fread( &x0, sizeof( double ), 1, fp );
    fread( &y0, sizeof( double ), 1, fp );

    int numPoints;
    // read Geometry info
    fread( &numPoints, sizeof( int ), 1, fp );

    // check that Grid and Geometry in file match those expected
    bool success = true;
    if ( nx != q.Nx() ||
        ny != q.Ny() ||
        ngrid != q.Ngrid() ||
        dx != q.Dx() ||
        x0 != q.getXEdge(0,0) ||
        y0 != q.getYEdge(0,0) ||
        numPoints != f.getNumPoints() ) {

        // If old grid was previously allocated, print a warning and set
        // the return value to false
        if ( q.Nx() > 0 ) {
            cerr << "Warning: grids do not match.  Resizing grid." << endl;
            success = false;
        }
        Grid newgrid( nx, ny, ngrid, dx * nx, x0, y0 );
        resize( newgrid, numPoints );
    }

    // read Flux q
    Flux::index qind;
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for ( qind = q.begin(); qind != q.end(); ++qind ) {
            success = success && fread( &( q(lev,qind) ), sizeof( double ), 1, fp );
        }
    }

    // read Scalar omega
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for (int i=1; i<nx; ++i ) {
            for ( int j=1; j<ny; ++j ) {
                success = success && fread( &( omega(lev,i,j) ), sizeof( double ), 1, fp );
            }
        }
    }

    // read BoundaryVector f
    for ( int i=0; i < numPoints; ++i ) {
        success = success && fread( &( f(X,i) ), sizeof( double ), 1, fp );
        success = success && fread( &( f(Y,i) ), sizeof( double ), 1, fp );
    }

    // read timestep and time
    success = success && fread( &timestep, sizeof(int), 1, fp );
    success = success && fread( &time, sizeof(double), 1, fp );

    // close file
    fclose( fp );
    cerr << "done" << endl;
    return success;
}

bool State::save(std::string filename) const {
    cerr << "Writing restart file " << filename << "..." << flush;
    // open file
    FILE* fp = fopen( filename.c_str(), "wb" );
    if ( fp == NULL ) return false;

    // write Grid info
    const Grid& grid = q.getGrid();
    int nx = grid.Nx();
    int ny = grid.Ny();
    int ngrid = grid.Ngrid();
    double dx = grid.Dx();
    double x0 = grid.getXEdge(0,0);
    double y0 = grid.getYEdge(0,0);

    fwrite( &nx, sizeof( int ), 1, fp );
    fwrite( &ny, sizeof( int ), 1, fp );
    fwrite( &ngrid, sizeof( int ), 1, fp );
    fwrite( &dx, sizeof( double ), 1, fp );
    fwrite( &x0, sizeof( double ), 1, fp );
    fwrite( &y0, sizeof( double ), 1, fp );

    // write Geometry info
    int numPoints = f.getNumPoints();
    fwrite( &numPoints, sizeof( int ), 1, fp );

    // write Flux q
    Flux::index qind;
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for ( qind = q.begin(); qind != q.end(); ++qind ) {
            double qq = q(lev,qind);
            fwrite( &qq, sizeof( double ), 1, fp );
        }
    }

    // write Scalar omega
    for ( int lev=0; lev < q.Ngrid(); ++lev ) {
        for (int i=1; i<nx; ++i ) {
            for ( int j=1; j<ny; ++j ) {
                double g = omega(lev,i,j);
                fwrite( &g, sizeof( double ), 1, fp );
            }
        }
    }

    // write BoundaryVector f
    for ( int i=0; i < numPoints; ++i ) {
        double fx = f(X,i);
        double fy = f(Y,i);
        fwrite( &fx, sizeof( double ), 1, fp );
        fwrite( &fy, sizeof( double ), 1, fp );
    }

    // write timestep and time
    fwrite( &timestep, sizeof(int), 1, fp );
    fwrite( &time, sizeof(double), 1, fp );

    // close file
    fclose( fp );
    cerr << "done" << endl;
    return true;
}

} // namespace ibpm
<|endoftext|>