Пример #1
0
void EflResources::initCb__( void*         _this
                           , Ecore_Thread* _th )
{
    ASSERT( _this && _th
          , "NULL pointers passed to thread function." );
    EflResources* rh( static_cast< EflResources* >( _this ) );

    std::for_each( init_images__.begin()
                 , init_images__.end()
                 , [&]( std::string const _path )
    {
        Evas_Object* object = evas_object_image_add( rh->window__ );
        evas_object_image_load_size_set( object
                                       , rh->max_width__
                                       , rh->max_height__ );
        evas_object_image_file_set( object
                                  , _path.c_str()
                                  , nullptr );
        CCallbackHandler::evasEventCallback( object
                                           , CALLBACK_IMAGE_PRELOADED
                                           , [=](){ ++( rh->resources_loaded__ );
                                                    rh->signals__[LOADING]->emit(); } );
        rh->preloaded_images__[_path] = object;
        evas_object_image_preload( object
                                 , 0 );
    } );
}
Пример #2
0
  void FlatTabWidget::resizeEvent(QResizeEvent *event)
  {
    QSize s = event->size();


    int handleHeight = m_handle->sizeHint().height();
    int tabHeight = m_tabBar->sizeHint().height();
    int stackHeight = 0;
    if(!m_stack->isHidden())
    {
      stackHeight = s.height() - tabHeight - handleHeight;
    }
    int width = s.width();


    QRect rh(0,0, width, handleHeight);
    m_handle->setGeometry(rh);

    QRect rs(0,handleHeight, s.width(), stackHeight);
    m_stack->setGeometry(rs);

    QRect rt(0,handleHeight + stackHeight, width, tabHeight);
    m_tabBar->setGeometry(rt);

  }
