Пример #1
0
bool orReport::print(QPrinter *prtThis, bool boolSetupPrinter, bool showPreview, QWidget *parent)
{
// TODO: Figure out how all this is supposed to be with the new engine
  bool retval = false;
  bool localPrinter = false;

  if (multiPainter)
  {
    if(_internal->_prerenderer.isValid())
    {
      _internal->_genDoc = _internal->_prerenderer.generate();
      if(_internal->_genDoc)
      {
        ORPrintRender prender;
        prender.setupPrinter(_internal->_genDoc, prtThis);
        if (boolSetupPrinter)     // 1st call
        {
          retval = multiPainter->begin(multiPrinter);
          if (retval == false)
          {
            delete multiPainter;
            multiPrinter = 0;
            multiPainter = 0;
          }
        }
        else                      // 2nd or later print call
          retval = multiPrinter->newPage();
        if (retval)
          retval = render(multiPainter, multiPrinter);

        delete _internal->_genDoc;
        _internal->_genDoc = 0;
      }
    }
  }
  else
  {
    if(_internal != 0)
    {
      if (prtThis == 0)
      {
        prtThis = new ReportPrinter(QPrinter::HighResolution);
        localPrinter = true;
      }

      if(_internal->_prerenderer.isValid())
      {
        _internal->_genDoc = _internal->_prerenderer.generate();
        if(_internal->_genDoc)
        {
          retval = true;
          ORPrintRender prender;
          prender.setupPrinter(_internal->_genDoc, prtThis);

          if (showPreview)
          {
            PreviewDialog preview(_internal->_genDoc, prtThis, parent);
            if (preview.exec() == QDialog::Rejected)
              return false;
          }

          QPrintDialog pd(prtThis);
          if (boolSetupPrinter)
          {
            pd.setMinMax(1, _internal->_genDoc->pages());
            retval = (pd.exec() == QDialog::Accepted);
          }
  
          if(retval == true)
            retval = render(0, prtThis);

          delete _internal->_genDoc;
          _internal->_genDoc = 0;
        }
      }

      if (localPrinter && prtThis != 0)
        delete prtThis;
    }
  }

  return retval;
}
Пример #2
0
void Album::print()
{
    if (_scores.isEmpty())
        return;
    loadScores();
    QPrinter printer(QPrinter::HighResolution);

    Score* score = _scores[0]->score;
    printer.setCreator("MuseScore Version: " MSC_VERSION);
    printer.setFullPage(true);
    printer.setColorMode(QPrinter::Color);
    printer.setDoubleSidedPrinting(score->pageFormat()->twosided());
    printer.setOutputFormat(QPrinter::NativeFormat);

    QPrintDialog pd(&printer, 0);
    if (!pd.exec())
        return;

    QPainter painter(&printer);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);
    double mag = printer.logicalDpiX() / MScore::DPI;
    painter.scale(mag, mag);

    int fromPage = printer.fromPage() - 1;
    int toPage   = printer.toPage()   - 1;
    if (fromPage < 0)
        fromPage = 0;
    if (toPage < 0)
        toPage = 100000;

    //
    // start pageOffset with configured offset of
    // first score
    //
    int pageOffset = 0;
    if (_scores[0]->score)
        pageOffset = _scores[0]->score->pageNumberOffset();

    foreach(AlbumItem* item, _scores) {
        Score* score = item->score;
        if (score == 0)
            continue;
        score->setPrinting(true);
        //
        // here we ignore the configured page offset
        //
        int oldPageOffset = score->pageNumberOffset();
        score->setPageNumberOffset(pageOffset);
        score->doLayout();
        const QList<Page*> pl = score->pages();
        int pages    = pl.size();
        for (int n = 0; n < pages; ++n) {
            if (n)
                printer.newPage();
            Page* page = pl.at(n);

            QRectF fr = page->abbox();
            QList<Element*> ell = page->items(fr);
            qStableSort(ell.begin(), ell.end(), elementLessThan);
            foreach(const Element* e, ell) {
                e->itemDiscovered = 0;
                if (!e->visible())
                    continue;
                QPointF pos(e->pagePos());
                painter.translate(pos);
                e->draw(&painter);
                painter.translate(-pos);
            }
        }
/***********************************************************************
// compress a block of data.
************************************************************************/
static NOINLINE unsigned
do_compress(const uint8_t* in, unsigned in_len,
            uint8_t* out, unsigned* out_len,
            void* wrkmem)
{
    register const uint8_t* ip;
    uint8_t* op;
    const uint8_t* const in_end = in + in_len;
    const uint8_t* const ip_end = in + in_len - M2_MAX_LEN - 5;
    const uint8_t* ii;
    const void* *const dict = (const void**) wrkmem;

    op = out;
    ip = in;
    ii = ip;

    ip += 4;
    for (;;) {
        register const uint8_t* m_pos;
        unsigned m_off;
        unsigned m_len;
        unsigned dindex;

        D_INDEX1(dindex,ip);
        GINDEX(m_pos,m_off,dict,dindex,in);
        if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET))
            goto literal;
#if 1
        if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3])
            goto try_match;
        D_INDEX2(dindex,ip);
#endif
        GINDEX(m_pos,m_off,dict,dindex,in);
        if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET))
            goto literal;
        if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3])
            goto try_match;
        goto literal;

try_match:
#if 1 && defined(LZO_UNALIGNED_OK_2)
        if (* (const lzo_ushortp) m_pos != * (const lzo_ushortp) ip)
#else
        if (m_pos[0] != ip[0] || m_pos[1] != ip[1])
#endif
        {
        } else {
            if (m_pos[2] == ip[2]) {
#if 0
                if (m_off <= M2_MAX_OFFSET)
                    goto match;
                if (lit <= 3)
                    goto match;
                if (lit == 3) {			  /* better compression, but slower */
                    assert(op - 2 > out);
                    op[-2] |= (uint8_t)(3);
                    *op++ = *ii++;
                    *op++ = *ii++;
                    *op++ = *ii++;
                    goto code_match;
                }
                if (m_pos[3] == ip[3])
#endif
                    goto match;
            }
            else {
                /* still need a better way for finding M1 matches */
#if 0
                /* a M1 match */
#if 0
                if (m_off <= M1_MAX_OFFSET && lit > 0 && lit <= 3)
#else
                if (m_off <= M1_MAX_OFFSET && lit == 3)
#endif
                {
                    register unsigned t;

                    t = lit;
                    assert(op - 2 > out);
                    op[-2] |= (uint8_t)(t);
                    do *op++ = *ii++;
                    while (--t > 0);
                    assert(ii == ip);
                    m_off -= 1;
                    *op++ = (uint8_t)(M1_MARKER | ((m_off & 3) << 2));
                    *op++ = (uint8_t)(m_off >> 2);
                    ip += 2;
                    goto match_done;
                }
#endif
            }
        }

        /* a literal */
literal:
        UPDATE_I(dict, 0, dindex, ip, in);
        ++ip;
        if (ip >= ip_end)
            break;
        continue;

        /* a match */
