Beispiel #1
0
int64 PlainFile::tell() {
    ASSERT(valid());
    return m_position;
}
Beispiel #2
0
inline bool invalid(const node_id& val) {
  return !valid(val);
}
Beispiel #3
0
double
wald_method::run(const snp_row &row1, const snp_row &row2, float *output)
{
    arma::mat n0 = arma::zeros<arma::mat>( 3, 3 );
    arma::mat n1 = arma::zeros<arma::mat>( 3, 3 );
    for(int i = 0; i < row1.size( ); i++)
    {
        unsigned char snp1 = row1[ i ];
        unsigned char snp2 = row2[ i ];
        if( snp1 == 3 || snp2 == 3 || m_missing[ i ] == 1 )
        {
            continue;
        }

        unsigned int pheno = m_pheno[ i ];
        if( pheno == 0 )
        {
            n0( snp1, snp2 ) += 1;
        }
        else if( pheno == 1 )
        {
            n1( snp1, snp2 ) += 1;
        }
    }

    arma::mat eta( 3, 3 );
    double num_samples = 0.0;
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            if( n0( i, j ) < METHOD_SMALLEST_CELL_SIZE_BINOMIAL || n1( i, j ) < METHOD_SMALLEST_CELL_SIZE_BINOMIAL )
            {
                continue;
            }

            eta( i, j ) = log( n1( i, j ) / n0( i, j ) );
            num_samples += n1( i, j ) + n0( i, j );
        }
    }

    /* Find valid parameters and estimate beta */
    int num_valid = 0;
    arma::uvec valid( 4 );
    m_beta = arma::zeros<arma::vec>( 4 );
    int i_map[] = { 1, 1, 2, 2 };
    int j_map[] = { 1, 2, 1, 2 };
    for(int i = 0; i < 4; i++)
    {
        int c_i = i_map[ i ];
        int c_j = j_map[ i ];
        if( n0( 0, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n0( 0, c_j ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n0( c_i, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n0( c_i, c_j) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( 0, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( 0, c_j ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( c_i, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( c_i, c_j) >= METHOD_SMALLEST_CELL_SIZE_NORMAL )
        {
            valid[ num_valid ] = i;
            m_beta[ num_valid ] = eta( 0, 0 ) - eta( 0, c_j ) - eta( c_i, 0 ) + eta( c_i, c_j );
            num_valid++;
        }
    }
    set_num_ok_samples( (size_t)num_samples );
    if( num_valid <= 0 )
    {
        return -9;
    }
    
    valid.resize( num_valid );
    m_beta.resize( num_valid );

    /* Construct covariance matrix */
    m_C = arma::zeros<arma::mat>( num_valid, num_valid );
    for(int iv = 0; iv < num_valid; iv++)
    {
        int i = valid[ iv ];
        int c_i = i_map[ i ];
        int c_j = j_map[ i ];

        for(int jv = 0; jv < num_valid; jv++)
        {
            int j = valid[ jv ];
            int o_i = i_map[ j ];
            int o_j = j_map[ j ];

            int same_row = c_i == o_i;
            int same_col = c_j == o_j;
            int in_cell = i == j;

            m_C( iv, jv ) = 1.0 / n0( 0, 0 ) + same_col / n0( 0, c_j ) + same_row / n0( c_i, 0 ) + in_cell / n0( c_i, c_j );
            m_C( iv, jv ) += 1.0 / n1( 0, 0 ) + same_col / n1( 0, c_j ) + same_row / n1( c_i, 0 ) + in_cell / n1( c_i, c_j );
        }
    }

    arma::mat Cinv( num_valid, num_valid );
    if( !inv( Cinv, m_C ) )
    {
        return -9;
    }
    
    /* Test if b != 0 with Wald test */
    double chi = dot( m_beta, Cinv * m_beta );
    output[ 0 ] = chi;
    output[ 1 ] = 1.0 - chi_square_cdf( chi, num_valid );
    output[ 2 ] = valid.n_elem;

    return output[ 1 ];
}
Beispiel #4
0
void move::execute(bool& success, bool& complete)
{
	if(!valid()) {
		success = false;
		//Setting complete to true signifies to side_actions to delete the planned action.
		complete = true;
		return;
	}

	if(get_source_hex() == get_dest_hex()) {
		//zero-hex move, used by attack subclass
		success = complete = true;
		return;
	}

	LOG_WB << "Executing: " << shared_from_this() << "\n";

	// Copy the current route to ensure it remains valid throughout the animation.
	const std::vector<map_location> steps = route_->steps;

	set_arrow_brightness(ARROW_BRIGHTNESS_HIGHLIGHTED);
	hide_fake_unit();

	size_t num_steps;
	bool interrupted;
	try {
		events::mouse_handler& mouse_handler = resources::controller->get_mouse_handler_base();
		num_steps = mouse_handler.move_unit_along_route(steps, interrupted);
	} catch (return_to_play_side_exception&) {
		set_arrow_brightness(ARROW_BRIGHTNESS_STANDARD);
		throw; // we rely on the caller to delete this action
	}
	const map_location & final_location = steps[num_steps];
	unit_map::const_iterator unit_it = resources::units->find(final_location);

	if ( num_steps == 0 )
	{
		LOG_WB << "Move execution resulted in zero movement.\n";
		success = false;
		complete = true;
	}
	else if ( unit_it == resources::units->end()  ||  unit_it->id() != unit_id_ )
	{
		WRN_WB << "Unit disappeared from map during move execution." << std::endl;
		success = false;
		complete = true;
	}
	else
	{
		complete = num_steps + 1 == steps.size();
		success = complete && !interrupted;

		if ( !success )
		{
			if ( complete )
			{
				LOG_WB << "Move completed, but interrupted on final hex. Halting.\n";
				//reset to a single-hex path, just in case *this is a wb::attack
				route_->steps = std::vector<map_location>(1, final_location);
				arrow_.reset();
			}
			else
			{
				LOG_WB << "Move finished at (" << final_location << ") instead of at (" << get_dest_hex() << "). Setting new path.\n";
				route_->steps = std::vector<map_location>(steps.begin() + num_steps, steps.end());
				//FIXME: probably better to use the new calculate_new_route() instead of the above:
				//calculate_new_route(final_location, steps.back());
				// Of course, "better" would need to be verified.
				arrow_->set_path(route_->steps);
			}
		}
	}

	if(!complete)
	{
		set_arrow_brightness(ARROW_BRIGHTNESS_STANDARD);
		show_fake_unit();
	}
}
Beispiel #5
0
bool PlainFile::truncate(int64 size) {
  assert(valid());
  return ftruncate(m_fd, size) == 0;
}
Beispiel #6
0
	simple_file::simple_file(const std::wstring& aPath, const std::wstring& aMode) : 
		iFile(new handle(_wfopen(aPath.c_str(), aMode.c_str()))), iError(valid() ? 0 : errno) 
	{
	}
Beispiel #7
0
void ItemLineEdit::setItemNumber(const QString& pNumber)
{
  XSqlQuery item;
  bool      found = FALSE;

  _parsed = TRUE;

  if (pNumber == text())
    return;

  if (!pNumber.isEmpty())
  {
    if (_useValidationQuery)
    {
      item.prepare(_validationSql);
      item.bindValue(":item_number", pNumber);
      item.exec();
      if (item.first())
        found = TRUE;
    }
    else if (_useQuery)
    {
      item.prepare(_sql);
      item.exec();
      found = (item.findFirst("item_number", pNumber) != -1);
    }
    else if (pNumber != QString::Null())
    {
      QString pre( "SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                   "                uom_name, item_type, item_config, item_upccode");

      QStringList clauses;
      clauses = _extraClauses;
      clauses << "(item_number=:item_number OR item_upccode=:item_number)";

      item.prepare(buildItemLineEditQuery(pre, clauses, QString::null, _type));
      item.bindValue(":item_number", pNumber);
      item.exec();
      
      if (item.size() > 1)
      { 
        ParameterList params;
        params.append("search", pNumber);
        params.append("searchNumber");
        params.append("searchUpc");
        sSearch(params);
        return;
      }
      else
        found = item.first();
    }
  }
  if (found)
  {
    _itemNumber = pNumber;
    _uom        = item.value("uom_name").toString();
    _itemType   = item.value("item_type").toString();
    _configured = item.value("item_config").toBool();
    _id         = item.value("item_id").toInt();
    _upc        = item.value("item_upccode").toInt();
    _valid      = TRUE;

    setText(item.value("item_number").toString());

    emit aliasChanged("");
    emit typeChanged(_itemType);
    emit descrip1Changed(item.value("item_descrip1").toString());
    emit descrip2Changed(item.value("item_descrip2").toString());
    emit uomChanged(item.value("uom_name").toString());
    emit configured(item.value("item_config").toBool());
    emit upcChanged(item.value("item_upccode").toString());
    
    emit valid(TRUE);
  }
  else
  {
    _itemNumber = "";
    _uom        = "";
    _itemType   = "";
    _id         = -1;
    _valid      = FALSE;
    _upc        = "";

    setText("");

    emit aliasChanged("");
    emit typeChanged("");
    emit descrip1Changed("");
    emit descrip2Changed("");
    emit uomChanged("");
    emit configured(FALSE);
    emit upcChanged("");

    emit valid(FALSE);
  }
}
Beispiel #8
0
void WoLineEdit::silentSetId(const int pId)
{
  if (pId != -1)
  {
    XSqlQuery wo;

    wo.prepare(_query + _idClause +
               (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
               QString(";"));
    wo.bindValue(":id", pId);
    wo.exec();
    if (wo.first())
    {
      if (_completer)
        static_cast<QSqlQueryModel* >(_completer->model())->setQuery(QSqlQuery());

      _id    = pId;
      _valid = TRUE;

      setText(wo.value("number").toString());

      _qtyOrdered  = wo.value("wo_qtyord").toDouble();
      _qtyReceived = wo.value("wo_qtyrcv").toDouble();
      _method = wo.value("method").toString();
      _currentWarehouseid = (wo.value("warehous_id").isNull())
                                      ? -1 : wo.value("warehous_id").toInt();

      emit newId(_id);
      emit newItemid(wo.value("item_id").toInt());
      emit warehouseChanged(wo.value("warehous_code").toString());
      emit itemNumberChanged(wo.value("item_number").toString());
      emit uomChanged(wo.value("uom_name").toString());
      emit itemDescrip1Changed(wo.value("item_descrip1").toString());
      emit itemDescrip2Changed(wo.value("item_descrip2").toString());
      emit startDateChanged(wo.value("wo_startdate").toDate());
      emit dueDateChanged(wo.value("wo_duedate").toDate());
      emit qtyOrderedChanged(wo.value("wo_qtyord").toDouble());
      emit qtyReceivedChanged(wo.value("wo_qtyrcv").toDouble());
      emit qtyBalanceChanged(wo.value("balance").toDouble());
      emit statusChanged(wo.value("wo_status").toString());
      emit methodChanged(wo.value("wo_method").toString());
      emit valid(TRUE);
    }
  }
  else
  {
    _id    = -1;
    _valid = FALSE;
    _currentWarehouseid = -1;

    XLineEdit::clear();

    emit newId(-1);
    emit newItemid(-1);
    emit warehouseChanged("");
    emit itemNumberChanged("");
    emit uomChanged("");
    emit itemDescrip1Changed("");
    emit itemDescrip2Changed("");
    emit startDateChanged(QDate());
    emit dueDateChanged(QDate());
    emit qtyOrderedChanged(0);
    emit qtyReceivedChanged(0);
    emit qtyBalanceChanged(0);
    emit statusChanged("");
    emit methodChanged("");
    emit valid(FALSE);
      
    _qtyOrdered  = 0;
    _qtyReceived = 0;
  }

  _parsed = TRUE;
  emit parsed();
}
Beispiel #9
0
void WomatlCluster::setId(int pWomatlid)
{
  _source = WoMaterial;
  _sourceId = pWomatlid;

  if (pWomatlid == -1)
    sPopulateInfo(-1);

  else
  {
    bool qual = FALSE;
    QString sql( "SELECT list.womatl_id AS womatlid, item_number, "
                 "       wo_id, uom_name, item_descrip1, item_descrip2,"
                 "       ABS(list.womatl_qtyreq) AS _qtyreq, "
                 "       ABS(list.womatl_qtyiss) AS _qtyiss,"
                 "       (list.womatl_qtyfxd) AS qtyfxd,"
                 "       (list.womatl_qtyper) AS qtyper,"
                 "       (list.womatl_scrap * 100) AS scrap,"
                 "       (abs(list.womatl_qtyreq)) AS qtyreq, "
                 "       (abs(list.womatl_qtyiss)) AS qtyiss, "
                 "       (list.womatl_qtywipscrap) AS qtywipscrap "
                 "FROM womatl AS list, womatl AS target, wo, itemsite, item, uom "
                 "WHERE ( (list.womatl_wo_id=wo_id)"
                 " AND (target.womatl_wo_id=wo_id)"
                 " AND (list.womatl_itemsite_id=itemsite_id)"
                 " AND (itemsite_item_id=item_id)"
                 " AND (list.womatl_uom_id=uom_id)"
                 " AND (target.womatl_id=:womatl_id)"
                 " AND (list.womatl_issuemethod IN (" );

    if (_type & Push)
    {
      sql += "'S'";
      qual = TRUE;
    }

    if (_type & Pull)
    {
      if (qual)
        sql += ",";
      else
        qual = TRUE;

      sql += "'L'";
    }

    if (_type & Mixed)
    {
      if (qual)
        sql += ",";

      sql += "'M'";
    }

    sql += ")) );";

    XSqlQuery query;
    query.prepare(sql);
    query.bindValue(":womatl_id", pWomatlid);
    query.exec();
    if (query.first())
    {
      _womatl.prepare(sql);
      _womatl.bindValue(":womatl_id", pWomatlid);
      _womatl.exec();

      emit newId(pWomatlid);

      _valid = TRUE;
      _id = pWomatlid;

      _itemNumber->populate(query);
      _itemNumber->setId(pWomatlid);
    }
    else
    {
      _valid = FALSE;
      _woid = -1;
      _id = -1;

      emit newId(-1);
      emit valid(FALSE);

      _itemNumber->clear();
    }
  }
}
Beispiel #10
0
void WoLineEdit::setId(int pId)
{
  bool found = FALSE;
  if (pId != -1)
  {
    XSqlQuery wo;
        if (_useQuery)
    {
      wo.prepare(_sql);
      wo.exec();
      found = (wo.findFirst("wo_id", pId) != -1);
    }
        else
        {
      wo.prepare( "SELECT formatWONumber(wo_id) AS wonumber,"
                  "       warehous_code, item_id, item_number, uom_name,"
                  "       item_descrip1, item_descrip2,"
                  "       wo_qtyord, wo_qtyrcv, wo_status,"
                  "       wo_duedate,"
                  "       wo_startdate,"
                  "       formatQtyPer(wo_qtyord) AS ordered,"
                  "       formatQtyPer(wo_qtyrcv) AS received, "
                  "       formatQtyPer(noNeg(wo_qtyord - wo_qtyrcv)) AS balance "
                  "FROM wo, itemsite, item, warehous, uom "
                  "WHERE ((wo_itemsite_id=itemsite_id)"
                  " AND (itemsite_item_id=item_id)"
                  " AND (item_inv_uom_id=uom_id)"
                  " AND (itemsite_warehous_id=warehous_id)"
                  " AND (wo_id=:wo_id));" );
      wo.bindValue(":wo_id", pId);
      wo.exec();
      found = (wo.first());
        }
        if (found)
    {
      _id    = pId;
      _valid = TRUE;

      setText(wo.value("wonumber").toString());

      emit newId(_id);
      emit newItemid(wo.value("item_id").toInt());
      emit warehouseChanged(wo.value("warehous_code").toString());
      emit itemNumberChanged(wo.value("item_number").toString());
      emit uomChanged(wo.value("uom_name").toString());
      emit itemDescrip1Changed(wo.value("item_descrip1").toString());
      emit itemDescrip2Changed(wo.value("item_descrip2").toString());
      emit startDateChanged(wo.value("wo_startdate").toDate());
      emit dueDateChanged(wo.value("wo_duedate").toDate());
      emit qtyOrderedChanged(wo.value("ordered").toString());
      emit qtyReceivedChanged(wo.value("received").toString());
      emit qtyBalanceChanged(wo.value("balance").toString());
      emit statusChanged(wo.value("wo_status").toString());
      emit valid(TRUE);

      _qtyOrdered  = wo.value("wo_qtyord").toDouble();
      _qtyReceived = wo.value("wo_qtyrcv").toDouble();

      _parsed = TRUE;

      return;
    }
  }

  _id    = -1;
  _valid = FALSE;

  setText("");

  emit newId(-1);
  emit newItemid(-1);
  emit warehouseChanged("");
  emit itemNumberChanged("");
  emit uomChanged("");
  emit itemDescrip1Changed("");
  emit itemDescrip2Changed("");
  emit startDateChanged(QDate());
  emit dueDateChanged(QDate());
  emit qtyOrderedChanged("");
  emit qtyReceivedChanged("");
  emit qtyBalanceChanged("");
  emit statusChanged("");
  emit valid(FALSE);
    
  _qtyOrdered  = 0;
  _qtyReceived = 0;

  _parsed = TRUE;
}
Beispiel #11
0
void OrderLineEdit::sParse()
{
  bool oldvalid = _valid;
  if (! _parsed)
  {
    QString stripped = text().trimmed().toUpper();
    if (stripped.length() == 0)
    {
      _parsed = true;
      setId(-1);
    }
    else
    {
      QString oldExtraClause = _extraClause;

      XSqlQuery countQ;
      countQ.prepare("SELECT COUNT(*) AS count FROM orderhead WHERE (TRUE) " +
		      _numClause +
		      (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
		      QString(";"));
      countQ.bindValue(":number", text());
      countQ.exec();
      if (countQ.first())
      {
	int result = countQ.value("count").toInt();
	if (result <= 0)
	{
	  _id = -1;
	  XLineEdit::clear();
	}
	else if (result == 1)
	{
	  XSqlQuery numQ;
	  numQ.prepare(_query + _numClause +
		      (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
		      QString(";"));
	  numQ.bindValue(":number", text());
	  numQ.exec();
	  if (numQ.first())
	  {
	    _valid = true;
	    setId(numQ.value("id").toInt(), numQ.value("name").toString());
	    _description	= numQ.value("description").toString();
	    _from		= numQ.value("orderhead_from").toString();
	    _to		= numQ.value("orderhead_to").toString();
	  }
	  else if (numQ.lastError().type() != QSqlError::NoError)
	    QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
					  .arg(__FILE__)
					  .arg(__LINE__),
				  numQ.lastError().databaseText());
	}
	else
	{
	  _extraClause += "AND (orderhead_number=" + text() + ")";
          sEllipses();
	  _extraClause += "AND (orderhead_type='" + type() + "')";
	}
      }
      else if (countQ.lastError().type() != QSqlError::NoError)
      {
	QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
				      .arg(__FILE__)
				      .arg(__LINE__),
			      countQ.lastError().databaseText());
      }

      _extraClause = oldExtraClause;
    }
  }

  _parsed = true;
  if (_valid != oldvalid)
    emit valid(_valid);
  emit parsed();
  emit numberChanged(text(), _name);
}
Beispiel #12
0
void RecursiveDirectoryIterator::next() {
  do {
    DirectoryIterator::next();
  } while (valid() && DirectoryIterator::isdot());
}
Beispiel #13
0
int PlainFile::getc() {
    ASSERT(valid());
    return File::getc();
}
Beispiel #14
0
bool PlainFile::truncate(int64 size) {
    ASSERT(valid());
    return ftruncate(m_fd, size) == 0;
}
   void pending_chain_state::get_undo_state( const chain_interface_ptr& undo_state_arg )const
   {
      auto undo_state = std::dynamic_pointer_cast<pending_chain_state>( undo_state_arg );
      chain_interface_ptr prev_state = _prev_state.lock();
      FC_ASSERT( prev_state );
      for( const auto& item : properties )
      {
         auto prev_value = prev_state->get_property( (chain_property_enum)item.first );
         undo_state->set_property( (chain_property_enum)item.first, prev_value );
      }
      for( const auto& item : assets )
      {
         auto prev_value = prev_state->get_asset_record( item.first );
         if( !!prev_value ) undo_state->store_asset_record( *prev_value );
         else undo_state->store_asset_record( item.second.make_null() );
      }
      for( const auto& item : slates )
      {
         auto prev_value = prev_state->get_delegate_slate( item.first );
         if( prev_value ) undo_state->store_delegate_slate( item.first, *prev_value );
         else undo_state->store_delegate_slate( item.first, delegate_slate() );
      }
      for( const auto& item : accounts )
      {
         auto prev_value = prev_state->get_account_record( item.first );
         if( !!prev_value ) undo_state->store_account_record( *prev_value );
         else undo_state->store_account_record( item.second.make_null() );
      }
#if 0
      for( const auto& item : proposals )
      {
         auto prev_value = prev_state->get_proposal_record( item.first );
         if( !!prev_value ) undo_state->store_proposal_record( *prev_value );
         else undo_state->store_proposal_record( item.second.make_null() );
      }
      for( const auto& item : proposal_votes )
      {
         auto prev_value = prev_state->get_proposal_vote( item.first );
         if( !!prev_value ) undo_state->store_proposal_vote( *prev_value );
         else { undo_state->store_proposal_vote( item.second.make_null() ); }
      }
#endif
      for( const auto& item : balances )
      {
         auto prev_value = prev_state->get_balance_record( item.first );
         if( !!prev_value ) undo_state->store_balance_record( *prev_value );
         else undo_state->store_balance_record( item.second.make_null() );
      }
      for( const auto& item : transactions )
      {
         auto prev_value = prev_state->get_transaction( item.first );
         if( !!prev_value ) undo_state->store_transaction( item.first, *prev_value );
         else undo_state->store_transaction( item.first, transaction_record() );
      }
      for( const auto& item : bids )
      {
         auto prev_value = prev_state->get_bid_record( item.first );
         if( prev_value.valid() ) undo_state->store_bid_record( item.first, *prev_value );
         else  undo_state->store_bid_record( item.first, order_record() );
      }
      for( const auto& item : asks )
      {
         auto prev_value = prev_state->get_ask_record( item.first );
         if( prev_value.valid() ) undo_state->store_ask_record( item.first, *prev_value );
         else  undo_state->store_ask_record( item.first, order_record() );
      }
      for( const auto& item : shorts )
      {
         auto prev_value = prev_state->get_short_record( item.first );
         if( prev_value.valid() ) undo_state->store_short_record( item.first, *prev_value );
         else  undo_state->store_short_record( item.first, order_record() );
      }
      for( const auto& item : collateral )
      {
         auto prev_value = prev_state->get_collateral_record( item.first );
         if( prev_value.valid() ) undo_state->store_collateral_record( item.first, *prev_value );
         else  undo_state->store_collateral_record( item.first, collateral_record() );
      }
      for( const auto& item : slots )
      {
         auto prev_value = prev_state->get_slot_record( item.first );
         if( prev_value ) undo_state->store_slot_record( *prev_value );
         else
         {
             slot_record invalid_slot_record;
             invalid_slot_record.start_time = item.first;
             invalid_slot_record.block_produced = true;
             invalid_slot_record.block_id = block_id_type();
             undo_state->store_slot_record( invalid_slot_record );
         }
      }
      for( const auto& item : market_statuses )
      {
         auto prev_value = prev_state->get_market_status( item.first.first, item.first.second );
         if( prev_value ) undo_state->store_market_status( *prev_value );
         else
         {
            undo_state->store_market_status( market_status() );
         }
      }
      for( const auto& item : feeds )
      {
         auto prev_value = prev_state->get_feed( item.first );
         if( prev_value ) undo_state->set_feed( *prev_value );
         else undo_state->set_feed( feed_record{item.first} );
      }
      for( const auto& item : burns )
      {
         undo_state->store_burn_record( burn_record( item.first ) );
      }

      const auto dirty_markets = prev_state->get_dirty_markets();
      undo_state->set_dirty_markets(dirty_markets);

      /* NOTE: Recent operations are currently not rewound on undo */
   }
req::ptr<File>
PhpStreamWrapper::open(const String& filename, const String& mode,
                       int options, const req::ptr<StreamContext>& context) {
  if (strncasecmp(filename.c_str(), "php://", 6)) {
    return nullptr;
  }

  const char *req = filename.c_str() + sizeof("php://") - 1;

  if (!strcasecmp(req, "stdin")) {
    return req::make<PlainFile>(dup(STDIN_FILENO), true, s_php);
  }
  if (!strcasecmp(req, "stdout")) {
    return req::make<PlainFile>(dup(STDOUT_FILENO), true, s_php);
  }
  if (!strcasecmp(req, "stderr")) {
    return req::make<PlainFile>(dup(STDERR_FILENO), true, s_php);
  }
  if (!strncasecmp(req, "fd/", sizeof("fd/") - 1)) {
    return openFD(req + sizeof("fd/") - 1);
  }
  if (!strncasecmp(req, "filter/", sizeof("filter/") - 1)) {
    return phpStreamOpenFilter(req + sizeof("filter") - 1, mode,
                               options, context);
  }

  if (!strncasecmp(req, "temp", sizeof("temp") - 1)) {
    auto file = req::make<TempFile>(true, s_php, s_temp);
    if (!file->valid()) {
      raise_warning("Unable to create temporary file");
      return nullptr;
    }
    return file;
  }
  if (!strcasecmp(req, "memory")) {
    auto file = req::make<TempFile>(true, s_php, s_memory);
    if (!file->valid()) {
      raise_warning("Unable to create temporary file");
      return nullptr;
    }

    file->getData()->m_mode = [mode] {
      if (mode.empty()) {
        return "w+b";
      }
      for (auto c : mode.slice()) {
        switch (c) {
          case '+':
          case 'w':
          case 'a':
          case 'x':
          case 'c':
            return "w+b";
          default:
            break;
        }
      }
      return "rb";
    }();
    return file;
  }

  if (!strcasecmp(req, "input")) {
    auto raw_post = g_context->getRawPostData();
    return req::make<MemFile>(
      raw_post.c_str(), raw_post.size(), s_php, s_input);
  }

  if (!strcasecmp(req, "output")) {
    return req::make<OutputFile>(filename);
  }

  return nullptr;
}
Beispiel #17
0
void decimate_inplace(MutableTriangleTopology& mesh, RawField<TV,VertexId> X,
                      const T distance, const T max_angle, const int min_vertices, const T boundary_distance) {
  if (mesh.n_vertices() <= min_vertices)
    return;
  const T area = sqr(distance);
  const T sign_sqr_min_cos = sign_sqr(max_angle > .99*pi ? -1 : cos(max_angle));

  // Finds the best edge to collapse v along.  Returns (q(e),dst(e)).
  const auto best_collapse = [&mesh,X](const VertexId v) {
    Quadric q = compute_quadric(mesh,X,v);

    // Find the best edge, ignoring normal constraints
    T min_q = inf;
    HalfedgeId min_e;
    for (const auto e : mesh.outgoing(v)) {
      const T qx = q(X[mesh.dst(e)]);
      if (min_q > qx) {
        min_q = qx;
        min_e = e;
      }
    }
    return tuple(min_q,mesh.dst(min_e));
  };

  // Initialize quadrics and heap
  Heap heap(mesh.n_vertices_);
  for (const auto v : mesh.vertices()) {
    const auto qe = best_collapse(v);
    if (qe.x <= area)
      heap.inv_heap[v] = heap.heap.append(tuple(v,qe.x,qe.y));
  }
  heap.make();

  // Update the quadric information for a vertex
  const auto update = [&heap,best_collapse,area](const VertexId v) {
    const auto qe = best_collapse(v);
    if (qe.x <= area)
      heap.set(v,qe.x,qe.y);
    else
      heap.erase(v);
  };

  // Repeatedly collapse the best vertex
  while (heap.size()) {
    const auto v = heap.pop();

    // Do these vertices still exist?
    if (mesh.valid(v.x) && mesh.valid(v.y)) {
      const auto e = mesh.halfedge(v.x,v.y);

      // Is the collapse invalid?
      if (e.valid() && mesh.is_collapse_safe(e)) {
        const auto vs = mesh.src(e),
                   vd = mesh.dst(e);
        const auto xs = X[vs],
                   xd = X[vd];

        // Are we moving a boundary vertex too far from its two boundary lines?
        {
          const auto b = mesh.halfedge(vs);
          if (mesh.is_boundary(b)) {
            const auto x0 = X[mesh.dst(b)],
                       x1 = X[mesh.src(mesh.prev(b))];
            if (   line_point_distance(simplex(xs,x0),xd) > boundary_distance
                || line_point_distance(simplex(xs,x1),xd) > boundary_distance)
              goto bad;
          }
        }

        // Do the normals change too much?
        if (sign_sqr_min_cos > -1)
          for (const auto ee : mesh.outgoing(vs))
            if (e!=ee && !mesh.is_boundary(ee)) {
              const auto v2 = mesh.opposite(ee);
              if (v2 != vd) {
                const auto x1 = X[mesh.dst(ee)],
                           x2 = X[v2];
                const auto n0 = cross(x2-x1,xs-x1),
                           n1 = cross(x2-x1,xd-x1);
                if (sign_sqr(dot(n0,n1)) < sign_sqr_min_cos*sqr_magnitude(n0)*sqr_magnitude(n1))
                  goto bad;
              }
            }

        // Collapse vs onto vd, then update the heap
        mesh.unsafe_collapse(e);
        if (mesh.n_vertices() <= min_vertices)
          break;
        update(vd);
        for (const auto e : mesh.outgoing(vd))
          update(mesh.dst(e));
      }
    }
    bad:;
  }
}
Beispiel #18
0
/** Applies this axis' parameters to the graph
*
*/
void ScaleDetails::apply()
{
  if (m_modified && valid())
  {
    //as the classes are separate now this may cause a problem as ideally i'd get this from the axis tab,
    //but at the moment there's nothing to cause a problem as the only other cases that are used are Date
    //and Time and Mantid doesn't support them in data yet i've been told
    ScaleDraw::ScaleType type = m_graph->axisType(m_mappedaxis);

    double start = 0.0, end = 0.0, step = 0.0, breakLeft = -DBL_MAX, breakRight = DBL_MAX;
    if (type == ScaleDraw::Date)
    {
      ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(m_graph->plotWidget()->axisScaleDraw(m_mappedaxis));
      QDateTime origin = sclDraw->dateTimeOrigin();
      start = (double)origin.secsTo(m_dteStartDateTime->dateTime());
      end = (double)origin.secsTo(m_dteEndDateTime->dateTime());
    } 
    else if (type == ScaleDraw::Time)
    {
      ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(m_graph->plotWidget()->axisScaleDraw(m_mappedaxis));
      QTime origin = sclDraw->dateTimeOrigin().time();
      start = (double)origin.msecsTo(m_timStartTime->time());
      end = (double)origin.msecsTo(m_timEndTime->time());
    } 
    else
    {
      start = m_dspnStart->value();
      end = m_dspnEnd->value();
    }

    if (m_radStep->isChecked())
    {
      step = m_dspnStep->value();
      if (type == ScaleDraw::Time)
      {
        switch (m_cmbUnit->currentIndex())
        {
        case 0:
          break;
        case 1:
          step *= 1e3;
          break;
        case 2:
          step *= 6e4;
          break;
        case 3:
          step *= 36e5;
          break;
        }
      }
      else if (type == ScaleDraw::Date)
      {
        switch (m_cmbUnit->currentIndex())
        {
        case 0:
          step *= 86400;
          break;
        case 1:
          step *= 604800;
          break;
        }
      }
    }

    if (m_grpAxesBreaks->isChecked())
    {
      breakLeft = qMin(m_dspnBreakStart->value(), m_dspnBreakEnd->value());
      breakRight = qMax(m_dspnBreakStart->value(), m_dspnBreakEnd->value());
    }
    m_graph->setScale(m_mappedaxis, start, end, step, m_spnMajorValue->value(), m_cmbMinorValue->currentText().toInt(),
      m_cmbScaleType->currentIndex(), m_chkInvert->isChecked(), breakLeft, breakRight, m_spnBreakPosition->value(),
      m_dspnStepBeforeBreak->value(),m_dspnStepAfterBreak->value(), m_cmbMinorTicksBeforeBreak->currentText().toInt(),
      m_cmbMinorTicksAfterBreak->currentText().toInt(), m_chkLog10AfterBreak->isChecked(), m_spnBreakWidth->value(),
      m_chkBreakDecoration->isChecked(), m_dspnN->value());
    m_graph->changeIntensity(true);
    m_graph->notifyChanges();
    m_modified = false;
  }
}
Beispiel #19
0
/** Get the value of the second key of a node.
 *  @param i is a node in a search tree
 *  @return the value of the second key at i
 */
keytyp Ssets2k::key2(index i) {
	assert(valid(i));
	return dmin(i) + dkey(i);
}
Beispiel #20
0
std::string user::token() const {
	if (valid()) {
		return data->token;
	}
	return "";
}
Beispiel #21
0
void ItemLineEdit::silentSetId(const int pId)
{
  XSqlQuery item;
  bool      found = FALSE;

  _parsed = TRUE;

  if (_useValidationQuery)
  {
    item.prepare(_validationSql);
    item.bindValue(":item_id", pId);
    item.exec();
    if (item.first())
      found = TRUE;
  }
  else if (_useQuery)
  {
    item.prepare(_sql);
    item.exec();
    found = (item.findFirst("item_id", pId) != -1);
  }
  else if (pId != -1)
  {
    QString pre( "SELECT DISTINCT item_number, item_descrip1, item_descrip2,"
                 "                uom_name, item_type, item_config, item_upccode");

    QStringList clauses;
    clauses = _extraClauses;
    clauses << "(item_id=:item_id)";

    item.prepare(buildItemLineEditQuery(pre, clauses, QString::null, _type));
    item.bindValue(":item_id", pId);
    item.exec();

    found = item.first();
  }

  if (found)
  {
    if (completer())
    {
      disconnect(this, SIGNAL(textChanged(QString)), this, SLOT(sHandleCompleter()));
      static_cast<QSqlQueryModel* >(completer()->model())->setQuery(QSqlQuery());
    }

    _itemNumber = item.value("item_number").toString();
    _uom        = item.value("uom_name").toString();
    _itemType   = item.value("item_type").toString();
    _configured = item.value("item_config").toBool();
    _upc        = item.value("item_upccode").toString();
    _id         = pId;
    _valid      = TRUE;

    setText(item.value("item_number").toString());
    emit aliasChanged("");
    emit typeChanged(_itemType);
    emit descrip1Changed(item.value("item_descrip1").toString());
    emit descrip2Changed(item.value("item_descrip2").toString());
    emit uomChanged(item.value("uom_name").toString());
    emit configured(item.value("item_config").toBool());
    emit upcChanged(item.value("item_upccode").toString());
    
    emit valid(TRUE);

    if (completer())
      connect(this, SIGNAL(textChanged(QString)), this, SLOT(sHandleCompleter()));
  }
  else
  {
    _itemNumber = "";
    _uom        = "";
    _itemType   = "";
    _id         = -1;
    _upc        = "";
    _valid      = FALSE;

    setText("");

    emit aliasChanged("");
    emit typeChanged("");
    emit descrip1Changed("");
    emit descrip2Changed("");
    emit uomChanged("");
    emit configured(FALSE);
    emit upcChanged("");

    emit valid(FALSE);
  }
} 
Beispiel #22
0
std::string user::name() const {
	if (valid()) {
		return data->name;
	}
	return "";
}
Beispiel #23
0
int64 PlainFile::tell() {
  assert(valid());
  return m_position;
}
Beispiel #24
0
void user::unlink_session(std::shared_ptr<session> s) {
	if (s && valid()) {
		const std::string &r_name = s->remote_name();
		data->live.erase(r_name);
	}
}
Beispiel #25
0
inline bool dispatch_message_valid(const header& hdr) {
  return  valid(hdr.dest_node)
       && nonzero(hdr.dest_actor)
       && nonzero(hdr.payload_len);
}
Beispiel #26
0
void user::log(const std::string &msg) {
	if (valid()) {
		data->log += "\n" + msg + "\n";
	}
}
Beispiel #27
0
void VendorLineEdit::setId(int pId)
{
  if (pId != -1)
  {
    QString sql( "SELECT vend_number, vend_name,"
                 "       vend_address1, vend_address2, vend_address3,"
                 "       vend_city, vend_state, vend_zip, vend_country "
                 "FROM vend "
                 "WHERE ( (vend_id=:vend_id)" );

    if (_type == __activeVendors)
      sql += " AND (vend_active) ";

    sql += ");";

    XSqlQuery vend;
    vend.prepare(sql);
    vend.bindValue(":vend_id", pId);
    vend.exec();
    if (vend.first())
    {
      _id     = pId;
      _valid  = TRUE;
  
      setText(vend.value("vend_number").toString());
      _parsed = TRUE;
      
      if (_mapper->model() &&
          _mapper->model()->data(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(this))).toString() != text())
        _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(this)), text());

      emit nameChanged(vend.value("vend_name").toString());
      emit address1Changed(vend.value("vend_address1").toString());
      emit address2Changed(vend.value("vend_address2").toString());
      emit address3Changed(vend.value("vend_address3").toString());
      emit cityChanged(vend.value("vend_city").toString());
      emit stateChanged(vend.value("vend_state").toString());
      emit zipCodeChanged(vend.value("vend_zip").toString());
      emit countryChanged(vend.value("vend_country").toString());
      emit newId(_id);
      emit valid(TRUE);

      return;
    }
  }

  _id     = -1;
  _valid  = FALSE;

  setText("");

  emit nameChanged("");
  emit address1Changed("");
  emit address2Changed("");
  emit address3Changed("");
  emit cityChanged("");
  emit stateChanged("");
  emit zipCodeChanged("");
  emit countryChanged("");
  emit newId(-1);
  emit valid(FALSE);

  _parsed = TRUE;
}
Beispiel #28
0
ProxyData::operator bool() const {
	return valid();
}
Beispiel #29
0
int PlainFile::getc() {
  assert(valid());
  return File::getc();
}
Beispiel #30
0
   void wallet_db::repair_records( const fc::sha512& password )
   { try {
       FC_ASSERT( is_open() );

       vector<generic_wallet_record> records;
       for( auto iter = my->_records.begin(); iter.valid(); ++iter )
           records.push_back( iter.value() );

       // Repair account_data.is_my_account and key_data.account_address
       for( generic_wallet_record& record : records )
       {
           try
           {
               if( wallet_record_type_enum( record.type ) == account_record_type )
               {
                   wallet_account_record account_record = record.as<wallet_account_record>();
                   store_account( account_record );
               }
           }
           catch( ... )
           {
           }
       }

       // Repair key_data.public_key when I have the private key and
       // repair key_data.account_address and account_data.is_my_account
       for( generic_wallet_record& record : records )
       {
           try
           {
               if( wallet_record_type_enum( record.type ) == key_record_type )
               {
                   wallet_key_record key_record = record.as<wallet_key_record>();
                   if( key_record.has_private_key() )
                   {
                       const private_key_type private_key = key_record.decrypt_private_key( password );
                       const public_key_type public_key = private_key.get_public_key();
                       if( key_record.public_key != public_key )
                       {
                           const address key_address = key_record.get_address();
                           keys.erase( key_address );
                           btc_to_bts_address.erase( key_address );
                           btc_to_bts_address.erase( address( pts_address( key_record.public_key, false, 0  ) ) );
                           btc_to_bts_address.erase( address( pts_address( key_record.public_key, true,  0  ) ) );
                           btc_to_bts_address.erase( address( pts_address( key_record.public_key, false, 56 ) ) );
                           btc_to_bts_address.erase( address( pts_address( key_record.public_key, true,  56 ) ) );

                           key_record.public_key = public_key;
                           my->load_key_record( key_record );
                       }
                   }
                   store_key( key_record );
               }
           }
           catch( ... )
           {
           }
       }

       // Repair transaction_data.record_id
       for( generic_wallet_record& record : records )
       {
           try
           {
               if( wallet_record_type_enum( record.type ) == transaction_record_type )
               {
                   wallet_transaction_record transaction_record = record.as<wallet_transaction_record>();
                   if( transaction_record.trx.id() != signed_transaction().id()  )
                   {
                       const transaction_id_type record_id = transaction_record.trx.permanent_id();
                       if( transaction_record.record_id != record_id )
                       {
                           transactions.erase( transaction_record.record_id );
                           id_to_transaction_record_index.erase( transaction_record.record_id );

                           transaction_record.record_id = record_id;
                           my->load_transaction_record( transaction_record );
                       }
                   }
                   store_transaction( transaction_record );
               }
           }
           catch( ... )
           {
           }
       }
   } FC_CAPTURE_AND_RETHROW() }