// ######################################################################
Histogram CenterSurroundHistogramSegmenter::smoothAndNormalize
(Histogram h, int numPoints)
{
  // maybe later want to add the weight for each channel
  //(Point2D<int> pt, std::vector<float> &dist, float weight)

  uint sindex = 0; uint eindex = NUM_L_BINS - 1;
  Histogram lHist(h, sindex, eindex);
  sindex = eindex + 1; eindex += NUM_A_BINS;
  Histogram aHist(h, sindex, eindex);
  sindex = eindex + 1; eindex += NUM_B_BINS;
  Histogram bHist(h, sindex, eindex);
  
  // smooth the histogram individually
  lHist.smooth(itsLKernel);
  aHist.smooth(itsAKernel);
  bHist.smooth(itsBKernel);

  // combine the histograms
  std::vector<Histogram> histograms;
  histograms.push_back(lHist);
  histograms.push_back(aHist);
  histograms.push_back(bHist);
  //Histogram histogram.reset(new Histogram(histograms));
  Histogram rh(histograms);
  
  // normalize with the number of points
  rh.divide(numPoints);

  return rh;
}
//------------------------------------------------------------------------------
void MoleculeElDensSurfaceWidget::SetRenderingStyle( MolekelMolecule::RenderingStyle rs )
{
	ResourceHandler< bool > rh( updatingGUI_, true, false );
    const int i = renderingStyleComboBox_->findData( int( rs ) );
    if( i < 0 ) return;
    renderingStyleComboBox_->setCurrentIndex( i );
}
Пример #5
0
static void record_handler(void *userData, AudioQueueRef inQ,
			   AudioQueueBufferRef inQB,
			   const AudioTimeStamp *inStartTime,
			   UInt32 inNumPackets,
			   const AudioStreamPacketDescription *inPacketDesc)
{
	struct ausrc_st *st = userData;
	unsigned int ptime;
	ausrc_read_h *rh;
	void *arg;
	(void)inStartTime;
	(void)inNumPackets;
	(void)inPacketDesc;

	pthread_mutex_lock(&st->mutex);
	ptime = st->ptime;
	rh  = st->rh;
	arg = st->arg;
	pthread_mutex_unlock(&st->mutex);

	if (!rh)
		return;

	rh(inQB->mAudioData, inQB->mAudioDataByteSize/2, arg);

	AudioQueueEnqueueBuffer(inQ, inQB, 0, NULL);

	/* Force a sleep here, coreaudio's timing is too fast */
#if !TARGET_OS_IPHONE
#define ENCODE_TIME 1000
	usleep((ptime * 1000) - ENCODE_TIME);
#endif
}
//------------------------------------------------------------------------------
void MoleculeElDensSurfaceWidget::SetPosTransparency( double a )
{
	ResourceHandler< bool > rh( updatingGUI_, true, false );
	assert( posTransparencyWidget_ );
	posTransparencyWidget_->setValue( a );
	QSettings s;
	s.setValue( POSITIVE_TRANSPARENCY_KEY, a  );
}
//------------------------------------------------------------------------------
void MoleculeElDensSurfaceWidget::SetNodalTransparency( double a )
{
	ResourceHandler< bool > rh( updatingGUI_, true, false );
	assert( nodTransparencyWidget_ );
	nodTransparencyWidget_->setValue( a );
	QSettings s;
	s.setValue( NODAL_TRANSPARENCY_KEY, a  );
}
//------------------------------------------------------------------------------
void MoleculeElDensSurfaceWidget::SetDMTransparency( double a )
{
	ResourceHandler< bool > rh( updatingGUI_, true, false );
	assert( dmTransparencyWidget_ );
	dmTransparencyWidget_->setValue( a );
	QSettings s;
	s.setValue( DENSITY_MATRIX_TRANSPARENCY_KEY, a  );
}
Пример #9
0
//------------------------------------------------------------------------------
void ImagePlaneProbeWidget::UnselectAll()
{
    ResourceHandler< bool > rh( updatingGUI_, true, false );
    gridDataGroup_->setChecked( false );
    orbitalsGroup_->setChecked( false );
    eldensGroup_->setChecked( false );
    spindensGroup_->setChecked( false );
    mepGroup_->setChecked( false );
}
Пример #10
0
//------------------------------------------------------------------------------
void ImagePlaneProbeWidget::MEPGroupToggledSlot( bool v )
{
    if( updatingGUI_ ) return;
    UnselectAll();
    ResourceHandler< bool > rh( updatingGUI_, true, false );
    mepGroup_->setChecked( v );
    stepSizeSpinBox_->setEnabled( true );
    emit MEPToggled( v );
}
Пример #11
0
ActorStackPool_::ActorStackPool_()
{
	_exit = false;
	_clearWait = false;
	_stackCount = 0;
	_stackTotalSize = 0;
	boost::thread rh(&ActorStackPool_::clearThread, this);
	_clearThread.swap(rh);
}
//------------------------------------------------------------------------------
void MoleculeElDensSurfaceWidget::DensityMatrixToggledSlot( bool  v )
{
    if( updatingGUI_ ) return;
    // enable/disable controls depending on value of checkbox
    ResourceHandler< bool > rh( updatingGUI_, true, false );
    table_->setEnabled( !v && mol_->GetNumberOfOrbitals() );
    signCheckBox_->setEnabled( !v );
    nodalSurfaceCheckBox_->setEnabled( !v );
    emit DensityMatrixToggled( v );
}
Пример #13
0
MASA::navierstokes_4d_compressible_powerlaw<Scalar>::navierstokes_4d_compressible_powerlaw()
{
  this->mmsname   = "navierstokes_4d_compressible_powerlaw";
  this->dimension = 4; // x + y + z + t = 4

  // Register parameters using nsctpl::manufactured_solution::foreach_parameter
  registration_helper<Scalar> rh(this);
  this->foreach_parameter(rh);

  this->init_var();
}
Пример #14
0
void RawTable::appendRows(const atable_ptr_t& rows) {
  type_switch<hyrise_basic_types> ts;
  for(size_t row=0; row < rows->size(); ++row) {
    rawtable::RowHelper rh(_metadata);
    for(size_t column=0; column < _metadata.size(); ++column) {
      type_func tf(rows, rh, column, row);
      ts(rows->typeOfColumn(column), tf);
    }
    std::unique_ptr<byte, void (*)(void *)> data(rh.build(), &std::free);
    appendRow(data.get());
  }
}
Пример #15
0
void
DSI_Simple_Server::invoke (CORBA::ServerRequest_ptr request,
                           TAO_AMH_DSI_Response_Handler * rph)
{
  CORBA::NVList_ptr opList;
  this->orb_->create_list (0, opList);

  request->arguments (opList);

  CORBA::Request_var target_request;

  this->target_->_create_request (0, // ctx
                                  request->operation (),
                                  opList,
                                  0, // result
                                  0, // exception_list,
                                  0, // context_list,
                                  target_request.inout (),
                                  0);

  target_request->_tao_lazy_evaluation (1);

  // Outgoing request must have the same byte order as the incoming one.
  target_request->_tao_byte_order (request->_tao_incoming_byte_order ());

  try
    {
      // Updates the byte order state, if necessary.
      TAO_DII_Reply_Handler_ptr rh_ptr;
      ACE_NEW (rh_ptr, My_DII_Reply_Handler (rph, this->orb_));
      TAO_DII_Reply_Handler_var rh(rh_ptr);
      target_request->sendc (rh.in());
    }
  catch (const CORBA::UNKNOWN&)
    {
      // Outgoing reply must have the same byte order as the incoming one.
      request->_tao_reply_byte_order (target_request->_tao_byte_order ());

      request->gateway_exception_reply (
          target_request->raw_user_exception ());
      return;
    }

  // Outgoing reply must have the same byte order as the incoming one.
  request->_tao_reply_byte_order (target_request->_tao_byte_order ());

  if (ACE_OS::strcmp ("shutdown", request->operation ()) == 0)
    {
      this->orb_->shutdown (0);
    }
}
Пример #16
0
void
DSI_Simple_Server::_dispatch (TAO_ServerRequest &request, TAO::Portable_Server::Servant_Upcall *)
{
  // No need to do any of this if the client isn't waiting.
  if (request.response_expected ())
    {
      if (!CORBA::is_nil (request.forward_location ()))
        {
          request.init_reply ();
          request.tao_send_reply ();

          // No need to invoke in this case.
          return;
        }
      else if (request.sync_with_server ())
        {
          // The last line before the call to this function
          // was an ACE_CHECK_RETURN, so if we're here, we
          // know there is no exception so far, and that's all
          // a SYNC_WITH_SERVER client request cares about.
          request.send_no_exception_reply ();
        }
    }

  // Create DSI request object.
  CORBA::ServerRequest *dsi_request = 0;
  ACE_NEW (dsi_request,
           CORBA::ServerRequest (request));

  try
    {
      TAO_AMH_DSI_Response_Handler_ptr rh_ptr;
      ACE_NEW (rh_ptr, TAO_AMH_DSI_Response_Handler(request));

      TAO_AMH_DSI_Response_Handler_var rh(rh_ptr);
      rh->init (request, 0);
      // Delegate to user.
      this->invoke (dsi_request, rh.in());
    }
  catch (const CORBA::Exception& ex)

    {
      // Only if the client is waiting.
      if (request.response_expected () && !request.sync_with_server ())
        {
          request.tao_send_reply_exception (ex);
        }
    }

  CORBA::release (dsi_request);
}
/**
 * For definition of this operation, refer to
 *  ttp://www.dmtf.org/download/spec/xmls/CIM_HTTP_Mapping10.htm#SecReferenceNames
 * This operation is used to enumerate the association objects
 * that refer to a particular target CIM Instance.
 *
 * @param resultClass see the reference method.
 * @param objectName see the reference method.
 * @param role see the reference method
 *
 * @returns If successful, the method returns the names of zero or more
 * full CIM Instance paths of Objects meeting the requested criteria.
 * @throws CIMException - as defined for associators method.
 */