match:
        UPDATE_I(dict, 0, dindex, ip, in);
        /* store current literal run */
        if (pd(ip, ii) > 0) {
            register unsigned t = pd(ip, ii);

            if (t <= 3) {
                assert(op - 2 > out);
                op[-2] |= (uint8_t)(t);
            }
            else if (t <= 18)
                *op++ = (uint8_t)(t - 3);
            else {
                register unsigned tt = t - 18;

                *op++ = 0;
                while (tt > 255) {
                    tt -= 255;
                    *op++ = 0;
                }
                assert(tt > 0);
                *op++ = (uint8_t)(tt);
            }
            do *op++ = *ii++;
            while (--t > 0);
        }

        /* code the match */
        assert(ii == ip);
        ip += 3;
        if (m_pos[3] != *ip++ || m_pos[4] != *ip++ || m_pos[5] != *ip++
                || m_pos[6] != *ip++ || m_pos[7] != *ip++ || m_pos[8] != *ip++
#ifdef LZO1Y
                || m_pos[ 9] != *ip++ || m_pos[10] != *ip++ || m_pos[11] != *ip++
                || m_pos[12] != *ip++ || m_pos[13] != *ip++ || m_pos[14] != *ip++
#endif
           ) {
            --ip;
            m_len = pd(ip, ii);
            assert(m_len >= 3);
            assert(m_len <= M2_MAX_LEN);

            if (m_off <= M2_MAX_OFFSET) {
                m_off -= 1;
#if defined(LZO1X)
                *op++ = (uint8_t)(((m_len - 1) << 5) | ((m_off & 7) << 2));
                *op++ = (uint8_t)(m_off >> 3);
#elif defined(LZO1Y)
                *op++ = (uint8_t)(((m_len + 1) << 4) | ((m_off & 3) << 2));
                *op++ = (uint8_t)(m_off >> 2);
#endif
            }
            else if (m_off <= M3_MAX_OFFSET) {
Пример #4
0
void gameDialog::UpdateCameraPosition(void) {
	static double last = 0.0;
	double delta = (gCurrentFrameTime - last)*20; // Number of blocks/s
	last = gCurrentFrameTime;
	if (delta > fRequestedCameraDistance - fCameraDistance)
		delta = fRequestedCameraDistance - fCameraDistance;
	// If the requested camera distance is bigger than the current, then slowly move out.
	if (fRequestedCameraDistance > fCameraDistance)
		fCameraDistance += delta;
	else
		fCameraDistance = fRequestedCameraDistance;
	Options::fgOptions.fCameraDistance = fRequestedCameraDistance; // Make sure it is saved
	if (fCameraDistance == 0.0f)
		return;
	ChunkCoord cc;
	gPlayer.GetChunkCoord(&cc);

	glm::vec3 playerOffset = gPlayer.GetOffsetToChunk();
	glm::vec3 pd(playerOffset.x, -playerOffset.z, playerOffset.y); // Same offset, but in Ephenation server coordinates

	glm::mat4 T1 = glm::translate(glm::mat4(1), playerOffset);
	glm::mat4 R1 = glm::rotate(glm::mat4(1), _angleVert, glm::vec3(-1.0f, 0.0f, 0.0f));
	glm::mat4 R2 = glm::rotate(glm::mat4(1), _angleHor, glm::vec3(0.0f, -1.0f, 0.0f));
	glm::mat4 T2 = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, fCameraDistance));
	glm::vec4 pos = T1 * R2 * R1 * T2 * glm::vec4(0,0,0,1);

	glm::vec3 cd(pos.x, -pos.z, pos.y); // Camera delta in Ephenation coordinates.

	// printf("Player: %.2f, %.2f, %.2f. Camera: %.2f,%.2f,%.2f\n", pd.x, pd.y, pd.z, cd.x, cd.y, cd.z);
	glm::vec3 norm = glm::normalize(cd-pd); // Vector from player to camera

	const float step = 0.1f;
	for (float d = step; d <= this->fCameraDistance; d = d + step) {
		signed long long x, y, z;
		x = gPlayer.x + (signed long long)(d * norm.x*BLOCK_COORD_RES);
		y = gPlayer.y + (signed long long)(d * norm.y*BLOCK_COORD_RES);
		z = gPlayer.z + (signed long long)(d * norm.z*BLOCK_COORD_RES);
		if (chunk::GetChunkAndBlock(x, y, z) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
		if (chunk::GetChunkAndBlock(x+1, y, z) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
		if (chunk::GetChunkAndBlock(x, y+1, z) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
		if (chunk::GetChunkAndBlock(x, y, z+1) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
		if (chunk::GetChunkAndBlock(x-1, y, z) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
		if (chunk::GetChunkAndBlock(x, y-1, z) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
		if (chunk::GetChunkAndBlock(x, y, z-1) != BT_Air) {
			this->fCameraDistance = d-step;
			break;
		}
	}
}
IGL_INLINE
void igl::copyleft::cgal::order_facets_around_edge(
  const Eigen::PlainObjectBase<DerivedV>& V,
  const Eigen::PlainObjectBase<DerivedF>& F,
  size_t s,
  size_t d, 
  const std::vector<int>& adj_faces,
  const Eigen::PlainObjectBase<DerivedV>& pivot_point,
  Eigen::PlainObjectBase<DerivedI>& order)
{
  assert(V.cols() == 3);
  assert(F.cols() == 3);
  assert(pivot_point.cols() == 3);
  auto signed_index_to_index = [&](int signed_idx)
  {
      return abs(signed_idx) -1;
  };
  auto get_opposite_vertex_index = [&](size_t fid) -> typename DerivedF::Scalar
  {
      typedef typename DerivedF::Scalar Index;
      if (F(fid, 0) != (Index)s && F(fid, 0) != (Index)d) return F(fid, 0);
      if (F(fid, 1) != (Index)s && F(fid, 1) != (Index)d) return F(fid, 1);
      if (F(fid, 2) != (Index)s && F(fid, 2) != (Index)d) return F(fid, 2);
      assert(false);
      // avoid warning
      return -1;
  };

  {
    // Check if s, d and pivot are collinear.
    typedef CGAL::Exact_predicates_exact_constructions_kernel K;
    K::Point_3 ps(V(s,0), V(s,1), V(s,2));
    K::Point_3 pd(V(d,0), V(d,1), V(d,2));
    K::Point_3 pp(pivot_point(0,0), pivot_point(0,1), pivot_point(0,2));
    if (CGAL::collinear(ps, pd, pp)) {
        throw std::runtime_error(
                "Pivot point is collinear with the outer edge!");
    }
  }

  const size_t N = adj_faces.size();
  const size_t num_faces = N + 1; // N adj faces + 1 pivot face

  // Because face indices are used for tie breaking, the original face indices
  // in the new faces array must be ascending.
  auto comp = [&](int i, int j) 
  {
    return signed_index_to_index(adj_faces[i]) <
      signed_index_to_index(adj_faces[j]);
  };
  std::vector<size_t> adj_order(N);
  for (size_t i=0; i<N; i++) adj_order[i] = i;
  std::sort(adj_order.begin(), adj_order.end(), comp);

  DerivedV vertices(num_faces + 2, 3);
  for (size_t i=0; i<N; i++) 
  {
    const size_t fid = signed_index_to_index(adj_faces[adj_order[i]]);
    vertices.row(i) = V.row(get_opposite_vertex_index(fid));
  }
  vertices.row(N  ) = pivot_point;
  vertices.row(N+1) = V.row(s);
  vertices.row(N+2) = V.row(d);

  DerivedF faces(num_faces, 3);
  for (size_t i=0; i<N; i++)
  {
    if (adj_faces[adj_order[i]] < 0) 
    {
      faces(i,0) = N+1; // s
      faces(i,1) = N+2; // d
      faces(i,2) = i  ;
    } else 
    {
      faces(i,0) = N+2; // d
      faces(i,1) = N+1; // s
      faces(i,2) = i  ;
    }
  }
  // Last face is the pivot face.
  faces(N, 0) = N+1;
  faces(N, 1) = N+2;
  faces(N, 2) = N;

  std::vector<int> adj_faces_with_pivot(num_faces);
  for (size_t i=0; i<num_faces; i++)
  {
    if ((size_t)faces(i,0) == N+1 && (size_t)faces(i,1) == N+2)
    {
        adj_faces_with_pivot[i] = int(i+1) * -1;
    } else
    {
        adj_faces_with_pivot[i] = int(i+1);
    }
  }

  DerivedI order_with_pivot;
  order_facets_around_edge(
    vertices, faces, N+1, N+2, adj_faces_with_pivot, order_with_pivot);

  assert((size_t)order_with_pivot.size() == num_faces);
  order.resize(N);
  size_t pivot_index = num_faces + 1;
  for (size_t i=0; i<num_faces; i++)
  {
    if ((size_t)order_with_pivot[i] == N)
    {
      pivot_index = i;
      break;
    }
  }
  assert(pivot_index < num_faces);

  for (size_t i=0; i<N; i++)
  {
    order[i] = adj_order[order_with_pivot[(pivot_index+i+1)%num_faces]];
  }
}
Пример #6
0
void displayPrivate::print(bool showPreview)
{
  int numCopies = 1;

  ParameterList params;
  if(!_parent->setParams(params))
    return;

  XSqlQuery report;
  report.prepare("SELECT report_grade, report_source "
                 "  FROM report "
                 " WHERE (report_name=:report_name)"
                 " ORDER BY report_grade DESC LIMIT 1");
  report.bindValue(":report_name", reportName);
  report.exec();
  QDomDocument _doc;
  if (report.first())
  {
    QString errorMessage;
    int     errorLine;

    if (!_doc.setContent(report.value("report_source").toString(), &errorMessage, &errorLine))
    {
      QMessageBox::critical(_parent, ::display::tr("Error Parsing Report"),
        ::display::tr("There was an error Parsing the report definition. %1 %2").arg(errorMessage).arg(errorLine));
      return;
    }
  }
  else
  {
    QMessageBox::critical(_parent, ::display::tr("Report Not Found"),
      ::display::tr("The report %1 does not exist.").arg(reportName));
    return;
  }

  ORPreRender pre;
  pre.setDom(_doc);
  pre.setParamList(params);
  ORODocument * doc = pre.generate();

  if(doc)
  {
    QPrinter printer(QPrinter::HighResolution);
    printer.setNumCopies( numCopies );

    ORPrintRender render;
    render.setupPrinter(doc, &printer);

    if(showPreview)
    {
      PreviewDialog preview (doc, &printer, _parent);
      if (preview.exec() == QDialog::Rejected)
        return;
    }

    QPrintDialog pd(&printer);
    pd.setMinMax(1, doc->pages());
    if(pd.exec() == QDialog::Accepted)
    {
      render.setPrinter(&printer);
      render.render(doc);
    }
    delete doc;
  }
}
Пример #7
0
void printChecks::sPrint()
{
  QList<int> printedChecks;

  ParameterList params;
  params.append("bankaccnt_id", _bankaccnt->id());

  bool setup = true;

  XSqlQuery checks;
  checks.prepare( "SELECT checkhead_id, checkhead_number, report_name "
                  "FROM checkhead, bankaccnt, form, report "
                  "WHERE ( (checkhead_bankaccnt_id=bankaccnt_id)"
                  " AND (bankaccnt_check_form_id=form_id)"
                  " AND (form_report_id=report_id)"
                  " AND (NOT checkhead_printed) "
                  " AND (NOT checkhead_void) "
                  " AND (bankaccnt_id=:bankaccnt_id) ) "
                  "ORDER BY checkhead_number "
                  "LIMIT :numtoprint; " );
  checks.bindValue(":bankaccnt_id", _bankaccnt->id());
  checks.bindValue(":numtoprint", _numberOfChecks->value());
  checks.exec();
/*
  bool userCanceled = false;
  if (orReport::beginMultiPrint(&printer, userCanceled) == false)
  {
    if(!userCanceled)
      systemError(this, tr("<p>Could not initialize printing system for "
			   "multiple reports."));
    return;
  }
*/
  QDomDocument docReport;
  QPrinter printer(QPrinter::HighResolution);
  ORPrintRender render;
  while (checks.next())
  {
    if(setup)
    {
      // get the report definition out of the database
      // this should somehow be condensed into a common code call or something
      // in the near future to facilitate easier conversion in other places
      // of the application to use the new rendering engine directly
      XSqlQuery report;
      report.prepare( "SELECT report_source "
                      "  FROM report "
                      " WHERE (report_name=:report_name) "
                      "ORDER BY report_grade DESC LIMIT 1;" );
      report.bindValue(":report_name", checks.value("report_name").toString());
      report.exec();
      if (report.first())
      {
        QString errorMessage;
        int     errorLine;
  
        if (!docReport.setContent(report.value("report_source").toString(), &errorMessage, &errorLine))
        {
          systemError(this, errorMessage, __FILE__, __LINE__);
          return;
        }
      }
      else
      {
        systemError(this, report.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
      // end getting the report definition out the database

      if(_setCheckNumber != -1 && _setCheckNumber != _nextCheckNum->text().toInt())
      {
        q.prepare("SELECT setNextCheckNumber(:bankaccnt_id, :nextCheckNumber) AS result;");
        q.bindValue(":bankaccnt_id", _bankaccnt->id());
        q.bindValue(":nextCheckNumber", _nextCheckNum->text().toInt());
        q.exec();
        if (q.first())
        {
          int result = q.value("result").toInt();
          if (result < 0)
          {
            systemError(this, storedProcErrorLookup("setNextCheckNumber", result),
                        __FILE__, __LINE__);
            return;
          }
        }
        else if (q.lastError().type() != QSqlError::NoError)
        {
          systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
          return;
        }
      }
    }

    q.prepare("UPDATE checkhead SET checkhead_number=fetchNextCheckNumber(checkhead_bankaccnt_id)"
              " WHERE(checkhead_id=:checkhead_id);");
    q.bindValue(":checkhead_id", checks.value("checkhead_id").toInt());
    q.exec();
    if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    ParameterList params;
    params.append("checkhead_id", checks.value("checkhead_id").toInt());
    params.append("apchk_id", checks.value("checkhead_id").toInt());

    ORPreRender pre;
    pre.setDom(docReport);
    pre.setParamList(params);
    ORODocument * doc = pre.generate();

    if(setup)
    {
      render.setupPrinter(doc, &printer);

      QPrintDialog pd(&printer);
      pd.setMinMax(1, doc->pages());
      if(pd.exec() != QDialog::Accepted)
        return;
      render.setPrinter(&printer);
      setup = false;
    }

    render.render(doc);
    printedChecks.append(checks.value("checkhead_id").toInt());

    int page_num = 1;
    while(page_num < doc->pages())
    {
      page_num++;

      XSqlQuery qq;
      qq.prepare("INSERT INTO checkhead"
                 "      (checkhead_recip_id, checkhead_recip_type,"
                 "       checkhead_bankaccnt_id, checkhead_printed,"
                 "       checkhead_checkdate, checkhead_number,"
                 "       checkhead_amount, checkhead_void,"
                 "       checkhead_misc,"
                 "       checkhead_for, checkhead_notes,"
                 "       checkhead_curr_id, checkhead_deleted) "
                 "SELECT checkhead_recip_id, checkhead_recip_type,"
                 "       checkhead_bankaccnt_id, TRUE,"
                 "       checkhead_checkdate, fetchNextCheckNumber(checkhead_bankaccnt_id),"
                 "       checkhead_amount, TRUE, TRUE,"
                 "       'Continuation of Check #'||checkhead_number,"
                 "       'Continuation of Check #'||checkhead_number,"
                 "       checkhead_curr_id, TRUE"
                 "  FROM checkhead"
                 " WHERE(checkhead_id=:checkhead_id);");
      qq.bindValue(":checkhead_id", checks.value("checkhead_id").toInt());
      if(!qq.exec())
      {
        systemError(this, "Received error but will continue anyway:\n"+qq.lastError().databaseText(), __FILE__, __LINE__);
      }
    }
  }
  //orReport::endMultiPrint(&printer);
  if (checks.lastError().type() != QSqlError::None)
  {
    systemError(this, checks.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if(!printedChecks.empty())
  {
    QList<int>::iterator it;

    if ( QMessageBox::question(this, tr("All Checks Printed"),
			       tr("<p>Did all the Checks print successfully?"),
				QMessageBox::Yes,
				QMessageBox::No | QMessageBox::Default) == QMessageBox::Yes)
    {
      XSqlQuery postCheck;
      postCheck.prepare( "SELECT markCheckAsPrinted(:checkhead_id) AS result;");
      for( it = printedChecks.begin(); it != printedChecks.end(); ++it)
      {
        postCheck.bindValue(":checkhead_id", (*it));
        postCheck.exec();
	if (postCheck.first())
	{
	  int result = postCheck.value("result").toInt();
	  if (result < 0)
	  {
	    systemError(this, storedProcErrorLookup("markCheckAsPrinted",
						   result), __FILE__, __LINE__);
	    return;
	  }
	}
	else if (postCheck.lastError().type() != QSqlError::None)
	{
	  systemError(this, postCheck.lastError().databaseText(), __FILE__, __LINE__);
	  return;
	}
      }
    }
    else
    {
      printChecksReview newdlg(this, "", TRUE);
      QString query = QString( "SELECT checkhead_id, checkhead_number"
                               "  FROM checkhead"
                               " WHERE (checkhead_id IN (" );
      bool first = true;
      for( it = printedChecks.begin(); it != printedChecks.end(); ++it)
      {
        if(!first)
          query += ",";
        query += QString::number((*it)); 
        first = false;
      }
      query += ") ); ";
      newdlg._checks->populate(query);
      newdlg.sSelectAll();
      newdlg.sMarkPrinted();
      newdlg._checks->clearSelection();
      newdlg.exec();
    }
  }
  else
    QMessageBox::information( this, tr("No Checks Printed"),
			     tr("<p>No Checks were printed for the selected "
				"Bank Account.") );

  omfgThis->sChecksUpdated(_bankaccnt->id(), -1, TRUE);
  sHandleBankAccount(_bankaccnt->id());
}
Пример #8
0
Файл: tree2.c Проект: Nos-/htw
void dispTree (tleaf* tree, void (*pd)(void*))
{
  if(tree->p[0]) dispTree(tree->p[0],pd);
  pd(tree->pData);
  if(tree->p[1]) dispTree(tree->p[1],pd);
}
static void smbconf_txt_flush_cache(struct smbconf_ctx *ctx)
{
	talloc_free(pd(ctx)->cache);
	pd(ctx)->cache = NULL;
}
Пример #10
0
bool PrintFile(const WCHAR *fileName, const WCHAR *printerName, bool displayErrors, const WCHAR *settings)
{
    if (!HasPermission(Perm_PrinterAccess))
        return false;

    ScopedMem<WCHAR> fileName2(path::Normalize(fileName));
    BaseEngine *engine = EngineManager::CreateEngine(!gUseEbookUI, fileName2);
    if (!engine || !engine->IsPrintingAllowed()) {
        if (displayErrors)
            MessageBox(NULL, _TR("Cannot print this file"), _TR("Printing problem."), MB_ICONEXCLAMATION | MB_OK | (IsUIRightToLeft() ? MB_RTLREADING : 0));
        return false;
    }

    HANDLE printer;
    bool ok = OpenPrinter((WCHAR *)printerName, &printer, NULL);
    if (!ok) {
        if (displayErrors)
            MessageBox(NULL, _TR("Printer with given name doesn't exist"), _TR("Printing problem."), MB_ICONEXCLAMATION | MB_OK | (IsUIRightToLeft() ? MB_RTLREADING : 0));
        return false;
    }

    // get printer driver information
    DWORD needed = 0;
    GetPrinter(printer, 2, NULL, 0, &needed);
    ScopedMem<PRINTER_INFO_2> infoData((PRINTER_INFO_2 *)AllocArray<BYTE>(needed));
    if (infoData)
        ok = GetPrinter(printer, 2, (LPBYTE)infoData.Get(), needed, &needed);
    if (!ok || !infoData || needed <= sizeof(PRINTER_INFO_2)) goto Exit;

    LONG structSize = DocumentProperties(NULL,
        printer,                /* Handle to our printer. */
        (WCHAR *)printerName,   /* Name of the printer. */ 
        NULL,                   /* Asking for size, so */
        NULL,                   /* these are not used. */
        0);                     /* Zero returns buffer size. */
    if (structSize < sizeof(DEVMODE)) {
        // If failure, inform the user, cleanup and return failure.
        if (displayErrors)
            MessageBox(NULL, _TR("Could not obtain Printer properties"), _TR("Printing problem."), MB_ICONEXCLAMATION | MB_OK | (IsUIRightToLeft() ? MB_RTLREADING : 0));
        goto Exit;
    }
    LPDEVMODE devMode = (LPDEVMODE)malloc(structSize);
    if (!devMode) goto Exit;

    // Get the default DevMode for the printer and modify it for your needs.
    LONG returnCode = DocumentProperties(NULL,
        printer,
        (WCHAR *)printerName,
        devMode,        /* The address of the buffer to fill. */
        NULL,           /* Not using the input buffer. */
        DM_OUT_BUFFER); /* Have the output buffer filled. */
    if (IDOK != returnCode) {
        // If failure, inform the user, cleanup and return failure.
        if (displayErrors)
            MessageBox(NULL, _TR("Could not obtain Printer properties"), _TR("Printing problem."), MB_ICONEXCLAMATION | MB_OK | (IsUIRightToLeft() ? MB_RTLREADING : 0));
        goto Exit;
    }

    ClosePrinter(printer);
    printer = NULL;

    {
        Print_Advanced_Data advanced;
        Vec<PRINTPAGERANGE> ranges;
        ApplyPrintSettings(settings, engine->PageCount(), ranges, advanced);

        PrintData pd(engine, infoData, devMode, ranges, advanced);
        ok = PrintToDevice(pd);
        if (!ok && displayErrors)
            MessageBox(NULL, _TR("Couldn't initialize printer"), _TR("Printing problem."),
                MB_ICONEXCLAMATION | MB_OK | (IsUIRightToLeft() ? MB_RTLREADING : 0));
    }

Exit:
    free(devMode);
    if (printer)
        ClosePrinter(printer);
    delete engine;
    return ok;
}
int main(int argc, char const *argv[])
{
    if (argc != 7)
    {
        std::cerr << "Usage: itqlsh_test data_path lsh_file param.L param.N benchmark_file hamming" << std::endl;
        return -1;
    }
    std::cout << "Example of using Iterative Quantization" << std::endl << std::endl;
    typedef float DATATYPE;
    std::cout << "LOADING DATA ..." << std::endl;
    lshbox::timer timer;
    lshbox::Matrix<DATATYPE> data(argv[1]);
    std::cout << "LOAD TIME: " << timer.elapsed() << "s." << std::endl;
    std::cout << "CONSTRUCTING INDEX ..." << std::endl;
    timer.restart();
    std::string file(argv[2]);
    bool use_index = false;
    lshbox::itqLsh<DATATYPE> mylsh;
    if (use_index)
    {
        mylsh.load(file);
    }
    else
    {
        lshbox::itqLsh<DATATYPE>::Parameter param;
        param.L = atoi(argv[3]);
        param.D = data.getDim();
        param.N = atoi(argv[4]);
        param.S = 10000;
        param.I = 50;
        mylsh.reset(param);
        mylsh.train(data);
        mylsh.hash(data);
    }
    mylsh.save(file);
    std::cout << "CONSTRUCTING TIME: " << timer.elapsed() << "s." << std::endl;
    std::cout << "LOADING BENCHMARK ..." << std::endl;
    timer.restart();
    lshbox::Matrix<DATATYPE>::Accessor accessor(data);
    lshbox::Metric<DATATYPE> metric(data.getDim(), L2_DIST);
    lshbox::Benchmark bench;
    std::string benchmark(argv[5]);
    bench.load(benchmark);
    unsigned K = bench.getK();
    lshbox::Scanner<lshbox::Matrix<DATATYPE>::Accessor> scanner(
        accessor,
        metric,
        K
    );
    std::cout << "LOADING TIME: " << timer.elapsed() << "s." << std::endl;
    std::cout << "RUNING QUERY ..." << std::endl;
    lshbox::Stat cost, recall;
    lshbox::progress_display pd(bench.getQ());
    timer.restart();
    for (unsigned i = 0; i != bench.getQ(); ++i)
    {
        mylsh.query(data[bench.getQuery(i)], scanner, atoi(argv[6]));
        recall << bench.getAnswer(i).recall(scanner.topk());
        cost << float(scanner.cnt()) / float(data.getSize());
        ++pd;
    }
    std::cout << "MEAN QUERY TIME: " << timer.elapsed() / bench.getQ() << "s." << std::endl;
    std::cout << "RECALL   : " << recall.getAvg() << " +/- " << recall.getStd() << std::endl;
    std::cout << "COST     : " << cost.getAvg() << " +/- " << cost.getStd() << std::endl;
}
Пример #12
0
// Turns LLL tree into tree of code fragments
programData opcodeify(Node node,
                      programAux aux=Aux(),
                      programVerticalAux vaux=verticalAux()) {
    std::string symb = "_"+mkUniqueToken();
    Metadata m = node.metadata;
    // Numbers
    if (node.type == TOKEN) {
        return pd(aux, nodeToNumeric(node), 1);
    }
    else if (node.val == "ref" || node.val == "get" || node.val == "set") {
        std::string varname = node.args[0].val;
        // Determine reference to variable
        if (!aux.vars.count(node.args[0].val)) {
            aux.vars[node.args[0].val] = utd(aux.nextVarMem);
            aux.nextVarMem += 32;
        }
        Node varNode = tkn(aux.vars[varname], m);
        //std::cerr << varname << " " << printSimple(varNode) << "\n";
        // Set variable
        if (node.val == "set") {
            programData sub = opcodeify(node.args[1], aux, vaux);
            if (!sub.outs)
                err("Value to set variable must have nonzero arity!", m);
            // What if we are setting a stack variable?
            if (vaux.dupvars.count(node.args[0].val)) {
                int h = vaux.height - vaux.dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                Node nodelist[] = {
                    sub.code,
                    token("SWAP"+unsignedToDecimal(h), m),
                    token("POP", m)
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
            // Setting a memory variable
            else {
                Node nodelist[] = {
                    sub.code,
                    varNode,
                    token("MSTORE", m),
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
        }
        // Get variable
        else if (node.val == "get") {
            // Getting a stack variable
            if (vaux.dupvars.count(node.args[0].val)) {
                 int h = vaux.height - vaux.dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                return pd(aux, token("DUP"+unsignedToDecimal(h)), 1);                   
            }
            // Getting a memory variable
            else {
                Node nodelist[] = 
                     { varNode, token("MLOAD", m) };
                return pd(aux, multiToken(nodelist, 2, m), 1);
            }
        }
        // Refer variable
        else if (node.val == "ref") {
            if (vaux.dupvars.count(node.args[0].val))
                err("Cannot ref stack variable!", m);
            return pd(aux, varNode, 1);
        }
    }
    // Comments do nothing
    else if (node.val == "comment") {
        return pd(aux, astnode("_", m), 0);
    }
    // Custom operation sequence
    // eg. (ops bytez id msize swap1 msize add 0 swap1 mstore) == alloc
    if (node.val == "ops") {
        std::vector<Node>  subs2;
        int depth = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            std::string op = upperCase(node.args[i].val);
            if (node.args[i].type == ASTNODE || opinputs(op) == -1) {
                programVerticalAux vaux2 = vaux;
                vaux2.height = vaux.height - i - 1 + node.args.size();
                programData sub = opcodeify(node.args[i], aux, vaux2);
                aux = sub.aux;
                depth += sub.outs;
                subs2.push_back(sub.code);
            }
            else {
                subs2.push_back(token(op, m));
                depth += opoutputs(op) - opinputs(op);
            }
        }
        if (depth < 0 || depth > 1) err("Stack depth mismatch", m);
        return pd(aux, astnode("_", subs2, m), 0);
    }
    // Code blocks
    if (node.val == "lll" && node.args.size() == 2) {
        if (node.args[1].val != "0") aux.allocUsed = true;
        std::vector<Node> o;
        o.push_back(finalize(opcodeify(node.args[0])));
        programData sub = opcodeify(node.args[1], aux, vaux);
        Node code = astnode("____CODE", o, m);
        Node nodelist[] = {
            token("$begincode"+symb+".endcode"+symb, m), token("DUP1", m),
            token("$begincode"+symb, m), sub.code, token("CODECOPY", m),
            token("$endcode"+symb, m), token("JUMP", m),
            token("~begincode"+symb, m), code, 
            token("~endcode"+symb, m), token("JUMPDEST", m)
        };
        return pd(sub.aux, multiToken(nodelist, 11, m), 1);
    }
    // Stack variables
    if (node.val == "with") {
        programData initial = opcodeify(node.args[1], aux, vaux);
        programVerticalAux vaux2 = vaux;
        vaux2.dupvars[node.args[0].val] = vaux.height;
        vaux2.height += 1;
        if (!initial.outs)
            err("Initial variable value must have nonzero arity!", m);
        programData sub = opcodeify(node.args[2], initial.aux, vaux2);
        Node nodelist[] = {
            initial.code,
            sub.code
        };
        programData o = pd(sub.aux, multiToken(nodelist, 2, m), sub.outs);
        if (sub.outs)
            o.code.args.push_back(token("SWAP1", m));
        o.code.args.push_back(token("POP", m));
        return o;
    }
    // Seq of multiple statements
    if (node.val == "seq") {
        std::vector<Node> children;
        int lastOut = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            programData sub = opcodeify(node.args[i], aux, vaux);
            aux = sub.aux;
            if (sub.outs == 1) {
                if (i < node.args.size() - 1) sub.code = popwrap(sub.code);
                else lastOut = 1;
            }
            children.push_back(sub.code);
        }
        return pd(aux, astnode("_", children, m), lastOut);
    }
    // 2-part conditional (if gets rewritten to unless in rewrites)
    else if (node.val == "unless" && node.args.size() == 2) {
        programData cond = opcodeify(node.args[0], aux, vaux);
        programData action = opcodeify(node.args[1], cond.aux, vaux);
        aux = action.aux;
        if (!cond.outs) err("Condition of if/unless statement has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            cond.code,
            token("$endif"+symb, m), token("JUMPI", m),
            action.code,
            token("~endif"+symb, m), token("JUMPDEST", m)
        };
        return pd(aux, multiToken(nodelist, 6, m), 0);
    }
    // 3-part conditional
    else if (node.val == "if" && node.args.size() == 3) {
        programData ifd = opcodeify(node.args[0], aux, vaux);
        programData thend = opcodeify(node.args[1], ifd.aux, vaux);
        programData elsed = opcodeify(node.args[2], thend.aux, vaux);
        aux = elsed.aux;
        if (!ifd.outs)
            err("Condition of if/unless statement has arity 0", m);
        // Handle cases where one conditional outputs something
        // and the other does not
        int outs = (thend.outs && elsed.outs) ? 1 : 0;
        if (thend.outs > outs) thend.code = popwrap(thend.code);
        if (elsed.outs > outs) elsed.code = popwrap(elsed.code);
        Node nodelist[] = {
            ifd.code,
            token("ISZERO", m),
            token("$else"+symb, m), token("JUMPI", m),
            thend.code,
            token("$endif"+symb, m), token("JUMP", m),
            token("~else"+symb, m), token("JUMPDEST", m),
            elsed.code,
            token("~endif"+symb, m), token("JUMPDEST", m)
        };
        return pd(aux, multiToken(nodelist, 12, m), outs);
    }
    // While (rewritten to this in rewrites)
    else if (node.val == "until") {
        programData cond = opcodeify(node.args[0], aux, vaux);
        programData action = opcodeify(node.args[1], cond.aux, vaux);
        aux = action.aux;
        if (!cond.outs)
            err("Condition of while/until loop has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            token("~beg"+symb, m), token("JUMPDEST", m),
            cond.code,
            token("$end"+symb, m), token("JUMPI", m),
            action.code,
            token("$beg"+symb, m), token("JUMP", m),
            token("~end"+symb, m), token("JUMPDEST", m),
        };
        return pd(aux, multiToken(nodelist, 10, m));
    }
    // Memory allocations
    else if (node.val == "alloc") {
        programData bytez = opcodeify(node.args[0], aux, vaux);
        aux = bytez.aux;
        if (!bytez.outs)
            err("Alloc input has arity 0", m);
        aux.allocUsed = true;
        Node nodelist[] = {
            bytez.code,
            token("MSIZE", m), token("SWAP1", m), token("MSIZE", m),
            token("ADD", m), 
            token("0", m), token("SWAP1", m), token("MSTORE", m)
        };
        return pd(aux, multiToken(nodelist, 8, m), 1);
    }
    // All other functions/operators
    else {
        std::vector<Node>  subs2;
        int depth = opinputs(upperCase(node.val));
        if (depth == -1)
            err("Not a function or opcode: "+node.val, m);
        if ((int)node.args.size() != depth)
            err("Invalid arity for "+node.val, m);
        for (int i = node.args.size() - 1; i >= 0; i--) {
            programVerticalAux vaux2 = vaux;
            vaux2.height = vaux.height - i - 1 + node.args.size();
            programData sub = opcodeify(node.args[i], aux, vaux2);
            aux = sub.aux;
            if (!sub.outs)
                err("Input "+unsignedToDecimal(i)+" has arity 0", sub.code.metadata);
            subs2.push_back(sub.code);
        }
        subs2.push_back(token(upperCase(node.val), m));
        int outdepth = opoutputs(upperCase(node.val));
        return pd(aux, astnode("_", subs2, m), outdepth);
    }
}
Пример #13
0
Файл: tree1.c Проект: Nos-/htw
void dispTree (tleaf* tree, void (*pd)(void*))
{
  if(tree->pl) dispTree(tree->pl,pd);
  pd(tree->pData);
  if(tree->pr) dispTree(tree->pr,pd);
}
Пример #14
0
int main(int argc, char const *argv[])
{
    if (argc != 4)
    {
        std::cerr << "Usage: ./thlsh_test data_file lsh_file benchmark_file" << std::endl;
        return -1;
    }
    std::cout << "Example of using Thresholding LSH" << std::endl << std::endl;
    typedef float DATATYPE;
    std::cout << "LOADING DATA ..." << std::endl;
    lshbox::timer timer;
    lshbox::Matrix<DATATYPE> data(argv[1]);
    std::cout << "LOAD TIME: " << timer.elapsed() << "s." << std::endl;
    std::cout << "CONSTRUCTING INDEX ..." << std::endl;
    timer.restart();
    std::string file(argv[2]);
    bool use_index = false;
    lshbox::thLsh<DATATYPE> mylsh;
    if (use_index)
    {
        mylsh.load(file);
    }
    else
    {
        lshbox::thLsh<DATATYPE>::Parameter param;
        param.M = 521;
        param.L = 5;
        param.D = data.getDim();
        param.N = 12;
        param.Max = std::numeric_limits<float>::max();
        param.Min = - std::numeric_limits<float>::max();
        for (unsigned i = 0; i != data.getSize(); ++i)
        {
            for (unsigned j = 0; j != data.getDim(); ++j)
            {
                if (data[i][j] > param.Max)
                {
                    param.Max = data[i][j];
                }
                if (data[i][j] < param.Min)
                {
                    param.Min = data[i][j];
                }
            }
        }
        mylsh.reset(param);
        lshbox::progress_display pd(data.getSize());
        for (unsigned i = 0; i != data.getSize(); ++i)
        {
            mylsh.insert(i, data[i]);
            ++pd;
        }
    }
    mylsh.save(file);
    std::cout << "CONSTRUCTING TIME: " << timer.elapsed() << "s." << std::endl;
    std::cout << "LOADING BENCHMARK ..." << std::endl;
    timer.restart();
    lshbox::Matrix<DATATYPE>::Accessor accessor(data);
    lshbox::Metric<DATATYPE> metric(data.getDim(), L1_DIST);
    lshbox::Benchmark bench;
    std::string benchmark(argv[3]);
    bench.load(benchmark);
    unsigned K = bench.getK();
    lshbox::Scanner<lshbox::Matrix<DATATYPE>::Accessor> scanner(
        accessor,
        metric,
        K
    );
    std::cout << "LOADING TIME: " << timer.elapsed() << "s." << std::endl;
    std::cout << "RUNING QUERY ..." << std::endl;
    timer.restart();
    lshbox::Stat cost, recall, precision;
    lshbox::progress_display pd(bench.getQ());
    for (unsigned i = 0; i != bench.getQ(); ++i)
    {
        scanner.reset(data[bench.getQuery(i)]);
        mylsh.query(data[bench.getQuery(i)], scanner);
        scanner.topk().genTopk();
        recall << bench.getAnswer(i).recall(scanner.topk());
        recall << bench.getAnswer(i).precision(scanner.topk());
        cost << float(scanner.cnt()) / float(data.getSize());
        ++pd;
    }
    std::cout << "MEAN QUERY TIME: " << timer.elapsed() / bench.getQ() << "s." << std::endl;
    std::cout << "RECALL   : " << recall.getAvg() << " +/- " << recall.getStd() << std::endl;
    std::cout << "PRECISION: " << recall.getAvg() << " +/- " << recall.getStd() << std::endl;
    std::cout << "COST     : " << cost.getAvg() << " +/- " << cost.getStd() << std::endl;

    // scanner.reset(data[0]);
    // mylsh.query(data[0], scanner);
    // scanner.topk().genTopk();
    // std::vector<std::pair<float, unsigned> > res = scanner.topk().getTopk();
    // for (std::vector<std::pair<float, unsigned> >::iterator it = res.begin(); it != res.end(); ++it)
    // {
    //     std::cout << it->second << ": " << it->first << std::endl;
    // }
    // std::cout << "DISTANCE COMPARISON TIMES: " << scanner.cnt() << std::endl;
}
gcException IPCToolMain::installTool(gcRefPtr<UserCore::ToolInfo> info)
{
	gcString exe(info->getExe());
	gcString args(info->getArgs());

	if (!UTIL::FS::isValidFile(exe.c_str()))
		return gcException(ERR_INVALIDFILE);

	if (exe.size() > 0 && args == "GAME_LIBRARY")
	{
		size_t pos = exe.find_last_of(".bz2");

		if (pos == (exe.size()-1))
		{
			UTIL::FS::Path pd(exe.c_str(), "", true);
			pd += UTIL::FS::File(info->getName());

			gcString dest = pd.getFullPath();
			uint64 size = UTIL::FS::getFileSize(exe.c_str());

			try
			{
				UTIL::FS::FileHandle srcFh(exe.c_str(), UTIL::FS::FILE_READ);
				UTIL::FS::FileHandle destFh(dest.c_str(), UTIL::FS::FILE_WRITE);

				UTIL::MISC::BZ2Worker bz2(UTIL::MISC::BZ2_DECOMPRESS);

				srcFh.read(size, [&bz2, &destFh](const unsigned char* buff, uint32 size) -> bool
				{
					UTIL::FS::FileHandle *pDest = &destFh;

					bz2.write((const char*)buff, size, [&pDest](const unsigned char* buff, uint32 size) -> bool
					{
						pDest->write((const char*)buff, size);
						return false;
					});

					return false;
				});
			}
			catch (gcException &e)
			{
				return e;
			}

			info->overridePath(dest.c_str());
			UTIL::FS::delFile(exe.c_str());	
		}
		else
		{
			info->overridePath(exe.c_str());
		}
	}
	else if (args.find("PRECHECK_") == 0)
	{
		info->setInstalled();
	}
	else
	{
		return gcException(ERR_TOOLINSTALL, gcString("Un-supported tool install [{0}]", info->getName()));
	}

	return gcException(ERR_COMPLETED);
}
/**
 * get the list of share names defined in the configuration.
 */
static WERROR smbconf_txt_get_share_names(struct smbconf_ctx *ctx,
					  TALLOC_CTX *mem_ctx,
					  uint32_t *num_shares,
					  char ***share_names)
{
	uint32_t count;
	uint32_t added_count = 0;
	TALLOC_CTX *tmp_ctx = NULL;
	WERROR werr = WERR_OK;
	char **tmp_share_names = NULL;

	if ((num_shares == NULL) || (share_names == NULL)) {
		werr = WERR_INVALID_PARAM;
		goto done;
	}

	werr = smbconf_txt_load_file(ctx);
	if (!W_ERROR_IS_OK(werr)) {
		return werr;
	}

	tmp_ctx = talloc_stackframe();

	/* make sure "global" is always listed first,
	 * possibly after NULL section */

	if (smbconf_share_exists(ctx, NULL)) {
		werr = smbconf_add_string_to_array(tmp_ctx, &tmp_share_names,
						   0, NULL);
		if (!W_ERROR_IS_OK(werr)) {
			goto done;
		}
		added_count++;
	}

	if (smbconf_share_exists(ctx, GLOBAL_NAME)) {
		werr = smbconf_add_string_to_array(tmp_ctx, &tmp_share_names,
						   added_count, GLOBAL_NAME);
		if (!W_ERROR_IS_OK(werr)) {
			goto done;
		}
		added_count++;
	}

	for (count = 0; count < pd(ctx)->cache->num_shares; count++) {
		if (strequal(pd(ctx)->cache->share_names[count], GLOBAL_NAME) ||
		    (pd(ctx)->cache->share_names[count] == NULL))
		{
			continue;
		}

		werr = smbconf_add_string_to_array(tmp_ctx, &tmp_share_names,
					added_count,
					pd(ctx)->cache->share_names[count]);
		if (!W_ERROR_IS_OK(werr)) {
			goto done;
		}
		added_count++;
	}

	*num_shares = added_count;
	if (added_count > 0) {
		*share_names = talloc_move(mem_ctx, &tmp_share_names);
	} else {
		*share_names = NULL;
	}

done:
	talloc_free(tmp_ctx);
	return werr;
}
Пример #17
0
    void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop)
    {
        if (object == &Obj && Prop.getTypeId() == Part::PropertyGeometryList::getClassTypeId()) {
            const Part::PropertyGeometryList& geom = static_cast<const Part::PropertyGeometryList&>(Prop);
            const std::vector<Part::Geometry*>& items = geom.getValues();
            if (items.size() != 2)
                return;
            Part::Geometry* g1 = items[0];
            Part::Geometry* g2 = items[1];
            if (!g1 || g1->getTypeId() != Part::GeomArcOfCircle::getClassTypeId())
                return;
            if (!g2 || g2->getTypeId() != Part::GeomLineSegment::getClassTypeId())
                return;
            Part::GeomArcOfCircle* arc = static_cast<Part::GeomArcOfCircle*>(g1);
            Part::GeomLineSegment* seg = static_cast<Part::GeomLineSegment*>(g2);

            try {
                Base::Vector3d m1 = arc->getCenter();
              //Base::Vector3d a3 = arc->getStartPoint();
                Base::Vector3d a3 = arc->getEndPoint(true);
              //Base::Vector3d l1 = seg->getStartPoint();
                Base::Vector3d l2 = seg->getEndPoint();
#if 0
                Py::Module pd("FilletArc");
                Py::Callable method(pd.getAttr(std::string("makeFilletArc")));
                Py::Callable vector(pd.getAttr(std::string("Vector")));

                Py::Tuple xyz(3);
                Py::Tuple args(6);
                xyz.setItem(0, Py::Float(m1.x));
                xyz.setItem(1, Py::Float(m1.y));
                xyz.setItem(2, Py::Float(m1.z));
                args.setItem(0,vector.apply(xyz));

                xyz.setItem(0, Py::Float(a3.x));
                xyz.setItem(1, Py::Float(a3.y));
                xyz.setItem(2, Py::Float(a3.z));
                args.setItem(1,vector.apply(xyz));

                xyz.setItem(0, Py::Float(l2.x));
                xyz.setItem(1, Py::Float(l2.y));
                xyz.setItem(2, Py::Float(l2.z));
                args.setItem(2,vector.apply(xyz));

                xyz.setItem(0, Py::Float((float)0));
                xyz.setItem(1, Py::Float((float)0));
                xyz.setItem(2, Py::Float((float)1));
                args.setItem(3,vector.apply(xyz));

                args.setItem(4,Py::Float(radius));
                args.setItem(5,Py::Int((int)0));
                Py::Tuple ret(method.apply(args));
                Py::Object S1(ret.getItem(0));
                Py::Object S2(ret.getItem(1));
                Py::Object M2(ret.getItem(2));

                Base::Vector3d s1, s2, m2;
                s1.x = (double)Py::Float(S1.getAttr("x"));
                s1.y = (double)Py::Float(S1.getAttr("y"));
                s1.z = (double)Py::Float(S1.getAttr("z"));

                s2.x = (double)Py::Float(S2.getAttr("x"));
                s2.y = (double)Py::Float(S2.getAttr("y"));
                s2.z = (double)Py::Float(S2.getAttr("z"));

                m2.x = (double)Py::Float(M2.getAttr("x"));
                m2.y = (double)Py::Float(M2.getAttr("y"));
                m2.z = (double)Py::Float(M2.getAttr("z"));

                coords->point.set1Value(0, (float)s1.x,(float)s1.y,(float)s1.z);
                coords->point.set1Value(1, (float)m2.x,(float)m2.y,(float)m2.z);
                coords->point.set1Value(2, (float)s2.x,(float)s2.y,(float)s2.z);

                Base::Console().Message("M1=<%.4f,%.4f>\n", m1.x,m1.y);
                Base::Console().Message("M2=<%.4f,%.4f>\n", m2.x,m2.y);
                Base::Console().Message("S1=<%.4f,%.4f>\n", s1.x,s1.y);
                Base::Console().Message("S2=<%.4f,%.4f>\n", s2.x,s2.y);
                Base::Console().Message("P=<%.4f,%.4f>\n", a3.x,a3.y);
                Base::Console().Message("Q=<%.4f,%.4f>\n", l2.x,l2.y);
                Base::Console().Message("\n");
#else
                Py::Module pd("PartDesign");
                Py::Callable method(pd.getAttr(std::string("makeFilletArc")));

                Py::Tuple args(6);
                args.setItem(0,Py::Vector(m1));
                args.setItem(1,Py::Vector(a3));
                args.setItem(2,Py::Vector(l2));
                args.setItem(3,Py::Vector(Base::Vector3d(0,0,1)));
                args.setItem(4,Py::Float(radius));
              //args.setItem(5,Py::Int((int)0));
                args.setItem(5,Py::Int((int)1));
                Py::Tuple ret(method.apply(args));
                Py::Vector S1(ret.getItem(0));
                Py::Vector S2(ret.getItem(1));
                Py::Vector M2(ret.getItem(2));

                Base::Vector3d s1 = S1.toVector();
                Base::Vector3d s2 = S2.toVector();
                Base::Vector3d m2 = M2.toVector();
                coords->point.set1Value(0, (float)s1.x,(float)s1.y,(float)s1.z);
                coords->point.set1Value(1, (float)m2.x,(float)m2.y,(float)m2.z);
                coords->point.set1Value(2, (float)s2.x,(float)s2.y,(float)s2.z);

                Base::Console().Message("M1=<%.4f,%.4f>\n", m1.x,m1.y);
                Base::Console().Message("M2=<%.4f,%.4f>\n", m2.x,m2.y);
                Base::Console().Message("S1=<%.4f,%.4f>\n", s1.x,s1.y);
                Base::Console().Message("S2=<%.4f,%.4f>\n", s2.x,s2.y);
                Base::Console().Message("P=<%.4f,%.4f>\n", a3.x,a3.y);
                Base::Console().Message("Q=<%.4f,%.4f>\n", l2.x,l2.y);
                Base::Console().Message("\n");
#endif
            }
            catch (Py::Exception&) {
                Base::PyException e; // extract the Python error text
                Base::Console().Error("%s\n", e.what());
            }
        }
    }
/**
 * get a definition of a share (service) from configuration.
 */
static WERROR smbconf_txt_get_share(struct smbconf_ctx *ctx,
				    TALLOC_CTX *mem_ctx,
				    const char *servicename,
				    struct smbconf_service **service)
{
	WERROR werr;
	uint32_t sidx, count;
	bool found;
	TALLOC_CTX *tmp_ctx = NULL;
	struct smbconf_service *tmp_service = NULL;

	werr = smbconf_txt_load_file(ctx);
	if (!W_ERROR_IS_OK(werr)) {
		return werr;
	}

	found = smbconf_find_in_array(servicename,
				      pd(ctx)->cache->share_names,
				      pd(ctx)->cache->num_shares,
				      &sidx);
	if (!found) {
		return WERR_NO_SUCH_SERVICE;
	}

	tmp_ctx = talloc_stackframe();

	tmp_service = TALLOC_ZERO_P(tmp_ctx, struct smbconf_service);
	if (tmp_service == NULL) {
		werr = WERR_NOMEM;
		goto done;
	}

	if (servicename != NULL) {
		tmp_service->name = talloc_strdup(tmp_service, servicename);
		if (tmp_service->name == NULL) {
			werr = WERR_NOMEM;
			goto done;
		}
	}

	for (count = 0; count < pd(ctx)->cache->num_params[sidx]; count++) {
		werr = smbconf_add_string_to_array(tmp_service,
				&(tmp_service->param_names),
				count,
				pd(ctx)->cache->param_names[sidx][count]);
		if (!W_ERROR_IS_OK(werr)) {
			goto done;
		}
		werr = smbconf_add_string_to_array(tmp_service,
				&(tmp_service->param_values),
				count,
				pd(ctx)->cache->param_values[sidx][count]);
		if (!W_ERROR_IS_OK(werr)) {
			goto done;
		}
	}

	tmp_service->num_params = count;
	if (count > 0) {
		*service = talloc_move(mem_ctx, &tmp_service);
	} else {
		*service = NULL;
	}

done:
	talloc_free(tmp_ctx);
	return werr;
}
Пример #19
0
    void packControlMessageForSending( ControlInfoWrapper& cinfo, 
				       minissf::CompactDataType* mesg )
    {
      PackedData pd(mesg);
      cinfo.pack( pd );
    }
Пример #20
0
int _lzo1c_do_compress   ( const lzo_bytep in,  lzo_uint  in_len,
                                 lzo_bytep out, lzo_uintp out_len,
                                 lzo_voidp wrkmem,
                                 lzo_compress_t func )
{
    int r;
#if defined(LZO_TEST_COMPRESS_OVERRUN)
    lzo_uint avail_out = *out_len;
#endif


#if defined(LZO_COLLECT_STATS)
    _lzo1c_stats_init(lzo_stats);
    lzo_stats->in_len = in_len;
#endif


    /* don't try to compress a block that's too short */
    if (in_len <= 0)
    {
        *out_len = 0;
        r = LZO_E_OK;
    }
    else if (in_len <= MIN_LOOKAHEAD + 1)
    {
#if defined(LZO_RETURN_IF_NOT_COMPRESSIBLE)
        *out_len = 0;
        r = LZO_E_NOT_COMPRESSIBLE;
#else
        *out_len = pd(STORE_RUN(out,in,in_len), out);
        r = (*out_len > in_len) ? LZO_E_OK : LZO_E_ERROR;
#endif
    }
    else
        r = func(in,in_len,out,out_len,wrkmem);


#if defined(LZO_EOF_CODE)
#if defined(LZO_TEST_COMPRESS_OVERRUN)
    if (r == LZO_E_OK && avail_out - *out_len < 3)
        r = LZO_E_COMPRESS_OVERRUN;
#endif
    if (r == LZO_E_OK)
    {
        lzo_bytep op = out + *out_len;
        *op++ = M3_MARKER | 1;
        *op++ = 0;
        *op++ = 0;
        *out_len += 3;
    }
#endif


#if defined(LZO_COLLECT_STATS)
    lzo_stats->out_len = *out_len;
    lzo_stats->match_bytes =
       1 * lzo_stats->m1_matches + 2 * lzo_stats->m2_matches +
       3 * lzo_stats->m3_matches + 4 * lzo_stats->m4_matches;
    _lzo1c_stats_calc(lzo_stats);
#endif

    return r;
}
Пример #21
0
// ---------------------------------------------------------
// TDdParser::SetMediaObjAttrL()
// ---------------------------------------------------------
//
void TDdParser::SetMediaObjAttrL( TDdAttr aAttr, const TDesC& aValue, CMediaObjectData *& aMediaObject )
    {
    TInt ok( ETrue );
    switch( aAttr )
        {
        case EDdSize:
            {
            if ( !aMediaObject->Size() )
                {
                // Parse as TUint - negative not allowed.
                TUint size;
                TLex lex( aValue );
                if ( !lex.Val( size ) )
                    {
                    aMediaObject->SetSize( size );
                    }
                else
                    {
                    ok = EFalse;
                    }
                }
            break;
            }

        case EDdType:
            {
            ok = aMediaObject->AddTypeL( aValue );
            break;
            }

        case EDdProgressiveDl:
            {
            TBool pd( EFalse );
            if ( !aValue.CompareF( KDdTrue ) )
                {
                pd = ETrue;
                }
            else if ( aValue.CompareF( KDdFalse ) )
                {
                // Expected 'true' or 'false'
                Error( KErrCodInvalidDescriptor );
                break;
                }
            aMediaObject->SetProgressiveDownload( pd );
            break;
            }

        case EDdSuppressUserConfirmation:
            {
            TInt confirm = CCodData::ENever; 
            if ( !aValue.CompareF(KDdNever) )
                {
                confirm = CCodData::ENever; 
                }
            else if ( aValue.CompareF(KDdUserConfirmStepOnly) )
                {
                confirm = CCodData::EUserConfirmStepOnly; 
                }
            else if ( aValue.CompareF(KDdAlways) )
                {
                confirm = CCodData::EAlways;      
                }
            else 
                {
                Error( KErrCodInvalidDescriptor );
                }
            iData->SetSuppressConfirm( confirm );
            break;
            }
        case EDdUpdatedDDURI:
            {
            if(!iData->UpdatedDDUriL().Length())
                {
                iData->SetUpdatedDDURI( aValue );
                }
            
            break;
            }
        default:
            {
            // Unexpected value.
            CodPanic( ECodInternal );
            }
        }
    if ( !ok )
        {
        Error( KErrCodInvalidDescriptor );
        }
    }
Пример #22
0
bool Player::prepare()
{
    //Init Gst
    //
    QString caps_value = "audio/x-raw-int";

      // On mac we bundle the gstreamer plugins with knowthelist
    #if defined(Q_OS_DARWIN)
      QString scanner_path;
      QString plugin_path;
      QString registry_filename;

      caps_value = "audio/x-raw-float";
      QDir pd(QCoreApplication::applicationDirPath() + "/../plugins");
      scanner_path = QCoreApplication::applicationDirPath() + "/../plugins/gst-plugin-scanner";
      plugin_path = QCoreApplication::applicationDirPath() + "/../plugins/gstreamer";
      registry_filename = QDesktopServices::storageLocation(QDesktopServices::DataLocation) +
              QString("/gst-registry-%1-bin").arg(QCoreApplication::applicationVersion());

      if ( pd.exists())
        setenv("GST_PLUGIN_SCANNER", scanner_path.toLocal8Bit().constData(), 1);

      if ( pd.exists()) {
        setenv("GST_PLUGIN_PATH", plugin_path.toLocal8Bit().constData(), 1);
        // Never load plugins from anywhere else.
        setenv("GST_PLUGIN_SYSTEM_PATH", plugin_path.toLocal8Bit().constData(), 1);
      }

      if (!registry_filename.isEmpty()) {
        setenv("GST_REGISTRY", registry_filename.toLocal8Bit().constData(), 1);
      }
    #endif

      gst_init (0, 0);

    //prepare

        GstElement *dec, *conv,*resample,*sink, *gain, *audio, *vol, *level, *equalizer;
        GstElement *levelout;
        GstPad *audiopad;
        GstCaps *caps;
        pipeline = gst_pipeline_new ("pipeline");
        bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
        caps = gst_caps_new_simple (caps_value.toLatin1().data(),
                                    "channels", G_TYPE_INT, 2, NULL);


        dec = gst_element_factory_make ("decodebin2", "decoder");
        g_signal_connect (dec, "new-decoded-pad", G_CALLBACK (cb_newpad), this);
        gst_bin_add (GST_BIN (pipeline), dec);

        audio = gst_bin_new ("audiobin");
        conv = gst_element_factory_make ("audioconvert", "aconv");
        resample = gst_element_factory_make ("audioresample", "resample");
        audiopad = gst_element_get_static_pad (conv, "sink");
        gain = gst_element_factory_make ("audioamplify", "gain");
        level = gst_element_factory_make ("level", "levelintern");
        vol = gst_element_factory_make ("volume", "volume");
        levelout = gst_element_factory_make ("level", "levelout");
        equalizer = gst_element_factory_make ("equalizer-3bands", "equalizer");
        sink = gst_element_factory_make ("autoaudiosink", "sink");

        g_object_set (level, "message", TRUE, NULL);
        g_object_set (levelout, "message", TRUE, NULL);
        g_object_set (level, "peak-ttl", 300000000000, NULL);

        gst_bin_add_many (GST_BIN (audio), conv, resample, level, gain, equalizer, levelout, vol, sink, NULL);
        gst_element_link (conv,resample);

        gst_element_link_filtered (resample, level, caps);
        gst_element_link (level, gain);
        gst_element_link (gain, equalizer);
        gst_element_link (equalizer, vol);
        gst_element_link_filtered (vol, levelout, caps);
        gst_element_link (levelout,sink);

        gst_element_add_pad (audio, gst_ghost_pad_new ("sink", audiopad));
        gst_bin_add (GST_BIN (pipeline), audio);


        GstElement *l_src;
        l_src = gst_element_factory_make ("filesrc", "localsrc");
        gst_bin_add_many (GST_BIN (pipeline), l_src, NULL);
        gst_element_set_state (l_src, GST_STATE_NULL);
        gst_element_link ( l_src,dec);

        gst_bus_set_sync_handler (bus, bus_cb, this);

        gst_object_unref (audiopad);

        return pipeline;
}
Пример #23
0
void QWidget::scroll( int dx, int dy, const QRect& r )
{
    if ( testWState( WState_BlockUpdates ) && !children() )
	return;
    bool valid_rect = r.isValid();
    QRect sr = valid_rect?r:rect();
    int x1, y1, x2, y2, w=sr.width(), h=sr.height();
    if ( dx > 0 ) {
	x1 = sr.x();
	x2 = x1+dx;
	w -= dx;
    } else {
	x2 = sr.x();
	x1 = x2-dx;
	w += dx;
    }
    if ( dy > 0 ) {
	y1 = sr.y();
	y2 = y1+dy;
	h -= dy;
    } else {
	y2 = sr.y();
	y1 = y2-dy;
	h += dy;
    }

    if ( dx == 0 && dy == 0 )
	return;

    QSize s( qt_screen->width(), qt_screen->height() );
    QRegion alloc = valid_rect ? paintableRegion() : allocatedRegion();

    QRegion dAlloc = alloc;
    QPoint td1 = qt_screen->mapToDevice( QPoint(0,0), s );
    QPoint td2 = qt_screen->mapToDevice( QPoint(dx,dy), s );
    dAlloc.translate( td2.x()-td1.x(), td2.y()-td1.y() );

    QRegion scrollRegion( alloc & dAlloc );

    if ( w > 0 && h > 0 ) {
	QGfx * mygfx=graphicsContext( FALSE );
	mygfx->setClipDeviceRegion( scrollRegion );
	mygfx->scroll(x2,y2,w,h,x1,y1);
	delete mygfx;
    }

    paintable_region_dirty = TRUE;

    QPoint gpos = mapToGlobal( QPoint() );

    if ( !valid_rect && children() ) {	// scroll children
	setChildrenAllocatedDirty();
	QPoint pd( dx, dy );
	QObjectListIt it(*children());
	register QObject *object;
	while ( it ) {				// move all children
	    object = it.current();
	    if ( object->isWidgetType() ) {
		QWidget *w = (QWidget *)object;
		QPoint oldp = w->pos();
		QRect  r( w->pos() + pd, w->size() );
		w->crect = r;
		w->updateRequestedRegion( gpos + w->pos() );
		QMoveEvent e( r.topLeft(), oldp );
		QApplication::sendEvent( w, &e );
	    }
	    ++it;
	}
    }

    QSize ds( qt_screen->deviceWidth(), qt_screen->deviceHeight() );
    scrollRegion = qt_screen->mapFromDevice( scrollRegion, ds );
    scrollRegion.translate( -gpos.x(), -gpos.y() );

    QRegion update( sr );
    update -= scrollRegion;
    if ( dx ) {
	int x = x2 == sr.x() ? sr.x()+w : sr.x();
	update |= QRect( x, sr.y(), QABS(dx), sr.height() );
    }
    if ( dy ) {
	int y = y2 == sr.y() ? sr.y()+h : sr.y();
	update |= QRect( sr.x(), y, sr.width(), QABS(dy) );
    }
    repaint( update, !testWFlags(WRepaintNoErase) );
    if ( !valid_rect && children() )
	paint_children( this, update, FALSE );
}
Пример #24
0
bool UserPropertiesHandler::handleURI(URI& uri)
{
    bool addUser = uri.action == "add_user";
    bool editUser = uri.action == "edit_user";
    if (!addUser && !editUser)
        return false;

    wxWindow* w = getParentWindow(uri);
    ServerPtr server;
    UserPtr user;
    wxString title(_("Modify User"));
    if (addUser)
    {
        server = extractMetadataItemPtrFromURI<Server>(uri);
        if (!server)
            return true;
        title = _("Create New User");
        user.reset(new User(server));
    }
    else
    {
        user = extractMetadataItemPtrFromURI<User>(uri);
        if (!user)
            return true;
#ifdef __WXGTK__
        if (user->getUsername() == "SYSDBA")
        {
            showWarningDialog(w, _("The password for the SYSDBA user should not be changed here."),
                _("The appropriate way to change the password of the SYSDBA user is to run the changeDBAPassword.sh script in Firebird's bin directory.\n\nOtherwise the scripts will not be updated."),
                AdvancedMessageDialogButtonsOk(), config(), "DIALOG_warn_sysdba_change",
                _("Do not show this information again"));
        }
#endif
        server = user->getServer();
        if (!server)
            return true;
    }

    UserDialog d(w, title, addUser);
    d.setUser(user);
    if (d.ShowModal() == wxID_OK)
    {
        ProgressDialog pd(w, _("Connecting to Server..."), 1);
        pd.doShow();
        IBPP::Service svc;
        if (!getService(server.get(), svc, &pd, true)) // true = need SYSDBA password
            return true;

        try
        {
            IBPP::User u;
            user->assignTo(u);
            if (addUser)
                svc->AddUser(u);
            else
                svc->ModifyUser(u);
            server->notifyObservers();
        }
        catch(IBPP::Exception& e)
        {
            wxMessageBox(e.what(), _("Error"),
                wxOK | wxICON_WARNING);
        }
    }
    return true;
}
Пример #25
0
dtype compute_graph(int num_parts_y,int num_parts_x,int num_pairs,int *pairs,int num_lab_y,int num_lab_x,Real *data,Real *dist,Real *wcosts,
int numhyp,Real* lscr,int *reslab,int aiter,int restart)
{
    double lowerBound;
    float t,tot_t;
    int iter;

    int seed = 1124285485;
    srand(seed);

    dtype scr;

    int st_parts_x=num_parts_x;
    int st_parts_y=num_parts_y;
    int st_num_lab_x=num_lab_x;
    int st_num_lab_y=num_lab_y;
    int st_numlab=num_lab_y*num_lab_x;//num_parts_x*num_parts_y;//num_labels;
    //copy data because it is internally modified
    std::vector<dtype> copy_data_vec(data, data + num_parts_x * num_parts_y * num_lab_x * num_lab_y);
    dtype* copy_data = copy_data_vec.data();
//    dtype* copy_data=(dtype*)malloc(num_parts_x*num_parts_y*num_lab_x*num_lab_y*sizeof(dtype));
//    for (int i=0;i<num_parts_x*num_parts_y*num_lab_x*num_lab_y;i++)
//        copy_data[i]=data[i];
    clock_t t0,t1;
    t0 = clock ();
    int l1,l2;
    CV_Fast_PD pd( num_parts_x*num_parts_y, num_lab_x*num_lab_y, num_lab_x, copy_data,
	               num_pairs, pairs, dist, aiter,
				   wcosts );
  	//CV_Fast_PD pd( _numpoints, _numlabels, _lcosts,
	//               _numpairs, _pairs, _dist, _max_iters,
	//			   _wcosts );
    //printf("Parts %d,%d Labels %d\n",num_parts_x,num_parts_y,num_lab_x*num_lab_y);
	pd.run();
    for( int i = 0; i < num_parts_x*num_parts_y; i++ )
    {
        //printf("Lab%d:%d ",i,pd._pinfo[i].label);
	 	reslab[i]= pd._pinfo[i].label;  
    }

    Real bestE=pd.score(); 
    lscr[0]=-bestE;
	/*for (iter=0; iter<numhyp; iter++) 
    {
        bestE=10000;
        for (int idrestart=restart; idrestart>=0;idrestart--)
        {
            if (restart==0)
		        mrf->optimize(aiter, t);
		    else
		    {
			    //mrf->initialize();
                ((Expansion*)mrf)->clearAnswer();
			    mrf->optimize(aiter,t);	
		    }
                //printf("After C\n");
      		E = mrf->totalEnergy();
            //printf("After(%d,%d)",num_lab_y,num_lab_x);
            if (restart>0 && E>bestE)
            {
                //printf("Higher energy it=%d rest=%d energy=%f\n",iter,idrestart,E);
                continue;
            }
            //printf("Lower energy it=%d rest=%d energy=%f\n",iter,idrestart,E);
            bestE=E;
       		//lowerBound = mrf->lowerBound();
       		tot_t = tot_t + t ;
            for ( int  i = 0; i < num_parts_y*num_parts_x; i++ )
            {
                reslab[iter*num_parts_y*num_parts_x+i] = mrf->getLabel(i);//gc->whatLabel(i);
            }
	    }        
	    *lscr=-bestE;
	    lscr++;
        //t0 = clock ();
        for ( int  i = 0; i < num_parts_y*num_parts_x; i++ )
        {
            int aux=reslab[iter*num_parts_y*num_parts_x+i];
			//reslab[iter*num_parts_y*num_parts_x+i] = aux;//gc->whatLabel(i);
            //data[i*st_numlab+aux]=1;//delete solution
            for (int rx=-1;rx<2;rx++)
            {
                for (int ry=-1;ry<2;ry++)  
                {                       
                    int pp=aux+rx+ry*st_num_lab_x;
                    pp=maxi(pp,0);
                    pp=mini(pp,st_numlab-1);
                    data[pp+i*st_numlab]=10;//delete solution
                }
            }
            //printf("%d ",reslab[i]);
        }
        //printf("Done\n",num_lab_y,num_lab_x);
        //t1 = clock ();   
        //printf("t0=%d t1=%d Diff %f \n",t0,t1,float(t1-t0)/CLOCKS_PER_SEC);
        //trees=((Expansion*)mrf)->getEnergies();
        //sol=((Expansion*)mrf)->getSolutions();        
    }
    delete mrf;*/
    t1 = clock ();
    //printf("t0=%d t1=%d Diff %f \n",t0,t1,float(t1-t0)/CLOCKS_PER_SEC);
    return -bestE;
}
Пример #26
0
bool PrintFile(const WCHAR *fileName, WCHAR *printerName, bool displayErrors, const WCHAR *settings)
{
    bool ok = false;
    if (!HasPermission(Perm_PrinterAccess))
        return false;

    ScopedMem<WCHAR> fileName2(path::Normalize(fileName));
    BaseEngine *engine = EngineManager::CreateEngine(fileName2, true /* prefer Chm2Engine */);
#ifndef DISABLE_DOCUMENT_RESTRICTIONS
    if (engine && !engine->AllowsPrinting()) {
        delete engine;
        engine = NULL;
    }
#endif
    if (!engine) {
        if (displayErrors)
            MessageBoxWarning(NULL, _TR("Cannot print this file"), _TR("Printing problem."));
        return false;
    }

    HANDLE printer;
    BOOL res = OpenPrinter(printerName, &printer, NULL);
    if (0 == res) {
        if (displayErrors)
            MessageBoxWarning(NULL, _TR("Printer with given name doesn't exist"), _TR("Printing problem."));
        return false;
    }

    LPDEVMODE devMode = NULL;
    // get printer driver information
    DWORD needed = 0;
    GetPrinter(printer, 2, NULL, 0, &needed);
    ScopedMem<PRINTER_INFO_2> infoData((PRINTER_INFO_2 *)AllocArray<BYTE>(needed));
    if (infoData)
        res = GetPrinter(printer, 2, (LPBYTE)infoData.Get(), needed, &needed);
    if ((0 == res) || !infoData || needed <= sizeof(PRINTER_INFO_2))
        goto Exit;

    LONG structSize = DocumentProperties(NULL,
        printer,
        printerName,
        NULL,                   /* Asking for size, so */
        NULL,                   /* not used. */
        0);                     /* Zero returns buffer size. */
    if (structSize < sizeof(DEVMODE)) {
        // If failure, inform the user, cleanup and return failure.
        if (displayErrors)
            MessageBoxWarning(NULL, _TR("Could not obtain Printer properties"), _TR("Printing problem."));
        goto Exit;
    }
    devMode = (LPDEVMODE)malloc(structSize);
    if (!devMode)
        goto Exit;

    // Get the default DevMode for the printer and modify it for your needs.
    LONG returnCode = DocumentProperties(NULL,
        printer,
        printerName,
        devMode,        /* The address of the buffer to fill. */
        NULL,           /* Not using the input buffer. */
        DM_OUT_BUFFER); /* Have the output buffer filled. */
    if (IDOK != returnCode) {
        // If failure, inform the user, cleanup and return failure.
        if (displayErrors)
            MessageBoxWarning(NULL, _TR("Could not obtain Printer properties"), _TR("Printing problem."));
        goto Exit;
    }

    ClosePrinter(printer);
    printer = NULL;

    {
        Print_Advanced_Data advanced;
        Vec<PRINTPAGERANGE> ranges;
        ApplyPrintSettings(settings, engine->PageCount(), ranges, advanced, devMode);

        PrintData pd(engine, infoData, devMode, ranges, advanced);
        ok = PrintToDevice(pd);
        if (!ok && displayErrors)
            MessageBoxWarning(NULL, _TR("Couldn't initialize printer"), _TR("Printing problem."));
    }

Exit:
    free(devMode);
    if (printer)
        ClosePrinter(printer);
    delete engine;
    return ok;
}
Пример #27
0
Файл: ktx.cpp Проект: DXGL/skia
bool SkKTXFile::readKTXFile(const uint8_t* data, size_t dataLen) {
    const uint8_t *buf = data;
    size_t bytesLeft = dataLen;

    // Make sure original KTX header is there... this should have been checked
    // already by a call to is_ktx()
    SkASSERT(bytesLeft > KTX_FILE_IDENTIFIER_SIZE);
    SkASSERT(0 == memcmp(KTX_FILE_IDENTIFIER, buf, KTX_FILE_IDENTIFIER_SIZE));
    buf += KTX_FILE_IDENTIFIER_SIZE;
    bytesLeft -= KTX_FILE_IDENTIFIER_SIZE;

    // Read header, but first make sure that we have the proper space: we need
    // two 32-bit ints: 1 for endianness, and another for the mandatory image
    // size after the header.
    if (bytesLeft < 8 + sizeof(Header)) {
        return false;
    }

    uint32_t endianness = this->readInt(&buf, &bytesLeft);
    fSwapBytes = kKTX_ENDIANNESS_CODE != endianness;

    // Read header values
    fHeader.fGLType                = this->readInt(&buf, &bytesLeft);
    fHeader.fGLTypeSize            = this->readInt(&buf, &bytesLeft);
    fHeader.fGLFormat              = this->readInt(&buf, &bytesLeft);
    fHeader.fGLInternalFormat      = this->readInt(&buf, &bytesLeft);
    fHeader.fGLBaseInternalFormat  = this->readInt(&buf, &bytesLeft);
    fHeader.fPixelWidth            = this->readInt(&buf, &bytesLeft);
    fHeader.fPixelHeight           = this->readInt(&buf, &bytesLeft);
    fHeader.fPixelDepth            = this->readInt(&buf, &bytesLeft);
    fHeader.fNumberOfArrayElements = this->readInt(&buf, &bytesLeft);
    fHeader.fNumberOfFaces         = this->readInt(&buf, &bytesLeft);
    fHeader.fNumberOfMipmapLevels  = this->readInt(&buf, &bytesLeft);
    fHeader.fBytesOfKeyValueData   = this->readInt(&buf, &bytesLeft);

    // Check for things that we understand...
    {
        // First, we only support compressed formats and single byte
        // representations at the moment. If the internal format is
        // compressed, the the GLType field in the header must be zero.
        // In the future, we may support additional data types (such
        // as GL_UNSIGNED_SHORT_5_6_5)
        if (fHeader.fGLType != 0 && fHeader.fGLType != GR_GL_UNSIGNED_BYTE) {
            return false;
        }

        // This means that for well-formatted KTX files, the glTypeSize
        // field must be one...
        if (fHeader.fGLTypeSize != 1) {
            return false;
        }

        // We don't support 3D textures.
        if (fHeader.fPixelDepth > 1) {
            return false;
        }

        // We don't support texture arrays
        if (fHeader.fNumberOfArrayElements > 1) {
            return false;
        }

        // We don't support cube maps
        if (fHeader.fNumberOfFaces > 1) {
            return false;
        }

        // We don't support width and/or height <= 0
        if (fHeader.fPixelWidth <= 0 || fHeader.fPixelHeight <= 0) {
            return false;
        }
    }

    // Make sure that we have enough bytes left for the key/value
    // data according to what was said in the header.
    if (bytesLeft < fHeader.fBytesOfKeyValueData) {
        return false;
    }

    // Next read the key value pairs
    size_t keyValueBytesRead = 0;
    while (keyValueBytesRead < fHeader.fBytesOfKeyValueData) {
        uint32_t keyValueBytes = this->readInt(&buf, &bytesLeft);
        keyValueBytesRead += 4;

        if (keyValueBytes > bytesLeft) {
            return false;
        }

        KeyValue kv(keyValueBytes);
        if (!kv.readKeyAndValue(buf)) {
            return false;
        }

        fKeyValuePairs.push_back(kv);

        uint32_t keyValueBytesPadded = (keyValueBytes + 3) & ~3;
        buf += keyValueBytesPadded;
        keyValueBytesRead += keyValueBytesPadded;
        bytesLeft -= keyValueBytesPadded;
    }

    // Read the pixel data...
    int mipmaps = SkMax32(fHeader.fNumberOfMipmapLevels, 1);
    SkASSERT(mipmaps == 1);

    int arrayElements = SkMax32(fHeader.fNumberOfArrayElements, 1);
    SkASSERT(arrayElements == 1);

    int faces = SkMax32(fHeader.fNumberOfFaces, 1);
    SkASSERT(faces == 1);

    int depth = SkMax32(fHeader.fPixelDepth, 1);
    SkASSERT(depth == 1);

    for (int mipmap = 0; mipmap < mipmaps; ++mipmap) {
        // Make sure that we have at least 4 more bytes for the first image size
        if (bytesLeft < 4) {
            return false;
        }

        uint32_t imgSize = this->readInt(&buf, &bytesLeft);

        // Truncated file.
        if (bytesLeft < imgSize) {
            return false;
        }

        // !FIXME! If support is ever added for cube maps then the padding
        // needs to be taken into account here.
        for (int arrayElement = 0; arrayElement < arrayElements; ++arrayElement) {
            for (int face = 0; face < faces; ++face) {
                for (int z = 0; z < depth; ++z) {
                    PixelData pd(buf, imgSize);
                    fPixelData.append(1, &pd);
                }
            }
        }
        
        uint32_t imgSizePadded = (imgSize + 3) & ~3;
        buf += imgSizePadded;
        bytesLeft -= imgSizePadded;
    }

    return bytesLeft == 0;
}
Пример #28
0
		void register_callback(const typename callback_t<T>::msg_callback_type &handler)
		{
			std::shared_ptr<callback_base_t> pd(new callback_t<T>(handler));

			callbacks_.insert(T::descriptor(), pd);
		}
Пример #29
0
// Implementation of encoding/decoding with length argument that is not provided with normal Decoder/Encoder calls
void kafka_proto_io_impl(PacketCodec& p, MessageSet& ms, int32_t encoded_length)
{
    if (p.is_writer()) {
        if (ms.compression_ == COMP_None) {
            for (auto& message : ms.messages_) {
                // Encode offset
                p.io(message.offset);
                // Add encoded message length field
                auto len_field = p.start_length();
                // Encode message
                p.io(message);
                // Update length field
                p.end_length(len_field);
            }
        } else {
            // First we need to encode into an uncompressed messages set in a temp buffer
            PacketEncoder pe(ms.encoded_size_);

            // Store the actual compression requested and make a recursive call with no compression set
            auto actual_compression = ms.compression_;
            ms.compression_ = COMP_None;

            pe.io(ms);

            if (!pe.ok()) {
                p.set_err(pe.err())
                    << "Failed to encoded message set before compression: "
                    << pe.err_str();
                return;
            }

            // Reset compression to avoid confusion
            ms.compression_ = actual_compression;

            // Now encode a regular message with that value.
            // Note that for now this means a whole extra copy since we need to assign the encoded buffer to a string
            // Maybe if we ever need to optimise this we can find a cleaner way to allow non-copy references in message value
            // without making them much harder to work with in general.
            MessageSet::Message m{slice(), pe.get_as_slice(false), 0, actual_compression};

            // Now we can encode the message set with single compressed message into the output buffer
            // Encode null offset
            static int64_t zero = 0;
            p.io(zero);
            // Add encoded message length field
            auto len_field = p.start_length();
            // Encode message
            p.io(m);
            // Update length field
            p.end_length(len_field);
        }
    } else {
        // No length prefix for messages and we might have partial one at end of buffer legitimately
        // Keep reading until we have them all (or hit error)...
        // In some cases a MessageSet might be embedded inside a larger structure with a length prefix before it
        // in this case we need to stop reading once we have consumed the length the prefix gave otherwise we might
        // read past the end and into non MessageSet bytes that follow.
        // Decoder provides access to the last length prefix passed for this purpose, although it is not always present
        // so only use it if it is
        auto start_offset = p.get_cursor();

        while (p.ok() && (encoded_length == -1 || (p.get_cursor() - start_offset) < static_cast<size_t>(encoded_length))) {
            MessageSet::Message m;

            p.io(m.offset);
            auto len_field = p.start_length();
            p.io(m);
            p.end_length(len_field);

            if (p.ok()) {
                if (m.compression_ == COMP_None) {
                    // This doesn't
                    ms.push(std::move(m));
                } else {
                    // Message decoder already should have detected compression and decompressed the message's value
                    // we just need to decode that as a nested message set and append messages to this message set...
                    // We rely on the decompressed buffer being the last one decompressed and so it is on the end of the
                    // Decoder's list. We get it and use directly which both saves copy overhead but more importantly
                    // means the messages we decode will have their key/value slices pointing into a valid buffer once
                    // this PacketDecoder is destructed below.
                    auto decoder = reinterpret_cast<PacketDecoder *>(&p);
                    PacketDecoder pd(decoder->get_last_decompress_buffer());

                    // Decode messages directly into the message set here - new ones will be appended.
                    pd.io(ms);
                }
            }
        }

        // Not having enough bytes to read more is a normal termination condition for reads regardless of if we had
        // partial message at end off buffer or not. In both cases it's expected case and so should not be left as
        // an error state. Any other error should be left though.
        if (p.err() == PacketCodec::ERR_TRUNCATED) {
            p.set_err(PacketCodec::ERR_NONE);
        }
    }
}
Пример #30
0
void SurfaceItem::render(const Map &map, const Camera &camera)
{
    int zone = map.zone(vertices().at(0));

    GLuint tex = textureId();

    if (zone < 0)
        return;

    m_program->bind();
    m_program->setUniformValue(m_matrixUniform, camera.viewProjectionMatrix());

    QSize size = surface()->size();
    m_program->setUniformValue(m_pixelSizeUniform, 5. / size.width(), 5. / size.height());
    m_program->setUniformValue(m_eyeUniform, camera.viewPos());
    m_program->setUniformValue(m_focusColorUniform, GLfloat(m_opacity));
    m_program->setUniformValueArray(m_lightsUniform, map.lights(zone).constData(), map.lights(zone).size());
    m_program->setUniformValue(m_numLightsUniform, map.lights(zone).size());

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex);

    QVector<QVector3D> v = vertices();

    QVector3D va = v[0];
    QVector3D vb = v[1];
    QVector3D vc = v[2];
    QVector3D vd = v[3];

    QVector<QVector3D> vertexBuffer;
    vertexBuffer << va << vb << vd << vd << vb << vc;

    qreal y1 = 0;
    qreal y2 = 1;

    if (surface()->origin() == QWaylandSurface::OriginTopLeft)
        qSwap(y1, y2);

    QVector<QVector2D> texCoordBuffer;
    texCoordBuffer << QVector2D(0, y2) << QVector2D(1, y2)
                   << QVector2D(0, y1) << QVector2D(0, y1)
                   << QVector2D(1, y2) << QVector2D(1, y1);

    m_program->setUniformValue(m_normalUniform, -QVector3D::crossProduct(vb - va, vc - va).normalized());

    m_program->enableAttributeArray(m_vertexAttr);
    m_program->setAttributeArray(m_vertexAttr, vertexBuffer.constData());
    m_program->enableAttributeArray(m_texCoordAttr);
    m_program->setAttributeArray(m_texCoordAttr, texCoordBuffer.constData());

    glEnable(GL_BLEND);
    glDisable(GL_CULL_FACE);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    glDisable(GL_BLEND);

    m_program->disableAttributeArray(m_texCoordAttr);
    m_program->disableAttributeArray(m_vertexAttr);

#if 0
    QOpenGLPaintDevice device(camera.viewSize());
    QPainter p(&device);

    va = camera.viewProjectionMatrix().map(va);
    vb = camera.viewProjectionMatrix().map(vb);
    vc = camera.viewProjectionMatrix().map(vc);
    vd = camera.viewProjectionMatrix().map(vd);

    QVector3D c(camera.viewSize().width() * 0.5, camera.viewSize().height() * 0.5, 0);
    va = c + c * va * QVector3D(1, -1, 0);
    vb = c + c * vb * QVector3D(1, -1, 0);
    vc = c + c * vc * QVector3D(1, -1, 0);
    vd = c + c * vd * QVector3D(1, -1, 0);

    QPointF pa(va.x(), va.y());
    QPointF pb(vb.x(), vb.y());
    QPointF pc(vc.x(), vc.y());
    QPointF pd(vd.x(), vd.y());

    p.drawLine(pa, pb);
    p.drawLine(pb, pc);
    p.drawLine(pc, pd);
    p.drawLine(pd, pa);

    extern QVector3D debug;

    QVector3D d = camera.viewProjectionMatrix().map(debug);
    d = c + c * d * QVector3D(1, -1, 0);

    static QVector3D old;
    if (debug != old)
        old = debug;

    p.setPen(Qt::NoPen);
    p.setBrush(Qt::red);
    p.drawEllipse(QRectF(d.x() - 2, d.y() - 2, 4, 4));

    p.end();
#endif
}