void
    CppSimpleAssociatorProviderIFC::referenceNames(const ProviderEnvironmentIFCRef &env,
                                                   CIMObjectPathResultHandlerIFC &result,
                                                   const String &ns,
                                                   const CIMObjectPath &objectName,
                                                   const String &resultClass,
                                                   const String &role)
{

    CIMOMHandleIFCRef lch = env->getCIMOMHandle();
    CIMClass theAssocClass = lch->getClass(ns, resultClass);
    _RHReferenceNames rh(result,ns);
    doReferences(env, rh,ns ,objectName , theAssocClass,"",role, "");
}
Пример #18
0
int main()
{
    std::vector<point>         pts;
    point                      dim(0,0);
    rhomb                      rh(0,0,0,0);
    boost::tuples::tie(dim,rh)=read_points(std::cin,pts);
    boost::multi_array<bool,2> m(boost::extents[dim.x][dim.y]);

    for(point pp(rh.pp-dim.y,dim.y); pp.x<dim.x;) {
        mark(m,pts,pp,1,1);
        ++pp.x;
        mark(m,pts,pp,1,1);
        --pp.y;
    }
    mark(m,pts,point(dim.x,rh.pp-dim.x),1,1);

    for(point pm(rh.pm-1,-1); pm.x<dim.x;) {
        mark(m,pts,pm,1,-1);
        ++pm.x;
        mark(m,pts,pm,1,-1);
        ++pm.y;
    }
    mark(m,pts,point(dim.x,dim.x-rh.pm),1,-1);

    for(point mp(-1,rh.mp-1); mp.y<dim.y;) {
        mark(m,pts,mp,-1,1);
        ++mp.y;
        mark(m,pts,mp,-1,1);
        ++mp.x;
    }
    mark(m,pts,point(dim.y-rh.mp,dim.y),-1,1);

    for(point mm(-1,1-rh.mm); mm.y>=0;) {
        mark(m,pts,mm,-1,-1);
        --mm.y;
        mark(m,pts,mm,-1,-1);
        ++mm.x;
    }
    mark(m,pts,point(-rh.mm,0),-1,-1);

    for(int y=0; y<dim.y; ++y) {
        for(int x=0; x<dim.x; ++x) {
            if(x+y>rh.pp||x-y>rh.pm||-x+y>rh.mp||-x-y>rh.mm||m[x][y])std::cout<<".";
            else       std::cout<<"*";
        }
        std::cout<<"\n";
    }
}
Пример #19
0
  std::shared_ptr<AbstractTable> createRawTable() {
    metadata_vec_t cols({ *ColumnMetadata::metadataFromString("INTEGER", "col1"),
            *ColumnMetadata::metadataFromString("STRING", "col2"),
            *ColumnMetadata::metadataFromString("FLOAT", "col3") });

    auto main = std::make_shared<RawTable>(cols);
    for (size_t i=0; i < 100; ++i) {
      hyrise::storage::rawtable::RowHelper rh(cols);
      rh.set<hyrise_int_t>(0, i);
      rh.set<hyrise_string_t>(1, "MeinNameIstSlimShady" + std::to_string(i));
      rh.set<hyrise_float_t>(2, 1.1*i);
      unsigned char *data = rh.build();
      main->appendRow(data);
      free(data);
    }
    return main;
  }
QoreValue QoreDivideEqualsOperatorNode::evalValueImpl(bool& needs_deref, ExceptionSink* xsink) const {
   ValueEvalRefHolder res(right, xsink);
   if (*xsink)
      return QoreValue();

   // get ptr to current value (lvalue is locked for the scope of the LValueHelper object)
   LValueHelper v(left, xsink);
   if (!v)
      return QoreValue();

   // is either side a number?
   if (res->getType() == NT_NUMBER || v.getType() == NT_NUMBER) {
      // check for divide by zero
      if (res->getAsFloat() == 0.0) {
	 xsink->raiseException("DIVISION-BY-ZERO", "division by zero in arbitrary-precision numeric expression");
	 return QoreValue();
      }
      // FIXME: efficiency
      ReferenceHolder<> rh(res.getReferencedValue(), xsink);
      v.divideEqualsNumber(*rh, "</= operator>");
   }
   // is either side a float?
   else if (res->getType() == NT_FLOAT || v.getType() == NT_FLOAT) {
      double val = res->getAsFloat();
      if (val == 0.0) {
	 xsink->raiseException("DIVISION-BY-ZERO", "division by zero in floating-point expression");
	 return QoreValue();
      }
      return v.divideEqualsFloat(val, "</= operator>");
   }
   else { // do integer divide equals
      int64 val = res->getAsBigInt();
      if (!val) {
	 xsink->raiseException("DIVISION-BY-ZERO", "division by zero in integer expression");
	 return QoreValue();
      }
      // get new value if necessary
      return v.divideEqualsBigInt(val, "</= operator>");
   }

   // reference return value and return
   return ref_rv ? v.getReferencedValue() : QoreValue();
}
  storage::atable_ptr_t createRawTable() {
    metadata_vec_t columns({ *ColumnMetadata::metadataFromString("INTEGER", "col1"),
                             *ColumnMetadata::metadataFromString("STRING", "col2"),
                             *ColumnMetadata::metadataFromString("FLOAT", "col3") });
    auto main = std::make_shared<RawTable<>>(columns);
    storage::rawtable::RowHelper rh(columns);
    unsigned char *data = nullptr;

    for(size_t i=0; i<10; i++) {
      rh.set<storage::hyrise_int_t>(0, i);
      rh.set<storage::hyrise_string_t>(1, "SomeText" + std::to_string(i));
      rh.set<storage::hyrise_float_t>(2, 1.1*i);
      data = rh.build();
      main->appendRow(data);
      free(data);
    }

    return main;
  }
Пример #22
0
std::pair<point,rhomb> read_points(std::istream& is,Sequence& s)
{
    rhomb rh(INT_MIN,INT_MIN,INT_MIN,INT_MIN);
    int   xmax=0;
    s.clear();
    int y=0;
    for(std::string str; std::getline(is,str); ++y) {
        int line_xmax=0;
        for(int x=0; (x=str.find_first_of('*',x))!=std::string::npos; ++x) {
            s.push_back(point(x,y));
            line_xmax=x;
            if( x+y>rh.pp)rh.pp= x+y;
            if( x-y>rh.pm)rh.pm= x-y;
            if(-x+y>rh.mp)rh.mp=-x+y;
            if(-x-y>rh.mm)rh.mm=-x-y;
        }
        if(line_xmax>xmax)xmax=line_xmax;
    }
    return std::make_pair(point(xmax+1,y),rh);
}
Пример #23
0
void
ImR_DSI_Forwarder::_dispatch (TAO_ServerRequest &request,
                              TAO::Portable_Server::Servant_Upcall * /*context */ )
{
  // No need to do any of this if the client isn't waiting.
  if (request.response_expected ())
    {
      if (!CORBA::is_nil (request.forward_location ()))
        {
          request.init_reply ();
          request.tao_send_reply ();

          // No need to invoke in this case.
          return;
        }
    }

  // Create DSI request object.
  CORBA::ServerRequest *dsi_request = 0;
  ACE_NEW (dsi_request,
           CORBA::ServerRequest (request));
  try
    {
      TAO_AMH_DSI_Response_Handler_ptr rhp;
      ACE_NEW (rhp, TAO_AMH_DSI_Response_Handler(request));
      TAO_AMH_DSI_Response_Handler_var rh(rhp);

      rh->init (request, 0);
      // Delegate to user.
      this->invoke (dsi_request, rh.in());
    }
  catch (const CORBA::Exception& ex)
    {
      // Only if the client is waiting.
      if (request.response_expected () && !request.sync_with_server ())
        {
          request.tao_send_reply_exception (ex);
        }
    }
  CORBA::release (dsi_request);
}
/**
 * For definition of this operation, refer to
 * http://www.dmtf.org/download/spec/xmls/CIM_HTTP_Mapping10.htm#SecReferencesMethod
 * This operation is used to enumerate the association objects
 * that refer to a particular target CIM Instance.
 *
 * @param resultClass Defines the association that the objectName object
 * 	should be associated to.  The provider uses this information to
 * 	identify which association must be traversed in case it supports
 * 	more than one association.
 *
 * @param objectName The objectName input parameter defines the target
 * 	CIM Object whose referring Objects are to be returned.  This is an
 * 	Instance name (model path).
 *
 * @param role The role input parameter, if not empty (""), MUST be a
 * 	valid Property name.  It acts as a filter on the returned set of
 * 	Objects by mandating that each returned Object MUST refer to the
 * 	target Object via a Property whose name matches the value of this
 * 	parameter.
 *
 * @param includeQualifiers see the includeQualifiers for associators.
 * @param includeClassOrigin see the includeClassOrigin for associators.
 * @param propertyList see the propertyList for associators
 *
 * @returns If successful, the method returns zero or more CIM Instances
 * 	meeting the requested criteria.
 *
 * @throws CIMException - as defined for the associators method.
 */
void
    CppSimpleAssociatorProviderIFC::references(const ProviderEnvironmentIFCRef
                                               &env, CIMInstanceResultHandlerIFC &result,
                                               const String &ns,
                                               const CIMObjectPath &objectName,
                                               const String &resultClass,
                                               const String &role,
                                               WBEMFlags:: EIncludeQualifiersFlag includeQualifiers,
                                               WBEMFlags:: EIncludeClassOriginFlag includeClassOrigin,
                                               const StringArray *propertyList)
{

    CIMOMHandleIFCRef lch = env->getCIMOMHandle();
    CIMClass theAssocClass = lch->getClass(ns, resultClass,
                                           WBEMFlags::E_NOT_LOCAL_ONLY,
                                           includeQualifiers,
                                           includeClassOrigin);

    _RHReferences rh(result,includeQualifiers ,includeClassOrigin ,propertyList );
    doReferences(env, rh, ns, objectName, theAssocClass, "", role, "");
}
Пример #25
0
//------------------------------------------------------------------------------
void ImagePlaneProbeWidget::TableItemChangedSlot( QTableWidgetItem* i  )
{
    if( updatingGUI_  ) return;
    assert( i );
    const int orbitalIndex = i->data( Qt::UserRole ).toInt();
    if( i->checkState() == Qt::Unchecked ) // checked to unchecked
    {
        selectedOrbital_ = -1;
    }
    else if( i->checkState() == Qt::Checked ) // unchecked to checked
    {
        if( selectedOrbital_ >= 0 ) // if another orbital selected --> unselect
        {
            QTableWidgetItem* si = table_->item( selectedOrbital_, 0 );
            assert( si );
            ResourceHandler< bool > rh( updatingGUI_, true, false );
            si->setCheckState( Qt::Unchecked );
        }
        selectedOrbital_ = orbitalIndex;
    }
    emit OrbitalSelected( selectedOrbital_ );
}
Пример #26
0
 /**
  * @param heights: a vector of integers
  * @return: a integer
  */
 int trapRainWater(vector<int> &heights) {
     // write your code here
     int n=heights.size();
     //lh[i] records the max height left of heights[i]
     vector<int> lh(n,0);
     //rh[i] records the max hegiht right of height[i];
     vector<int> rh(n,0);
     
     for(int i=1; i<n; i++){
         // current lh[i] = height[i-1] or lh[i-1]
         lh[i]=max(heights[i-1],lh[i-1]);
         rh[n-i-1]=max(heights[n-i],rh[n-i]);
     }
     
     int res=0;
     for(int i=0; i<n; i++){
         int h=min(lh[i],rh[i]);
         if(heights[i]<h){
             res+=(h-heights[i]);
         }
     }
     return res;
 }
Пример #27
0
void Http::Request::main()
	throw()
{
	char buf[131072];

	try {
		http_parser_init(&_parser,HTTP_RESPONSE);
		_parser.data = this;

		http_parser_url urlParsed;
		if (http_parser_parse_url(_url.c_str(),_url.length(),0,&urlParsed)) {
			suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL parse error");
			return;
		}
		if (!(urlParsed.field_set & (1 << UF_SCHEMA))) {
			suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL specifies no schema");
			return;
		}

		std::string schema(_url.substr(urlParsed.field_data[UF_SCHEMA].off,urlParsed.field_data[UF_SCHEMA].len));

		if (schema == "file") {
			const std::string filePath(_url.substr(urlParsed.field_data[UF_PATH].off,urlParsed.field_data[UF_PATH].len));

			uint64_t lm = Utils::getLastModified(filePath.c_str());
			if (lm) {
				const std::map<std::string,std::string>::const_iterator ifModSince(_requestHeaders.find("If-Modified-Since"));
				if ((ifModSince != _requestHeaders.end())&&(ifModSince->second.length())) {
					uint64_t t64 = Utils::fromRfc1123(ifModSince->second);
					if ((t64)&&(lm > t64)) {
						suicidalThread = !_handler(this,_arg,_url,304,_responseHeaders,"");
						return;
					}
				}

				if (Utils::readFile(filePath.c_str(),_responseBody)) {
					_responseHeaders["Last-Modified"] = Utils::toRfc1123(lm);
					suicidalThread = !_handler(this,_arg,_url,200,_responseHeaders,_responseBody);
					return;
				}
			}

			suicidalThread = !_handler(this,_arg,_url,404,_responseHeaders,"file not found or not readable");
			return;
		} else if (schema == "http") {
			if (!(urlParsed.field_set & (1 << UF_HOST))) {
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL contains no host");
				return;
			}
			std::string host(_url.substr(urlParsed.field_data[UF_HOST].off,urlParsed.field_data[UF_HOST].len));

			std::list<InetAddress> v4,v6;
			{
				struct addrinfo *res = (struct addrinfo *)0;
				if (!getaddrinfo(host.c_str(),(const char *)0,(const struct addrinfo *)0,&res)) {
					struct addrinfo *p = res;
					do {
						if (p->ai_family == AF_INET)
							v4.push_back(InetAddress(p->ai_addr));
						else if (p->ai_family == AF_INET6)
							v6.push_back(InetAddress(p->ai_addr));
					} while ((p = p->ai_next));
					freeaddrinfo(res);
				}
			}

			std::list<InetAddress> *addrList;
			if (v4.empty()&&v6.empty()) {
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"could not find address for host in URL");
				return;
			} else if (v4.empty()) {
				addrList = &v6;
			} else {
				addrList = &v4;
			}
			InetAddress *addr;
			{
				addrList->sort();
				addrList->unique();
				unsigned int i = 0,k = 0;
				k = Utils::randomInt<unsigned int>() % addrList->size();
				std::list<InetAddress>::iterator a(addrList->begin());
				while (i++ != k) ++a;
				addr = &(*a);
			}

			int remotePort = ((urlParsed.field_set & (1 << UF_PORT))&&(urlParsed.port)) ? (int)urlParsed.port : (int)80;
			if ((remotePort <= 0)||(remotePort > 0xffff)) {
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL port out of range");
				return;
			}
			addr->setPort(remotePort);

			_fd = socket(addr->isV6() ? AF_INET6 : AF_INET,SOCK_STREAM,0);
			if (_fd <= 0) {
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"could not open socket");
				return;
			}

			for(;;) {
				if (connect(_fd,addr->saddr(),addr->saddrLen())) {
					if (errno == EINTR)
						continue;
					::close(_fd); _fd = 0;
					suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"connection failed to remote host");
					return;
				} else break;
			}

			const char *mstr = "GET";
			switch(_method) {
				case HTTP_METHOD_HEAD: mstr = "HEAD"; break;
				default: break;
			}
			int mlen = (int)snprintf(buf,sizeof(buf),"%s %s HTTP/1.1\r\nAccept-Encoding: \r\nHost: %s\r\n",mstr,_url.substr(urlParsed.field_data[UF_PATH].off,urlParsed.field_data[UF_PATH].len).c_str(),host.c_str());
			if (mlen >= (int)sizeof(buf)) {
				::close(_fd); _fd = 0;
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL too long");
				return;
			}
			if (!_sendAll(_fd,buf,mlen)) {
				::close(_fd); _fd = 0;
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"write error");
				return;
			}

			for(std::map<std::string,std::string>::const_iterator rh(_requestHeaders.begin());rh!=_requestHeaders.end();++rh) {
				mlen = (int)snprintf(buf,sizeof(buf),"%s: %s\r\n",rh->first.c_str(),rh->second.c_str());
				if (mlen >= (int)sizeof(buf)) {
					::close(_fd); _fd = 0;
					suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"header too long");
					return;
				}
				if (!_sendAll(_fd,buf,mlen)) {
					::close(_fd); _fd = 0;
					suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"write error");
					return;
				}
			}

			if (!_sendAll(_fd,"\r\n",2)) {
				::close(_fd); _fd = 0;
				suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"write error");
				return;
			}

			_responseStatusCode = 0;
			_messageComplete = false;
			for(;;) {
				mlen = (int)::recv(_fd,buf,sizeof(buf),0);
				if (mlen < 0) {
					if (errno != EINTR)
						break;
					else continue;
				}
				if (((int)http_parser_execute(&_parser,&_http_parser_settings,buf,mlen) != mlen)||(_parser.upgrade)) {
					::close(_fd); _fd = 0;
					suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"invalid HTTP response from server");
					return;
				}
				if (_messageComplete) {
					::close(_fd); _fd = 0;
					suicidalThread = !_handler(this,_arg,_url,_responseStatusCode,_responseHeaders,_responseBody);
					return;
				}
			}

			::close(_fd); _fd = 0;
			suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"empty HTTP response from server");
			return;
		} else {
			suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"only 'file' and 'http' methods are supported");
			return;
		}
	} catch ( ... ) {
		suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"unexpected exception retrieving URL");
		return;
	}
}
Пример #28
0
void PZStability::check() {
  Timer tfull;
  
  // Estimate runtime
  {
    // Test value
    arma::vec x0(count_params());
    x0.zeros();
    if(x0.n_elem)
      x0(0)=0.1;
    if(x0.n_elem>=2)
      x0(1)=-0.1;
    
    Timer t;
    eval(x0,GHMODE);
    double dt=t.get();

    // Total time is
    double ttot=2*x0.n_elem*(x0.n_elem+1)*dt;
    fprintf(stderr,"\nComputing the Hessian will take approximately %s\n",t.parse(ttot).c_str());
    fflush(stderr);
  }

  // Get gradient
  Timer t;
  arma::vec g(gradient());
  printf("Gradient norm is %e (%s)\n",arma::norm(g,2),t.elapsed().c_str()); fflush(stdout);
  if(cancheck && oocheck) {
    size_t nov=count_ov_params(oa,va);
    if(!restr)
      nov+=count_ov_params(ob,vb);

    double ovnorm=arma::norm(g.subvec(0,nov-1),2);
    double oonorm=arma::norm(g.subvec(nov,g.n_elem-1),2);
    printf("OV norm %e, OO norm %e.\n",ovnorm,oonorm);
  }
  t.set();

  // Evaluate Hessian
  arma::mat h(hessian());
  printf("Hessian evaluated (%s)\n",t.elapsed().c_str()); fflush(stdout);
  t.set();

  // Helpers
  arma::mat hvec;
  arma::vec hval;

  if(cancheck && oocheck) {
    // Amount of parameters
    size_t nov=count_ov_params(oa,va);
    if(!restr)
      nov+=count_ov_params(ob,vb);

    // Stability of canonical orbitals
    arma::mat hcan(h.submat(0,0,nov-1,nov-1));
    eig_sym_ordered(hval,hvec,hcan);
    printf("\nOV Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout);
    hval.t().print("Canonical orbital stability");

    // Stability of optimal orbitals
    arma::mat hopt(h.submat(nov-1,nov-1,h.n_rows-1,h.n_cols-1));
    eig_sym_ordered(hval,hvec,hopt);
    printf("\nOO Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout);
    hval.t().print("Optimal orbital stability");
  }

  if(cplx) {
    // Collect real and imaginary parts of Hessian.
    arma::uvec rp, ip;
    real_imag_idx(rp,ip);

    arma::mat rh(rp.n_elem,rp.n_elem);
    for(size_t i=0;i<rp.n_elem;i++)
      for(size_t j=0;j<rp.n_elem;j++)
	rh(i,j)=h(rp(i),rp(j));

    arma::mat ih(ip.n_elem,ip.n_elem);
    for(size_t i=0;i<ip.n_elem;i++)
      for(size_t j=0;j<ip.n_elem;j++)
	ih(i,j)=h(ip(i),ip(j));

    eig_sym_ordered(hval,hvec,rh);
    printf("\nReal part of Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout);
    hval.t().print("Real orbital stability");
    
    eig_sym_ordered(hval,hvec,ih);
    printf("\nImaginary part of Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout);
    hval.t().print("Imaginary orbital stability");
  }
   
  // Total stability
  eig_sym_ordered(hval,hvec,h);
  printf("\nFull Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout);
  hval.t().print("Orbital stability");

  fprintf(stderr,"Check completed in %s.\n",tfull.elapsed().c_str());
}
Пример #29
0
static std::shared_ptr< IResourceHandler > const create()
{
    std::shared_ptr< IResourceHandler > rh( new EflResources() );
    return rh;
}
//------------------------------------------------------------------------------
void MoleculeElDensSurfaceWidget::UpdateGUI( bool updateTable, bool updateBBox )
{
    table_->setEnabled( false );
    if( mol_ == 0 ) return;
    densityMatrixCheckBox_->setEnabled( mol_->CanComputeElectronDensity() );
    ResourceHandler< bool > rh( updatingGUI_, true, false );
    if( updateTable && mol_->GetNumberOfOrbitals() )
    {
        // update orbitals
        const int orbitals = mol_->GetNumberOfOrbitals();
        table_->setRowCount( orbitals );
        QStringList verticalHeaders;
        for( int i = 0;	 i != orbitals; ++i )
        {
            QTableWidgetItem *eigenValueItem = new QTableWidgetItem;
            eigenValueItem->setFlags(  Qt::ItemIsSelectable | Qt::ItemIsEnabled );
            eigenValueItem->setText( QString( "%1" ).arg( mol_->GetOrbitalEigenValue( i  ) ) );
            QTableWidgetItem *occupationItem = new QTableWidgetItem;
            occupationItem->setFlags(  Qt::ItemIsSelectable | Qt::ItemIsEnabled );
            occupationItem->setText( QString( "%1" ).arg( mol_->GetOrbitalOccupation( i ) ) );
            QTableWidgetItem *typeItem = new QTableWidgetItem;
            typeItem->setText( QString( "%1" ).arg( mol_->GetOrbitalType( i ) ) );
            QTableWidgetItem *generatedItem = new QTableWidgetItem;
            generatedItem->setFlags(  Qt::ItemIsSelectable | Qt::ItemIsEnabled );
            // Removed check box, not sure it's a good idea, user
            // will want to check the checkbox and then click on generate
            // to have multiple orbital surfaces generated at once.
            if( mol_->HasOrbitalSurface( i ) )
            {

                //generatedItem->setCheckState( Qt::Checked );
                generatedItem->setText( tr( "Yes" ) );
            }
            else
            {
                //generatedItem->setCheckState( Qt::Unchecked );
                generatedItem->setText( tr( "No" ) );
            }
            table_->setItem( i, 0, generatedItem );
            table_->setItem( i, 1, eigenValueItem );
            table_->setItem( i, 2, occupationItem );
            table_->setItem( i, 3, typeItem );

            //TEMPORARY DISABLED
            //if( mol_->IsAlphaOrbital( i ) )
            //{
            //    verticalHeaders << QString( "%1 (%2)" ).arg( i + 1 ).arg( tr( "alpha" ) );
            //}
            //else if( mol_->IsBetaOrbital( i ) )
            //{
            //    verticalHeaders << QString( "%1 (%2)" ).arg( i + 1 ).arg( tr( "beta" ) );
            //}
        }
        table_->setVerticalHeaderLabels( verticalHeaders );
        table_->resizeColumnsToContents();
        /// @todo do we need the following to make sure everything is unselected ?
        /// table_->setRangeSelected( QTableWidgetSelectionRange( 0, 0, table_->rowCount() - 1, 3 ), false );
    }
    if( updateBBox )
    {
        double dx = 0.;
        double dy = 0.;
        double dz = 0.;
        mol_->GetIsoBoundingBoxSize( dx, dy, dz );
#ifdef PERSISTENT_ISOBBOX
        QSettings s;
        if( s.contains( BBOX_DX_KEY ) ) dx = s.value( BBOX_DX_KEY ).toDouble();
        if( s.contains( BBOX_DY_KEY ) ) dy = s.value( BBOX_DY_KEY ).toDouble(); 
        if( s.contains( BBOX_DZ_KEY ) ) dz = s.value( BBOX_DZ_KEY ).toDouble();
#endif 
        dxSpinBox_->setValue( dx );
        dySpinBox_->setValue( dy );
        dzSpinBox_->setValue( dz );
        ComputeSteps();
    }
    
    double cx = 0.;
    double cy = 0.;
    double cz = 0.;
    double dx = 0.;
    double dy = 0.;
    double dz = 0.;
    mol_->GetIsoBoundingBoxSize( dx, dy, dz );
    mol_->GetIsoBoundingBoxCenter( cx, cy, cz );
    xSpinBox_->setValue( cx );
    ySpinBox_->setValue( cy );
    zSpinBox_->setValue( cz );
    xSpinBox_->setSingleStep( 0.05 * dx );
    ySpinBox_->setSingleStep( 0.05 * dy );
    zSpinBox_->setSingleStep( 0.05 * dz );
    xSpinBox_->setMinimum( cx - dx );
    xSpinBox_->setMaximum( cx + dx );
    ySpinBox_->setMinimum( cy - dy );
    ySpinBox_->setMaximum( cy + dy );
    zSpinBox_->setMinimum( cz - dz );
    zSpinBox_->setMaximum( cz + dz );
    dxSpinBox_->setSingleStep( 0.05 * dx );
    dySpinBox_->setSingleStep( 0.05 * dy );
    dzSpinBox_->setSingleStep( 0.05 * dz );
    table_->setEnabled( true );

}