Пример #1
0
 static void onNewSlot(Slot *s) {
   s->root(cx());
 }
nsresult
EventListenerManager::CompileEventHandlerInternal(Listener* aListener,
                                                  const nsAString* aBody,
                                                  Element* aElement)
{
  NS_PRECONDITION(aListener->GetJSListener(),
                  "Why do we not have a JS listener?");
  NS_PRECONDITION(aListener->mHandlerIsString,
                  "Why are we compiling a non-string JS listener?");

  nsresult result = NS_OK;

  nsIJSEventListener* jsListener = aListener->GetJSListener();
  NS_ASSERTION(!jsListener->GetHandler().HasEventHandler(),
               "What is there to compile?");

  nsCOMPtr<nsIDocument> doc;
  nsCOMPtr<nsIScriptGlobalObject> global =
    GetScriptGlobalAndDocument(getter_AddRefs(doc));
  NS_ENSURE_STATE(global);

  nsIScriptContext* context = global->GetScriptContext();
  NS_ENSURE_STATE(context);

  // Push a context to make sure exceptions are reported in the right place.
  AutoPushJSContext cx(context->GetNativeContext());
  JS::Rooted<JSObject*> handler(cx);

  JS::Rooted<JSObject*> scope(cx, jsListener->GetEventScope());

  nsCOMPtr<nsIAtom> typeAtom = aListener->mTypeAtom;
  nsIAtom* attrName = typeAtom;

  if (aListener->mHandlerIsString) {
    // OK, we didn't find an existing compiled event handler.  Flag us
    // as not a string so we don't keep trying to compile strings
    // which can't be compiled
    aListener->mHandlerIsString = false;

    // mTarget may not be an Element if it's a window and we're
    // getting an inline event listener forwarded from <html:body> or
    // <html:frameset> or <xul:window> or the like.
    // XXX I don't like that we have to reference content from
    // here. The alternative is to store the event handler string on
    // the nsIJSEventListener itself, and that still doesn't address
    // the arg names issue.
    nsCOMPtr<Element> element = do_QueryInterface(mTarget);
    MOZ_ASSERT(element || aBody, "Where will we get our body?");
    nsAutoString handlerBody;
    const nsAString* body = aBody;
    if (!aBody) {
      if (aListener->mTypeAtom == nsGkAtoms::onSVGLoad) {
        attrName = nsGkAtoms::onload;
      } else if (aListener->mTypeAtom == nsGkAtoms::onSVGUnload) {
        attrName = nsGkAtoms::onunload;
      } else if (aListener->mTypeAtom == nsGkAtoms::onSVGResize) {
        attrName = nsGkAtoms::onresize;
      } else if (aListener->mTypeAtom == nsGkAtoms::onSVGScroll) {
        attrName = nsGkAtoms::onscroll;
      } else if (aListener->mTypeAtom == nsGkAtoms::onSVGZoom) {
        attrName = nsGkAtoms::onzoom;
      } else if (aListener->mTypeAtom == nsGkAtoms::onbeginEvent) {
        attrName = nsGkAtoms::onbegin;
      } else if (aListener->mTypeAtom == nsGkAtoms::onrepeatEvent) {
        attrName = nsGkAtoms::onrepeat;
      } else if (aListener->mTypeAtom == nsGkAtoms::onendEvent) {
        attrName = nsGkAtoms::onend;
      }

      element->GetAttr(kNameSpaceID_None, attrName, handlerBody);
      body = &handlerBody;
      aElement = element;
    }
    aListener = nullptr;

    uint32_t lineNo = 0;
    nsAutoCString url (NS_LITERAL_CSTRING("-moz-evil:lying-event-listener"));
    MOZ_ASSERT(body);
    MOZ_ASSERT(aElement);
    nsIURI *uri = aElement->OwnerDoc()->GetDocumentURI();
    if (uri) {
      uri->GetSpec(url);
      lineNo = 1;
    }

    uint32_t argCount;
    const char **argNames;
    nsContentUtils::GetEventArgNames(aElement->GetNameSpaceID(),
                                     typeAtom,
                                     &argCount, &argNames);

    JSAutoCompartment ac(cx, context->GetWindowProxy());
    JS::CompileOptions options(cx);
    options.setIntroductionType("eventHandler")
           .setFileAndLine(url.get(), lineNo)
           .setVersion(SCRIPTVERSION_DEFAULT);

    JS::Rooted<JS::Value> targetVal(cx);
    // Go ahead and wrap into the current compartment of cx directly.
    JS::Rooted<JSObject*> wrapScope(cx, JS::CurrentGlobalOrNull(cx));
    if (WrapNewBindingObject(cx, wrapScope, aElement, &targetVal)) {
      MOZ_ASSERT(targetVal.isObject());

      nsDependentAtomString str(attrName);
      // Most of our names are short enough that we don't even have to malloc
      // the JS string stuff, so don't worry about playing games with
      // refcounting XPCOM stringbuffers.
      JS::Rooted<JSString*> jsStr(cx, JS_NewUCStringCopyN(cx,
                                                          str.BeginReading(),
                                                          str.Length()));
      NS_ENSURE_TRUE(jsStr, NS_ERROR_OUT_OF_MEMORY);

      options.setElement(&targetVal.toObject())
             .setElementAttributeName(jsStr);
    }

    JS::Rooted<JSObject*> handlerFun(cx);
    result = nsJSUtils::CompileFunction(cx, JS::NullPtr(), options,
                                        nsAtomCString(typeAtom),
                                        argCount, argNames, *body, handlerFun.address());
    NS_ENSURE_SUCCESS(result, result);
    handler = handlerFun;
    NS_ENSURE_TRUE(handler, NS_ERROR_FAILURE);
  } else {
    aListener = nullptr;
  }

  if (handler) {
    nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(mTarget);
    // Bind it
    JS::Rooted<JSObject*> boundHandler(cx);
    context->BindCompiledEventHandler(mTarget, scope, handler, &boundHandler);
    // Note - We pass null for aIncumbentGlobal below. We could also pass the
    // compilation global, but since the handler is guaranteed to be scripted,
    // there's no need to use an override, since the JS engine will always give
    // us the right answer.
    if (!boundHandler) {
      jsListener->ForgetHandler();
    } else if (jsListener->EventName() == nsGkAtoms::onerror && win) {
      nsRefPtr<OnErrorEventHandlerNonNull> handlerCallback =
        new OnErrorEventHandlerNonNull(boundHandler, /* aIncumbentGlobal = */ nullptr);
      jsListener->SetHandler(handlerCallback);
    } else if (jsListener->EventName() == nsGkAtoms::onbeforeunload && win) {
      nsRefPtr<OnBeforeUnloadEventHandlerNonNull> handlerCallback =
        new OnBeforeUnloadEventHandlerNonNull(boundHandler, /* aIncumbentGlobal = */ nullptr);
      jsListener->SetHandler(handlerCallback);
    } else {
      nsRefPtr<EventHandlerNonNull> handlerCallback =
        new EventHandlerNonNull(boundHandler, /* aIncumbentGlobal = */ nullptr);
      jsListener->SetHandler(handlerCallback);
    }
  }

  return result;
}
Пример #3
0
bool SVGCircleElement::selfHasRelativeLengths() const
{
    return cx().isRelative()
        || cy().isRelative()
        || r().isRelative();
}
Пример #4
0
bool Reed_Solomon::decode(const bvec &coded_bits, const ivec &erasure_positions, bvec &decoded_message, bvec &cw_isvalid)
{
  bool decoderfailure, no_dec_failure;
  int j, i, kk, l, L, foundzeros, iterations = floor_i(static_cast<double>(coded_bits.length()) / (n * m));
  bvec mbit(m * k);
  decoded_message.set_size(iterations * k * m, false);
  cw_isvalid.set_length(iterations);

  GFX rx(q, n - 1), cx(q, n - 1), mx(q, k - 1), ex(q, n - 1), S(q, 2 * t), Xi(q, 2 * t), Gamma(q), Lambda(q),
      Psiprime(q), OldLambda(q), T(q), Omega(q);
  GFX dummy(q), One(q, (char*)"0"), Omegatemp(q);
  GF delta(q), tempsum(q), rtemp(q), temp(q), Xk(q), Xkinv(q);
  ivec errorpos;

  if ( erasure_positions.length() ) {
    it_assert(max(erasure_positions) < iterations*n, "Reed_Solomon::decode: erasure position is invalid.");
  }
  
  no_dec_failure = true;
  for (i = 0; i < iterations; i++) {
    decoderfailure = false;
    //Fix the received polynomial r(x)
    for (j = 0; j < n; j++) {
      rtemp.set(q, coded_bits.mid(i * n * m + j * m, m));
      rx[j] = rtemp;
    }
    // Fix the Erasure polynomial Gamma(x)
    // and replace erased coordinates with zeros
    rtemp.set(q, -1);
    ivec alphapow = - ones_i(2);
    Gamma = One;
    for (j = 0; j < erasure_positions.length(); j++) {
      rx[erasure_positions(j)] = rtemp;
      alphapow(1) = erasure_positions(j);
      Gamma *= (One - GFX(q, alphapow));
    }
    //Fix the syndrome polynomial S(x).
    S.clear();
    for (j = 1; j <= 2 * t; j++) {
      S[j] = rx(GF(q, b + j - 1));
    }
    // calculate the modified syndrome polynomial Xi(x) = Gamma * (1+S) - 1
    Xi = Gamma * (One + S) - One;
    // Apply Berlekam-Massey algorithm
    if (Xi.get_true_degree() >= 1) { //Errors in the received word
      // Iterate to find Lambda(x), which hold all error locations
      kk = 0;
      Lambda = One;
      L = 0;
      T = GFX(q, (char*)"-1 0");
      while (kk < 2 * t) {
        kk = kk + 1;
        tempsum = GF(q, -1);
        for (l = 1; l <= L; l++) {
          tempsum += Lambda[l] * Xi[kk - l];
        }
        delta = Xi[kk] - tempsum;
        if (delta != GF(q, -1)) {
          OldLambda = Lambda;
          Lambda -= delta * T;
          if (2 * L < kk) {
            L = kk - L;
            T = OldLambda / delta;
          }
        }
        T = GFX(q, (char*)"-1 0") * T;
      }
      // Find the zeros to Lambda(x)
      errorpos.set_size(Lambda.get_true_degree());
      foundzeros = 0;
      for (j = q - 2; j >= 0; j--) {
        if (Lambda(GF(q, j)) == GF(q, -1)) {
          errorpos(foundzeros) = (n - j) % n;
          foundzeros += 1;
          if (foundzeros >= Lambda.get_true_degree()) {
            break;
          }
        }
      }
      if (foundzeros != Lambda.get_true_degree()) {
        decoderfailure = true;
      }
      else { // Forney algorithm...
        //Compute Omega(x) using the key equation for RS-decoding
        Omega.set_degree(2 * t);
        Omegatemp = Lambda * (One + Xi);
        for (j = 0; j <= 2 * t; j++) {
          Omega[j] = Omegatemp[j];
        }
        //Find the error/erasure magnitude polynomial by treating them the same
        Psiprime = formal_derivate(Lambda*Gamma);
        errorpos = concat(errorpos, erasure_positions);
        ex.clear();
        for (j = 0; j < errorpos.length(); j++) {
          Xk = GF(q, errorpos(j));
          Xkinv = GF(q, 0) / Xk;
          // we calculate ex = - error polynomial, in order to avoid the 
          // subtraction when recunstructing the corrected codeword
          ex[errorpos(j)] = (Xk * Omega(Xkinv)) / Psiprime(Xkinv);
          if (b != 1) { // non-narrow-sense code needs corrected error magnitudes
            int correction_exp = ( errorpos(j)*(1-b) ) % n;
            ex[errorpos(j)] *= GF(q, correction_exp + ( (correction_exp < 0) ? n : 0 ));
          }
        }
        //Reconstruct the corrected codeword.
        // instead of subtracting the error/erasures, we calculated 
        // the negative error with 'ex' above
        cx = rx + ex;
        //Code word validation
        S.clear();
        for (j = 1; j <= 2 * t; j++) {
          S[j] = cx(GF(q, b + j - 1));
        }
        if (S.get_true_degree() >= 1) {
          decoderfailure = true;
        }
      }
    }
    else {
      cx = rx;
      decoderfailure = false;
    }
    //Find the message polynomial
    mbit.clear();
    if (decoderfailure == false) {
      if (cx.get_true_degree() >= 1) { // A nonzero codeword was transmitted
        if (systematic) {
          for (j = 0; j < k; j++) {
            mx[j] = cx[j];
          }
        }
        else {
          mx = divgfx(cx, g);
        }
        for (j = 0; j <= mx.get_true_degree(); j++) {
          mbit.replace_mid(j * m, mx[j].get_vectorspace());
        }
      }
    }
    else { //Decoder failure.
      // for a systematic code it is better to extract the undecoded message
      // from the received code word, i.e. obtaining a bit error
      // prob. p_b << 1/2, than setting all-zero (p_b = 1/2)
      if (systematic) {
        mbit = coded_bits.mid(i * n * m, k * m);
      }
      else {
        mbit = zeros_b(k);
      }
      no_dec_failure = false;
    }
    decoded_message.replace_mid(i * m * k, mbit);
    cw_isvalid(i) = (!decoderfailure);
  }
  return no_dec_failure;
}
Пример #5
0
void Tri2dFCBlockSolver::rhsViscous()
{
  if (order == 1 || order == 2){
    // Galerkin
    int n1,n2,n3,nn;
    double xa,ya,xb,yb,xc,yc,vr,fv[nq],gv[nq];
    Array2D<double> qc(3,nq),qac(3,nqa),cx(3,2);
    for (int n=0; n<nTri; n++){
      n1 = tri(n,0);
      n2 = tri(n,1);
      n3 = tri(n,2);
      xa = x(n1,0);
      ya = x(n1,1);
      xb = x(n2,0);
      yb = x(n2,1);
      xc = x(n3,0);
      yc = x(n3,1);
      vr = xa*(yb-yc)+xb*(yc-ya)+xc*(ya-yb);
      vr = 2./vr;
      
      for (int i=0; i<3; i++){
	for (int k=0; k<nq ; k++) qc (i,k) = q (n1,k);
	for (int k=0; k<nqa; k++) qac(i,k) = qa(n1,k);
	cx(i,0) = .5*(x(n3,1)-x(n2,1));
	cx(i,1) = .5*(x(n2,0)-x(n3,0));
	nn      = n1;
	n1      = n2;
	n2      = n3;
	n3      = nn;
      }
      
      sys->rhsVisFluxGalerkin(1,&vr,&cx(0,0),&qc(0,0),&qac(0,0),&fv[0],&gv[0]);
      for (int k=0; k<nq ; k++) d(n1,k) -=(cx(0,0)*fv[k]+cx(0,1)*gv[k]);
      for (int k=0; k<nq ; k++) d(n2,k) -=(cx(1,0)*fv[k]+cx(1,1)*gv[k]);
      for (int k=0; k<nq ; k++) d(n3,k) -=(cx(2,0)*fv[k]+cx(2,1)*gv[k]);
    }
    qc.deallocate();
    qac.deallocate();
    cx.deallocate();
  }


  else{// third-order scheme
    int m,l1,l2,n1,n2;
    double dx,dy,fk,Ax,Ay,cf,cg,a=.5;
    Array2D<double> qaxE(nne,nqaGradQa),qayE(nne,nqaGradQa);
    Array2D<double> f(nne,nq),g(nne,nq);
    Array2D<double> fx(nne,nq),gx(nne,nq),fy(nne,nq),gy(nne,nq);
    for (int n=0; n<nElem; n++){

      qaxE.set(0.);
      qayE.set(0.);
      fx.set(0.);
      fy.set(0.);
      gx.set(0.);
      gy.set(0.);

      // compute local gradients at the nodes in this element
      for (int i=0; i<nne; i++)
	for (int j=0; j<nne; j++){
	  dx = dxg(n,i,j,0);
	  dy = dxg(n,i,j,1);
	  m  = elem(n,j);
	  for (int k=0; k<nqaGradQa; k++){
	    qaxE(i,k) += qa(m,iqagrad(k))*dx;
	    qayE(i,k) += qa(m,iqagrad(k))*dy;
	  }}

      // compute viscous fluxes at the nodes in this element
      for (int i=0; i<nne; i++){
	m = elem(n,i);
	sys->rhsVisFlux(1,&q(m,0),&qa(m,0),&qaxE(i,0),&qayE(i,0),
			&f(i,0),&g(i,0));
      }

      // compute gradients of viscous fluxes
      for (int i=0; i<nne; i++)
	for (int j=0; j<nne; j++){
	  dx = dxg(n,i,j,0);
	  dy = dxg(n,i,j,1);
	  for (int k=0; k<nq ; k++){
	    fx(i,k) += f(j,k)*dx;
	    gx(i,k) += g(j,k)*dx;
	    fy(i,k) += f(j,k)*dy;
	    gy(i,k) += g(j,k)*dy;
	  }}

      // compute directed viscous fluxes and corrections
      // at edges and distribute to nodes
      for (int i=0; i<nee; i++){
	l1 = edgeE(i,0);
	l2 = edgeE(i,1);
	n1 = elem(n,l1);
	n2 = elem(n,l2);
	Ax = a*areaE(n,i,0);
	Ay = a*areaE(n,i,1);
	dx = .5*(x(n2,0)-x(n1,0));
	dy = .5*(x(n2,1)-x(n1,1));
	for (int k=0; k<nq; k++){
	  cf       = dx*(fx(l2,k)-fx(l1,k))+
		     dy*(fy(l2,k)-fy(l1,k));
	  cg       = dx*(gx(l2,k)-gx(l1,k))+
		     dy*(gy(l2,k)-gy(l1,k));
	  fk       = Ax*(f(l1,k)+f(l2,k)-cf)+Ay*(g(l1,k)+g(l2,k)-cg);
	  d(n1,k) -= fk;
	  d(n2,k) += fk;
	}}}

    qaxE.deallocate();
    qayE.deallocate();
    f.deallocate();
    g.deallocate();
    fx.deallocate();
    gx.deallocate();
    fy.deallocate();
    gy.deallocate();
  }
}
Пример #6
0
    long long runCount( const string& ns, const BSONObj &cmd, string &err, int &errCode ) {
        // Lock 'ns'.
        Client::Context cx(ns);
        Collection* collection = cx.db()->getCollection(ns);

        if (NULL == collection) {
            err = "ns missing";
            return -1;
        }

        BSONObj query = cmd.getObjectField("query");

        BSONObj hintObj;
        if (Object == cmd["hint"].type()) {
            hintObj = cmd["hint"].Obj();
        }
        else if (String == cmd["hint"].type()) {
            const std::string hint = cmd.getStringField("hint");
            hintObj = BSON("$hint" << hint);
        }

        // count of all objects
        if (query.isEmpty()) {
            return applySkipLimit(collection->numRecords(), cmd);
        }

        Runner* rawRunner;
        long long skip = cmd["skip"].numberLong();
        long long limit = cmd["limit"].numberLong();

        if (limit < 0) {
            limit = -limit;
        }

        uassertStatusOK(getRunnerCount(collection, query, hintObj, &rawRunner));
        auto_ptr<Runner> runner(rawRunner);

        // Get a pointer to the current operation. We will try to copy the planSummary
        // there so that it appears in db.currentOp() and the slow query log.
        Client& client = cc();
        CurOp* currentOp = client.curop();

        // Have we copied the planSummary to 'currentOp' yet?
        bool gotPlanSummary = false;

        // Try to copy the plan summary to the 'currentOp'.
        if (!gotPlanSummary) {
            gotPlanSummary = setPlanSummary(runner.get(), currentOp);
        }

        try {
            const ScopedRunnerRegistration safety(runner.get());
            runner->setYieldPolicy(Runner::YIELD_AUTO);

            long long count = 0;
            Runner::RunnerState state;
            while (Runner::RUNNER_ADVANCED == (state = runner->getNext(NULL, NULL))) {
                // Try to copy the plan summary to the 'currentOp'. We need to try again
                // here because we might not have chosen a plan until after the first
                // call to getNext(...).
                if (!gotPlanSummary) {
                    gotPlanSummary = setPlanSummary(runner.get(), currentOp);
                }

                if (skip > 0) {
                    --skip;
                }
                else {
                    ++count;
                    // Fast-path. There's no point in iterating all over the runner if limit
                    // is set.
                    if (count >= limit && limit != 0) {
                        break;
                    }
                }
            }

            // Try to copy the plan summary to the 'currentOp', if we haven't already. This
            // could happen if, for example, the count is 0.
            if (!gotPlanSummary) {
                gotPlanSummary = setPlanSummary(runner.get(), currentOp);
            }

            // Emulate old behavior and return the count even if the runner was killed.  This
            // happens when the underlying collection is dropped.
            return count;
        }
        catch (const DBException &e) {
            err = e.toString();
            errCode = e.getCode();
        } 
        catch (const std::exception &e) {
            err = e.what();
            errCode = 0;
        } 

        // Historically we have returned zero in many count assertion cases - see SERVER-2291.
        log() << "Count with ns: " << ns << " and query: " << query
              << " failed with exception: " << err << " code: " << errCode
              << endl;

        return -2;
    }
Пример #7
0
bool
create_window(void)
{
	WNDCLASSEX wndClass;
	ZeroMemory (&wndClass, sizeof (wndClass));
    wndClass.cbSize        = sizeof (wndClass);
    wndClass.style         = CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc   = WndProc;
    wndClass.cbClsExtra    = 0;
    wndClass.cbWndExtra    = 0;
    wndClass.hInstance     = hInst;
    wndClass.hIcon         = LoadIcon (NULL, IDI_APPLICATION);
    wndClass.hIconSm       = NULL;
    wndClass.hCursor       = LoadCursor (NULL, IDC_ARROW);
    wndClass.hbrBackground = (HBRUSH) GetStockObject(GRAY_BRUSH);
    wndClass.lpszMenuName  = NULL;
    wndClass.lpszClassName = "blackscreen";

        if (!RegisterClassEx(&wndClass)) {
 //               return false;
        }

        RECT clientRect;
        clientRect.left = 0;
        clientRect.top = 0;
        clientRect.right = GetSystemMetrics(SM_CXSCREEN);
        clientRect.bottom = GetSystemMetrics(SM_CYSCREEN);

        UINT x(GetSystemMetrics(SM_XVIRTUALSCREEN));
        UINT y(GetSystemMetrics(SM_YVIRTUALSCREEN));
        UINT cx(GetSystemMetrics(SM_CXVIRTUALSCREEN));
        UINT cy(GetSystemMetrics(SM_CYVIRTUALSCREEN));

        clientRect.left = x;
        clientRect.top = y;
        clientRect.right = x + cx;
        clientRect.bottom = y + cy;

        AdjustWindowRect (&clientRect, WS_CAPTION, FALSE);
        hwnd = CreateWindowEx (0,
                               "blackscreen",
                               "blackscreen",
                               WS_POPUP  | WS_CLIPSIBLINGS | WS_CLIPCHILDREN|WS_BORDER,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               cx,
                               cy,
                               NULL,
                               NULL,
                               hInst,
                               NULL);
		typedef DWORD (WINAPI *PSLWA)(HWND, DWORD, BYTE, DWORD);

	PSLWA pSetLayeredWindowAttributes=NULL;
	/*
	* Code that follows allows the program to run in 
	* environment other than windows 2000
	* without crashing only difference being that 
	* there will be no transparency as 
	* the SetLayeredAttributes function is available only in
	* windows 2000
	*/
	HMODULE hDLL = LoadLibrary ("user32");
	if (hDLL) pSetLayeredWindowAttributes = (PSLWA) GetProcAddress(hDLL,"SetLayeredWindowAttributes");
	/*
	* Make the windows a layered window
	*/

#ifndef _X64
	LONG style = GetWindowLong(hwnd, GWL_STYLE);
	style = GetWindowLong(hwnd, GWL_STYLE);
	style &= ~(WS_DLGFRAME | WS_THICKFRAME);
	SetWindowLong(hwnd, GWL_STYLE, style);
#else
	LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE);
	style = GetWindowLongPtr(hwnd, GWL_STYLE);
	style &= ~(WS_DLGFRAME | WS_THICKFRAME);
	SetWindowLongPtr(hwnd, GWL_STYLE, style);
#endif

	if (pSetLayeredWindowAttributes != NULL) {
#ifndef _X64
		SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) |WS_EX_LAYERED|WS_EX_TRANSPARENT|WS_EX_TOPMOST);
#else
		SetWindowLongPtr (hwnd, GWL_EXSTYLE, GetWindowLongPtr(hwnd, GWL_EXSTYLE) |WS_EX_LAYERED|WS_EX_TRANSPARENT|WS_EX_TOPMOST);
#endif
	    ShowWindow (hwnd, SW_SHOWNORMAL);
	}
	if (pSetLayeredWindowAttributes != NULL) {
	/**
	* Second parameter RGB(255,255,255) sets the colorkey to white
	* LWA_COLORKEY flag indicates that color key is valid
	* LWA_ALPHA indicates that ALphablend parameter (factor)
	* is valid
	*/
	pSetLayeredWindowAttributes (hwnd, RGB(255,255,255), 255, LWA_ALPHA);
	}
	SetWindowPos(hwnd,HWND_TOPMOST,x,y,cx,cy, SWP_FRAMECHANGED|SWP_NOACTIVATE);
//SM_CXVIRTUALSCREEN
	return true;
}
NS_IMETHODIMP
mozJSComponentLoader::LoadModule(nsILocalFile* aComponentFile,
                                 nsIModule* *aResult)
{
    nsresult rv;

    nsCAutoString leafName;
    aComponentFile->GetNativeLeafName(leafName);
    if (!StringTail(leafName, 3).LowerCaseEqualsLiteral(".js"))
        return NS_ERROR_INVALID_ARG;

    if (!mInitialized) {
        rv = ReallyInit();
        if (NS_FAILED(rv))
            return rv;
    }

    nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(aComponentFile));
    if (!lfhash) {
        NS_ERROR("nsLocalFile not implementing nsIHashable");
        return NS_NOINTERFACE;
    }

    ModuleEntry* mod;
    if (mModules.Get(lfhash, &mod)) {
        NS_ASSERTION(mod->module, "Bad hashtable data!");
        NS_ADDREF(*aResult = mod->module);
        return NS_OK;
    }

    nsAutoPtr<ModuleEntry> entry(new ModuleEntry);
    if (!entry)
        return NS_ERROR_OUT_OF_MEMORY;

    rv = GlobalForLocation(aComponentFile, &entry->global, &entry->location);
    if (NS_FAILED(rv)) {
#ifdef DEBUG_shaver
        fprintf(stderr, "GlobalForLocation failed!\n");
#endif
        return rv;
    }

    nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID,
                                               &rv);
    if (NS_FAILED(rv))
        return rv;

    nsCOMPtr<nsIComponentManager> cm;
    rv = NS_GetComponentManager(getter_AddRefs(cm));
    if (NS_FAILED(rv))
        return rv;

    JSCLContextHelper cx(mContext);

    JSObject* cm_jsobj;
    nsCOMPtr<nsIXPConnectJSObjectHolder> cm_holder;
    rv = xpc->WrapNative(cx, entry->global, cm, 
                         NS_GET_IID(nsIComponentManager),
                         getter_AddRefs(cm_holder));

    if (NS_FAILED(rv)) {
#ifdef DEBUG_shaver
        fprintf(stderr, "WrapNative(%p,%p,nsIComponentManager) failed: %x\n",
                (void *)(JSContext*)cx, (void *)mCompMgr, rv);
#endif
        return rv;
    }

    rv = cm_holder->GetJSObject(&cm_jsobj);
    if (NS_FAILED(rv)) {
#ifdef DEBUG_shaver
        fprintf(stderr, "GetJSObject of ComponentManager failed\n");
#endif
        return rv;
    }

    JSObject* file_jsobj;
    nsCOMPtr<nsIXPConnectJSObjectHolder> file_holder;
    rv = xpc->WrapNative(cx, entry->global, aComponentFile, 
                         NS_GET_IID(nsIFile),
                         getter_AddRefs(file_holder));

    if (NS_FAILED(rv)) {
        return rv;
    }

    rv = file_holder->GetJSObject(&file_jsobj);
    if (NS_FAILED(rv)) {
        return rv;
    }

    JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);

    jsval argv[2], retval, NSGetModule_val;

    if (!JS_GetProperty(cx, entry->global, "NSGetModule", &NSGetModule_val) ||
        JSVAL_IS_VOID(NSGetModule_val)) {
        return NS_ERROR_FAILURE;
    }

    if (JS_TypeOfValue(cx, NSGetModule_val) != JSTYPE_FUNCTION) {
        nsCAutoString path;
        aComponentFile->GetNativePath(path);

        JS_ReportError(cx, "%s has NSGetModule property that is not a function",
                       path.get());
        return NS_ERROR_FAILURE;
    }
    
    argv[0] = OBJECT_TO_JSVAL(cm_jsobj);
    argv[1] = OBJECT_TO_JSVAL(file_jsobj);
    if (!JS_CallFunctionValue(cx, entry->global, NSGetModule_val,
                              2, argv, &retval)) {
        return NS_ERROR_FAILURE;
    }

#ifdef DEBUG_shaver_off
    JSString *s = JS_ValueToString(cx, retval);
    fprintf(stderr, "mJCL: %s::NSGetModule returned %s\n",
            registryLocation, JS_GetStringBytes(s));
#endif

    JSObject *jsModuleObj;
    if (!JS_ValueToObject(cx, retval, &jsModuleObj)) {
        /* XXX report error properly */
        return NS_ERROR_FAILURE;
    }

    rv = xpc->WrapJS(cx, jsModuleObj,
                     NS_GET_IID(nsIModule), getter_AddRefs(entry->module));
    if (NS_FAILED(rv)) {
        /* XXX report error properly */
#ifdef DEBUG
        fprintf(stderr, "mJCL: couldn't get nsIModule from jsval\n");
#endif
        return rv;
    }

    // Cache this module for later
    if (!mModules.Put(lfhash, entry))
        return NS_ERROR_OUT_OF_MEMORY;

    NS_ADDREF(*aResult = entry->module);

    // The hash owns the ModuleEntry now, forget about it
    entry.forget();

    return NS_OK;
}
Пример #9
0
    long long runCount( const string& ns, const BSONObj &cmd, string &err, int &errCode ) {
        // Lock 'ns'.
        Client::Context cx(ns);
        Collection* collection = cx.db()->getCollection(ns);

        if (NULL == collection) {
            err = "ns missing";
            return -1;
        }

        BSONObj query = cmd.getObjectField("query");
        const std::string hint = cmd.getStringField("hint");
        const BSONObj hintObj = hint.empty() ? BSONObj() : BSON("$hint" << hint);
        
        // count of all objects
        if (query.isEmpty()) {
            return applySkipLimit(collection->numRecords(), cmd);
        }

        Runner* rawRunner;
        long long skip = cmd["skip"].numberLong();
        long long limit = cmd["limit"].numberLong();

        if (limit < 0) {
            limit = -limit;
        }

        uassertStatusOK(getRunnerCount(collection, query, hintObj, &rawRunner));
        auto_ptr<Runner> runner(rawRunner);

        try {
            const ScopedRunnerRegistration safety(runner.get());
            runner->setYieldPolicy(Runner::YIELD_AUTO);

            long long count = 0;
            Runner::RunnerState state;
            while (Runner::RUNNER_ADVANCED == (state = runner->getNext(NULL, NULL))) {
                if (skip > 0) {
                    --skip;
                }
                else {
                    ++count;
                    // Fast-path. There's no point in iterating all over the runner if limit
                    // is set.
                    if (count >= limit && limit != 0) {
                        break;
                    }
                }
            }

            // Emulate old behavior and return the count even if the runner was killed.  This
            // happens when the underlying collection is dropped.
            return count;
        }
        catch (const DBException &e) {
            err = e.toString();
            errCode = e.getCode();
        } 
        catch (const std::exception &e) {
            err = e.what();
            errCode = 0;
        } 

        // Historically we have returned zero in many count assertion cases - see SERVER-2291.
        log() << "Count with ns: " << ns << " and query: " << query
              << " failed with exception: " << err << " code: " << errCode
              << endl;

        return -2;
    }
bool SVGCircleElement::hasRelativeValues() const
{
    return (cx().isRelative() || cy().isRelative() || r().isRelative());
}
Пример #11
0
    long long runCount(OperationContext* txn,
                       const string& ns,
                       const BSONObj &cmd,
                       string &err,
                       int &errCode) {
        // Lock 'ns'.
        Client::Context cx(txn, ns);
        Collection* collection = cx.db()->getCollection(txn, ns);
        const string& dbname = cx.db()->name();

        if (NULL == collection) {
            err = "ns missing";
            return -1;
        }

        CountRequest request;
        CmdCount* countComm = static_cast<CmdCount*>(Command::findCommand("count"));
        Status parseStatus = countComm->parseRequest(dbname, cmd, &request);
        if (!parseStatus.isOK()) {
            err = parseStatus.reason();
            errCode = parseStatus.code();
            return -1;
        }

        if (request.query.isEmpty()) {
            return applySkipLimit(collection->numRecords(txn), cmd);
        }

        PlanExecutor* rawExec;
        Status getExecStatus = getExecutorCount(txn, collection, request, &rawExec);
        if (!getExecStatus.isOK()) {
            err = getExecStatus.reason();
            errCode = parseStatus.code();
            return -1;
        }
        scoped_ptr<PlanExecutor> exec(rawExec);

        // Store the plan summary string in CurOp.
        if (NULL != txn->getCurOp()) {
            PlanSummaryStats stats;
            Explain::getSummaryStats(exec.get(), &stats);
            txn->getCurOp()->debug().planSummary = stats.summaryStr.c_str();
        }

        const ScopedExecutorRegistration safety(exec.get());

        Status execPlanStatus = exec->executePlan();
        if (!execPlanStatus.isOK()) {
            err = execPlanStatus.reason();
            errCode = execPlanStatus.code();
            return -2;
        }

        // Plan is done executing. We just need to pull the count out of the root stage.
        invariant(STAGE_COUNT == exec->getRootStage()->stageType());
        CountStage* countStage = static_cast<CountStage*>(exec->getRootStage());
        const CountStats* countStats =
            static_cast<const CountStats*>(countStage->getSpecificStats());

        return countStats->nCounted;
    }
Пример #12
0
Cvirtual_image Cshp_file::vimage() const
{
    Cvirtual_binary image;
    decode(image.write_start(cb_video()));
    return Cvirtual_image(image, cx(), cf() * cy(), cb_pixel());
}
Пример #13
0
 static void onRemoveSlot(Slot *s) {
   s->unroot(cx());
 }
Пример #14
0
        bool runNoDirectClient( const string& ns , 
                                const BSONObj& queryOriginal , const BSONObj& fields , const BSONObj& update , 
                                bool upsert , bool returnNew , bool remove ,
                                BSONObjBuilder& result , string& errmsg ) {
            
            
            Lock::DBWrite lk( ns );
            Client::Context cx( ns );

            BSONObj doc;
            
            bool found = Helpers::findOne( ns.c_str() , queryOriginal , doc );

            BSONObj queryModified = queryOriginal;
            if ( found && doc["_id"].type() && ! isSimpleIdQuery( queryOriginal ) ) {
                // we're going to re-write the query to be more efficient
                // we have to be a little careful because of positional operators
                // maybe we can pass this all through eventually, but right now isn't an easy way
                
                bool hasPositionalUpdate = false;
                {
                    // if the update has a positional piece ($)
                    // then we need to pull all query parts in
                    // so here we check for $
                    // a little hacky
                    BSONObjIterator i( update );
                    while ( i.more() ) {
                        const BSONElement& elem = i.next();
                        
                        if ( elem.fieldName()[0] != '$' || elem.type() != Object )
                            continue;

                        BSONObjIterator j( elem.Obj() );
                        while ( j.more() ) {
                            if ( str::contains( j.next().fieldName(), ".$" ) ) {
                                hasPositionalUpdate = true;
                                break;
                            }
                        }
                    }
                }

                BSONObjBuilder b( queryOriginal.objsize() + 10 );
                b.append( doc["_id"] );
                
                bool addedAtomic = false;

                BSONObjIterator i( queryOriginal );
                while ( i.more() ) {
                    const BSONElement& elem = i.next();

                    if ( str::equals( "_id" , elem.fieldName() ) ) {
                        // we already do _id
                        continue;
                    }
                    
                    if ( ! hasPositionalUpdate ) {
                        // if there is a dotted field, accept we may need more query parts
                        continue;
                    }
                    
                    if ( ! addedAtomic ) {
                        b.appendBool( "$atomic" , true );
                        addedAtomic = true;
                    }

                    b.append( elem );
                }
                queryModified = b.obj();
            }

            if ( remove ) {
                _appendHelper( result , doc , found , fields );
                if ( found ) {
                    deleteObjects( ns.c_str() , queryModified , true , true );
                    BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
                    le.appendNumber( "n" , 1 );
                    le.done();
                }
            }
            else {
                // update
                if ( ! found && ! upsert ) {
                    // didn't have it, and am not upserting
                    _appendHelper( result , doc , found , fields );
                }
                else {
                    // we found it or we're updating
                    
                    if ( ! returnNew ) {
                        _appendHelper( result , doc , found , fields );
                    }
                    
                    const NamespaceString requestNs(ns);
                    UpdateRequest request(requestNs);

                    request.setQuery(queryModified);
                    request.setUpdates(update);
                    request.setUpsert(upsert);
                    request.setUpdateOpLog();

                    UpdateResult res = mongo::update(request, &cc().curop()->debug());

                    if ( returnNew ) {
                        if ( res.upserted.isSet() ) {
                            queryModified = BSON( "_id" << res.upserted );
                        }
                        else if ( queryModified["_id"].type() ) {
                            // we do this so that if the update changes the fields, it still matches
                            queryModified = queryModified["_id"].wrap();
                        }
                        if ( ! Helpers::findOne( ns.c_str() , queryModified , doc ) ) {
                            errmsg = str::stream() << "can't find object after modification  " 
                                                   << " ns: " << ns 
                                                   << " queryModified: " << queryModified 
                                                   << " queryOriginal: " << queryOriginal;
                            log() << errmsg << endl;
                            return false;
                        }
                        _appendHelper( result , doc , true , fields );
                    }
                    
                    BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
                    le.appendBool( "updatedExisting" , res.existing );
                    le.appendNumber( "n" , res.numMatched );
                    if ( res.upserted.isSet() )
                        le.append( "upserted" , res.upserted );
                    le.done();
                    
                }
            }
            
            return true;
        }
Пример #15
0
bool SVGEllipseElement::hasRelativeValues() const
{
    return (cx().isRelative() || cy().isRelative() ||
            rx().isRelative() || ry().isRelative());
}
nsresult
mozJSComponentLoader::GlobalForLocation(nsILocalFile *aComponent,
                                        JSObject **aGlobal,
                                        char **aLocation)
{
    nsresult rv;

    JSPrincipals* jsPrincipals = nsnull;
    JSCLContextHelper cx(mContext);

#ifndef XPCONNECT_STANDALONE
    rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
    NS_ENSURE_SUCCESS(rv, rv);

    JSPrincipalsHolder princHolder(mContext, jsPrincipals);
#endif

    nsCOMPtr<nsIXPCScriptable> backstagePass;
    rv = mRuntimeService->GetBackstagePass(getter_AddRefs(backstagePass));
    NS_ENSURE_SUCCESS(rv, rv);

    JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);

    nsCOMPtr<nsIXPConnect> xpc =
        do_GetService(kXPConnectServiceContractID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Make sure InitClassesWithNewWrappedGlobal() installs the
    // backstage pass as the global in our compilation context.
    JS_SetGlobalObject(cx, nsnull);

    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                              NS_GET_IID(nsISupports),
                                              nsIXPConnect::
                                                  FLAG_SYSTEM_GLOBAL_OBJECT,
                                              getter_AddRefs(holder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *global;
    rv = holder->GetJSObject(&global);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineFunctions(cx, global, gGlobalFun)) {
        return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
    rv = xpc->WrapNative(cx, global, aComponent,
                         NS_GET_IID(nsILocalFile),
                         getter_AddRefs(locationHolder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *locationObj;
    rv = locationHolder->GetJSObject(&locationObj);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineProperty(cx, global, "__LOCATION__",
                           OBJECT_TO_JSVAL(locationObj), nsnull, nsnull, 0)) {
        return NS_ERROR_FAILURE;
    }

    nsCAutoString nativePath;
    // Quick hack to unbust XPCONNECT_STANDALONE.
    // This leaves the jsdebugger with a non-URL pathname in the 
    // XPCONNECT_STANDALONE case - but at least it builds and runs otherwise.
    // See: http://bugzilla.mozilla.org/show_bug.cgi?id=121438
#ifdef XPCONNECT_STANDALONE
    localFile->GetNativePath(nativePath);
#else
    NS_GetURLSpecFromFile(aComponent, nativePath);
#endif

    // Before compiling the script, first check to see if we have it in
    // the fastload file.  Note: as a rule, fastload errors are not fatal
    // to loading the script, since we can always slow-load.
    nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);

    // Save the old state and restore it upon return
    FastLoadStateHolder flState(flSvc);
    PRBool fastLoading = PR_FALSE;

    if (NS_SUCCEEDED(rv)) {
        rv = StartFastLoad(flSvc);
        if (NS_SUCCEEDED(rv)) {
            fastLoading = PR_TRUE;
        }
    }

    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), nativePath);
    NS_ENSURE_SUCCESS(rv, rv);

    JSScript *script = nsnull;

    if (fastLoading) {
        rv = ReadScript(flSvc, nativePath.get(), uri, cx, &script);
        if (NS_SUCCEEDED(rv)) {
            LOG(("Successfully loaded %s from fastload\n", nativePath.get()));
            fastLoading = PR_FALSE; // no need to write out the script
        } else if (rv == NS_ERROR_NOT_AVAILABLE) {
            // This is ok, it just means the script is not yet in the
            // fastload file.
            rv = NS_OK;
        } else {
            LOG(("Failed to deserialize %s\n", nativePath.get()));

            // Remove the fastload file, it may be corrupted.
            LOG(("Invalid fastload file detected, removing it\n"));
            nsCOMPtr<nsIObjectOutputStream> objectOutput;
            flSvc->GetOutputStream(getter_AddRefs(objectOutput));
            if (objectOutput) {
                flSvc->SetOutputStream(nsnull);
                objectOutput->Close();
            }
            nsCOMPtr<nsIObjectInputStream> objectInput;
            flSvc->GetInputStream(getter_AddRefs(objectInput));
            if (objectInput) {
                flSvc->SetInputStream(nsnull);
                objectInput->Close();
            }
            if (mFastLoadFile) {
                mFastLoadFile->Remove(PR_FALSE);
            }
            fastLoading = PR_FALSE;
        }
    }


    if (!script || NS_FAILED(rv)) {
        // The script wasn't in the fastload cache, so compile it now.
        LOG(("Slow loading %s\n", nativePath.get()));

#ifdef HAVE_PR_MEMMAP
        PRInt64 fileSize;
        rv = aComponent->GetFileSize(&fileSize);
        if (NS_FAILED(rv))
            return rv;

        PRInt64 maxSize;
        LL_UI2L(maxSize, PR_UINT32_MAX);
        if (LL_CMP(fileSize, >, maxSize)) {
            NS_ERROR("file too large");
            return NS_ERROR_FAILURE;
        }

        PRFileDesc *fileHandle;
        rv = aComponent->OpenNSPRFileDesc(PR_RDONLY, 0, &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        // Make sure the file is closed, no matter how we return.
        FileAutoCloser fileCloser(fileHandle);

        PRFileMap *map = PR_CreateFileMap(fileHandle, fileSize,
                                          PR_PROT_READONLY);
        if (!map) {
            NS_ERROR("Failed to create file map");
            return NS_ERROR_FAILURE;
        }

        // Make sure the file map is closed, no matter how we return.
        FileMapAutoCloser mapCloser(map);

        PRUint32 fileSize32;
        LL_L2UI(fileSize32, fileSize);

        char *buf = static_cast<char*>(PR_MemMap(map, 0, fileSize32));
        if (!buf) {
            NS_WARNING("Failed to map file");
            return NS_ERROR_FAILURE;
        }

        script = JS_CompileScriptForPrincipals(cx, global,
                                               jsPrincipals,
                                               buf, fileSize32,
                                               nativePath.get(), 1);
        PR_MemUnmap(buf, fileSize32);

#else  /* HAVE_PR_MEMMAP */

        /**
         * No memmap implementation, so fall back to using
         * JS_CompileFileHandleForPrincipals().
         */

        FILE *fileHandle;
        rv = aComponent->OpenANSIFileDesc("r", &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        script = JS_CompileFileHandleForPrincipals(cx, global,
                                                   nativePath.get(),
                                                   fileHandle, jsPrincipals);

        /* JS will close the filehandle after compilation is complete. */

#endif /* HAVE_PR_MEMMAP */
    }
Пример #17
0
Path SVGEllipseElement::toPathData() const
{
    return Path::createEllipse(FloatPoint(cx().value(), cy().value()),
                               rx().value(), ry().value());
}
Пример #18
0
        bool runNoDirectClient( const string& ns , 
                                const BSONObj& queryOriginal , const BSONObj& fields , const BSONObj& update , 
                                bool upsert , bool returnNew , bool remove ,
                                BSONObjBuilder& result ) {
            
            
            Lock::DBWrite lk( ns );
            Client::Context cx( ns );

            BSONObj doc;
            
            bool found = Helpers::findOne( ns.c_str() , queryOriginal , doc );

            BSONObj queryModified = queryOriginal;
            if ( found && doc["_id"].type() && ! isSimpleIdQuery( queryOriginal ) ) {
                // we're going to re-write the query to be more efficient
                // we have to be a little careful because of positional operators
                // maybe we can pass this all through eventually, but right now isn't an easy way
                BSONObjBuilder b( queryOriginal.objsize() + 10 );
                b.append( doc["_id"] );
                
                bool addedAtomic = false;

                BSONObjIterator i( queryOriginal );
                while ( i.more() ) {
                    const BSONElement& elem = i.next();

                    if ( str::equals( "_id" , elem.fieldName() ) ) {
                        // we already do _id
                        continue;
                    }
                    
                    if ( ! str::contains( elem.fieldName() , '.' ) ) {
                        // if there is a dotted field, accept we may need more query parts
                        continue;
                    }
                    
                    if ( ! addedAtomic ) {
                        b.appendBool( "$atomic" , true );
                        addedAtomic = true;
                    }

                    b.append( elem );
                }
                queryModified = b.obj();
            }

            if ( remove ) {
                _appendHelper( result , doc , found , fields );
                if ( found ) {
                    deleteObjects( ns.c_str() , queryModified , true , true );
                    BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
                    le.appendNumber( "n" , 1 );
                    le.done();
                }
            }
            else {
                // update
                if ( ! found && ! upsert ) {
                    // didn't have it, and am not upserting
                    _appendHelper( result , doc , found , fields );
                }
                else {
                    // we found it or we're updating
                    
                    if ( ! returnNew ) {
                        _appendHelper( result , doc , found , fields );
                    }
                    
                    UpdateResult res = updateObjects( ns.c_str() , update , queryModified , upsert , false , true , cc().curop()->debug() );
                    
                    if ( returnNew ) {
                        if ( ! res.existing && res.upserted.isSet() ) {
                            queryModified = BSON( "_id" << res.upserted );
                        }
                        log() << "queryModified: " << queryModified << endl;
                        verify( Helpers::findOne( ns.c_str() , queryModified , doc ) );
                        _appendHelper( result , doc , true , fields );
                    }
                    
                    BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
                    le.appendBool( "updatedExisting" , res.existing );
                    le.appendNumber( "n" , res.num );
                    if ( res.upserted.isSet() )
                        le.append( "upserted" , res.upserted );
                    le.done();
                    
                }
            }
            
            return true;
        }
Пример #19
0
void main() {

  //* Initialize parameters (system size, grid spacing, etc.)
  double eps0 = 8.8542e-12;   // Permittivity (C^2/(N m^2))
  int N = 64;   // Number of grid points on a side (square grid)
  double L = 1;    // System size
  double h = L/N;  // Grid spacing for periodic boundary conditions
  Matrix x(N), y(N);
  int i,j;
  for( i=1; i<=N; i++ )
    x(i) = (i-0.5)*h;  // Coordinates of grid points
  y = x;               // Square grid
  cout << "System is a square of length " << L << endl;

  //* Set up charge density rho(i,j)
  Matrix rho(N,N);
  rho.set(0.0);     // Initialize charge density to zero
  cout << "Enter number of line charges: "; int M; cin >> M;
  for( i=1; i<=M; i++ ) {
    cout << "For charge #" << i << endl;
    cout << "Enter x coordinate: "; double xc; cin >> xc;
    cout << "Enter y coordinate: "; double yc; cin >> yc;
    int ii = (int)(xc/h) + 1;    // Place charge at nearest
    int jj = (int)(yc/h) + 1;    // grid point
    cout << "Enter charge density: "; double q; cin >> q;
    rho(ii,jj) += q/(h*h);
  }

  //* Compute matrix P
  const double pi = 3.141592654;
  Matrix cx(N), cy(N);
  for( i=1; i<=N; i++ )
    cx(i) = cos((2*pi/N)*(i-1));
  cy = cx;
  Matrix RealP(N,N), ImagP(N,N);
  double numerator = -h*h/(2*eps0);
  double tinyNumber = 1e-20;  // Avoids division by zero
  for( i=1; i<=N; i++ )
   for( j=1; j<=N; j++ )
     RealP(i,j) = numerator/(cx(i)+cy(j)-2+tinyNumber);
  ImagP.set(0.0);

  //* Compute potential using MFT method
  Matrix RealR(N,N), ImagR(N,N), RealF(N,N), ImagF(N,N);
  for( i=1; i<=N; i++ )
   for( j=1; j<=N; j++ ) {
     RealR(i,j) = rho(i,j);
     ImagR(i,j) = 0.0;       // Copy rho into R for input to fft2
   }
  fft2(RealR,ImagR);   // Transform rho into wavenumber domain
  // Compute phi in the wavenumber domain
  for( i=1; i<=N; i++ )
   for( j=1; j<=N; j++ ) {
    RealF(i,j) = RealR(i,j)*RealP(i,j) - ImagR(i,j)*ImagP(i,j);
    ImagF(i,j) = RealR(i,j)*ImagP(i,j) + ImagR(i,j)*RealP(i,j);
   }
  Matrix phi(N,N);
  ifft2(RealF,ImagF);    // Inv. transf. phi into the coord. domain
  for( i=1; i<=N; i++ )
   for( j=1; j<=N; j++ )
     phi(i,j) = RealF(i,j);

  //* Print out the plotting variables: x, y, phi
  ofstream xOut("x.txt"), yOut("y.txt"), phiOut("phi.txt");
  for( i=1; i<=N; i++ ) {
    xOut << x(i) << endl;
    yOut << y(i) << endl;
    for( j=1; j<N; j++ )
      phiOut << phi(i,j) << ", ";
    phiOut << phi(i,N) << endl;
  }
}
Пример #20
0
    // Returns false when request includes 'end'
    void assembleResponse( Message &m, DbResponse &dbresponse, const HostAndPort& remote ) {

        // before we lock...
        int op = m.operation();
        bool isCommand = false;
        const char *ns = m.singleData()->_data + 4;

        if ( op == dbQuery ) {
            if( strstr(ns, ".$cmd") ) {
                isCommand = true;
                opwrite(m);
                if( strstr(ns, ".$cmd.sys.") ) {
                    if( strstr(ns, "$cmd.sys.inprog") ) {
                        inProgCmd(m, dbresponse);
                        return;
                    }
                    if( strstr(ns, "$cmd.sys.killop") ) {
                        killOp(m, dbresponse);
                        return;
                    }
                    if( strstr(ns, "$cmd.sys.unlock") ) {
                        unlockFsync(ns, m, dbresponse);
                        return;
                    }
                }
            }
            else {
                opread(m);
            }
        }
        else if( op == dbGetMore ) {
            opread(m);
        }
        else {
            opwrite(m);
        }

        globalOpCounters.gotOp( op , isCommand );

        Client& c = cc();
        if ( c.getAuthenticationInfo() )
            c.getAuthenticationInfo()->startRequest();
        
        auto_ptr<CurOp> nestedOp;
        CurOp* currentOpP = c.curop();
        if ( currentOpP->active() ) {
            nestedOp.reset( new CurOp( &c , currentOpP ) );
            currentOpP = nestedOp.get();
        }
        else {
            c.newTopLevelRequest();
        }

        CurOp& currentOp = *currentOpP;
        currentOp.reset(remote,op);

        OpDebug& debug = currentOp.debug();
        debug.op = op;

        long long logThreshold = cmdLine.slowMS;
        bool shouldLog = logLevel >= 1;

        if ( op == dbQuery ) {
            if ( handlePossibleShardedMessage( m , &dbresponse ) )
                return;
            receivedQuery(c , dbresponse, m );
        }
        else if ( op == dbGetMore ) {
            if ( ! receivedGetMore(dbresponse, m, currentOp) )
                shouldLog = true;
        }
        else if ( op == dbMsg ) {
            // deprecated - replaced by commands
            char *p = m.singleData()->_data;
            int len = strlen(p);
            if ( len > 400 )
                out() << curTimeMillis64() % 10000 <<
                      " long msg received, len:" << len << endl;

            Message *resp = new Message();
            if ( strcmp( "end" , p ) == 0 )
                resp->setData( opReply , "dbMsg end no longer supported" );
            else
                resp->setData( opReply , "i am fine - dbMsg deprecated");

            dbresponse.response = resp;
            dbresponse.responseTo = m.header()->id;
        }
        else {
            try {
                const NamespaceString nsString( ns );

                // The following operations all require authorization.
                // dbInsert, dbUpdate and dbDelete can be easily pre-authorized,
                // here, but dbKillCursors cannot.
                if ( op == dbKillCursors ) {
                    currentOp.ensureStarted();
                    logThreshold = 10;
                    receivedKillCursors(m);
                }
                else if ( !nsString.isValid() ) {
                    // Only killCursors doesn't care about namespaces
                    uassert( 16257, str::stream() << "Invalid ns [" << ns << "]", false );
                }
                else if ( ! c.getAuthenticationInfo()->isAuthorized(
                                  nsToDatabase( m.singleData()->_data + 4 ) ) ) {
                    setLastError(0, "unauthorized");
                }
                else if ( op == dbInsert ) {
                    receivedInsert(m, currentOp);
                }
                else if ( op == dbUpdate ) {
                    receivedUpdate(m, currentOp);
                }
                else if ( op == dbDelete ) {
                    receivedDelete(m, currentOp);
                }
                else {
                    mongo::log() << "    operation isn't supported: " << op << endl;
                    currentOp.done();
                    shouldLog = true;
                }
            }
            catch ( UserException& ue ) {
                tlog(3) << " Caught Assertion in " << opToString(op) << ", continuing "
                        << ue.toString() << endl;
                debug.exceptionInfo = ue.getInfo();
            }
            catch ( AssertionException& e ) {
                tlog(3) << " Caught Assertion in " << opToString(op) << ", continuing "
                        << e.toString() << endl;
                debug.exceptionInfo = e.getInfo();
                shouldLog = true;
            }
        }
        currentOp.ensureStarted();
        currentOp.done();
        debug.executionTime = currentOp.totalTimeMillis();

        logThreshold += currentOp.getExpectedLatencyMs();

        if ( shouldLog || debug.executionTime > logThreshold ) {
            mongo::tlog() << debug.report( currentOp ) << endl;
        }

        if ( currentOp.shouldDBProfile( debug.executionTime ) ) {
            // performance profiling is on
            if ( Lock::isReadLocked() ) {
                mongo::log(1) << "note: not profiling because recursive read lock" << endl;
            }
            else if ( lockedForWriting() ) {
                mongo::log(1) << "note: not profiling because doing fsync+lock" << endl;
            }
            else {
                Lock::DBWrite lk( currentOp.getNS() );
                if ( dbHolder()._isLoaded( nsToDatabase( currentOp.getNS() ) , dbpath ) ) {
                    Client::Context cx( currentOp.getNS(), dbpath, false );
                    profile(c , currentOp );
                }
                else {
                    mongo::log() << "note: not profiling because db went away - probably a close on: " << currentOp.getNS() << endl;
                }
            }
        }
        
        debug.reset();
    } /* assembleResponse() */
Пример #21
0
	pos2<T> center() const {
	  T x = cx();
	  T y = cy();
	  return pos2<T>(x,y);
	}
Пример #22
0
Path SVGCircleElement::toPathData() const
{
    return Path::createCircle(FloatPoint(cx().value(this), cy().value(this)), r().value(this));
}
void
AutoJSAPI::ReportException()
{
  if (!HasException()) {
    return;
  }

  // AutoJSAPI uses a JSAutoNullableCompartment, and may be in a null
  // compartment when the destructor is called. However, the JS engine
  // requires us to be in a compartment when we fetch the pending exception.
  // In this case, we enter the privileged junk scope and don't dispatch any
  // error events.
  JS::Rooted<JSObject*> errorGlobal(cx(), JS::CurrentGlobalOrNull(cx()));
  if (!errorGlobal) {
    if (mIsMainThread) {
      errorGlobal = xpc::PrivilegedJunkScope();
    } else {
      errorGlobal = workers::GetCurrentThreadWorkerGlobal();
    }
  }
  JSAutoCompartment ac(cx(), errorGlobal);
  JS::Rooted<JS::Value> exn(cx());
  js::ErrorReport jsReport(cx());
  if (StealException(&exn) &&
      jsReport.init(cx(), exn, js::ErrorReport::WithSideEffects)) {
    if (mIsMainThread) {
      RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport();

      RefPtr<nsGlobalWindow> win = xpc::WindowGlobalOrNull(errorGlobal);
      if (!win) {
        // We run addons in a separate privileged compartment, but they still
        // expect to trigger the onerror handler of their associated DOM Window.
        win = xpc::AddonWindowOrNull(errorGlobal);
      }
      nsPIDOMWindowInner* inner = win ? win->AsInner() : nullptr;
      xpcReport->Init(jsReport.report(), jsReport.toStringResult().c_str(),
                      nsContentUtils::IsCallerChrome(),
                      inner ? inner->WindowID() : 0);
      if (inner && jsReport.report()->errorNumber != JSMSG_OUT_OF_MEMORY) {
        JS::RootingContext* rcx = JS::RootingContext::get(cx());
        DispatchScriptErrorEvent(inner, rcx, xpcReport, exn);
      } else {
        JS::Rooted<JSObject*> stack(cx(),
          xpc::FindExceptionStackForConsoleReport(inner, exn));
        xpcReport->LogToConsoleWithStack(stack);
      }
    } else {
      // On a worker, we just use the worker error reporting mechanism and don't
      // bother with xpc::ErrorReport.  This will ensure that all the right
      // events (which are a lot more complicated than in the window case) get
      // fired.
      workers::WorkerPrivate* worker = workers::GetCurrentThreadWorkerPrivate();
      MOZ_ASSERT(worker);
      MOZ_ASSERT(worker->GetJSContext() == cx());
      // Before invoking ReportError, put the exception back on the context,
      // because it may want to put it in its error events and has no other way
      // to get hold of it.  After we invoke ReportError, clear the exception on
      // cx(), just in case ReportError didn't.
      JS_SetPendingException(cx(), exn);
      worker->ReportError(cx(), jsReport.toStringResult(), jsReport.report());
      ClearException();
    }
  } else {
    NS_WARNING("OOMed while acquiring uncaught exception from JSAPI");
    ClearException();
  }
}
Пример #24
0
    // Returns false when request includes 'end'
    void assembleResponse( Message &m, DbResponse &dbresponse, const HostAndPort& remote ) {

        // before we lock...
        int op = m.operation();
        bool isCommand = false;
        const char *ns = m.singleData()->_data + 4;
        if ( op == dbQuery ) {
            if( strstr(ns, ".$cmd") ) {
                isCommand = true;
                opwrite(m);
                if( strstr(ns, ".$cmd.sys.") ) {
                    if( strstr(ns, "$cmd.sys.inprog") ) {
                        inProgCmd(m, dbresponse);
                        return;
                    }
                    if( strstr(ns, "$cmd.sys.killop") ) {
                        killOp(m, dbresponse);
                        return;
                    }
                    if( strstr(ns, "$cmd.sys.unlock") ) {
                        unlockFsync(ns, m, dbresponse);
                        return;
                    }
                }
            }
            else {
                opread(m);
            }
        }
        else if( op == dbGetMore ) {
            opread(m);
        }
        else {
            opwrite(m);
        }

        globalOpCounters.gotOp( op , isCommand );

        Client& c = cc();

        auto_ptr<CurOp> nestedOp;
        CurOp* currentOpP = c.curop();
        if ( currentOpP->active() ) {
            nestedOp.reset( new CurOp( &c , currentOpP ) );
            currentOpP = nestedOp.get();
        }
        CurOp& currentOp = *currentOpP;
        currentOp.reset(remote,op);

        OpDebug& debug = currentOp.debug();
        debug.op = op;

        int logThreshold = cmdLine.slowMS;
        bool log = logLevel >= 1;

        if ( op == dbQuery ) {
            if ( handlePossibleShardedMessage( m , &dbresponse ) )
                return;
            receivedQuery(c , dbresponse, m );
        }
        else if ( op == dbGetMore ) {
            if ( ! receivedGetMore(dbresponse, m, currentOp) )
                log = true;
        }
        else if ( op == dbMsg ) {
            // deprecated - replaced by commands
            char *p = m.singleData()->_data;
            int len = strlen(p);
            if ( len > 400 )
                out() << curTimeMillis64() % 10000 <<
                      " long msg received, len:" << len << endl;

            Message *resp = new Message();
            if ( strcmp( "end" , p ) == 0 )
                resp->setData( opReply , "dbMsg end no longer supported" );
            else
                resp->setData( opReply , "i am fine - dbMsg deprecated");

            dbresponse.response = resp;
            dbresponse.responseTo = m.header()->id;
        }
        else {
            const char *ns = m.singleData()->_data + 4;
            char cl[256];
            nsToDatabase(ns, cl);
            if( ! c.getAuthenticationInfo()->isAuthorized(cl) ) {
                uassert_nothrow("unauthorized");
            }
            else {
                try {
                    if ( op == dbInsert ) {
                        receivedInsert(m, currentOp);
                    }
                    else if ( op == dbUpdate ) {
                        receivedUpdate(m, currentOp);
                    }
                    else if ( op == dbDelete ) {
                        receivedDelete(m, currentOp);
                    }
                    else if ( op == dbKillCursors ) {
                        currentOp.ensureStarted();
                        logThreshold = 10;
                        receivedKillCursors(m);
                    }
                    else {
                        mongo::log() << "    operation isn't supported: " << op << endl;
                        currentOp.done();
                        log = true;
                    }
                }
                catch ( UserException& ue ) {
                    tlog(3) << " Caught Assertion in " << opToString(op) << ", continuing " << ue.toString() << endl;
                    debug.exceptionInfo = ue.getInfo();
                }
                catch ( AssertionException& e ) {
                    tlog(3) << " Caught Assertion in " << opToString(op) << ", continuing " << e.toString() << endl;
                    debug.exceptionInfo = e.getInfo();
                    log = true;
                }
            }
        }
        currentOp.ensureStarted();
        currentOp.done();
        debug.executionTime = currentOp.totalTimeMillis();

        //DEV log = true;
        if ( log || debug.executionTime > logThreshold ) {
            if( logLevel < 3 && op == dbGetMore && strstr(ns, ".oplog.") && debug.executionTime < 4300 && !log ) {
                /* it's normal for getMore on the oplog to be slow because of use of awaitdata flag. */
            }
            else {
                mongo::tlog() << debug << endl;
            }
        }

        if ( currentOp.shouldDBProfile( debug.executionTime ) ) {
            // performance profiling is on
            if ( dbMutex.getState() < 0 ) {
                mongo::log(1) << "note: not profiling because recursive read lock" << endl;
            }
            else {
                writelock lk;
                if ( dbHolder()._isLoaded( nsToDatabase( currentOp.getNS() ) , dbpath ) ) {
                    Client::Context cx( currentOp.getNS() );
                    profile(c , currentOp );
                }
                else {
                    mongo::log() << "note: not profiling because db went away - probably a close on: " << currentOp.getNS() << endl;
                }
            }
        }
        
        debug.reset();
    } /* assembleResponse() */
//---------------------------------------------------------
void NDG2D::OutputNodes_cub()
//---------------------------------------------------------
{
  static int count = 0;
  string output_dir = ".";

  string buf = umOFORM("%s/cub_N%02d_%04d.vtk", 
                      output_dir.c_str(), m_cub.Ncub, ++count);

  FILE *fp = fopen(buf.c_str(), "w");
  if (!fp) {
    umLOG(1, "Could no open %s for output!\n", buf.c_str());
    return;
  }

  // Set flags and totals
 
  int Npoints = m_cub.Ncub;  // cubature nodes per element

  // set totals for Vtk output
#if (1)
  // FIXME: no connectivity
  int vtkTotalPoints = this->K * Npoints;
  int vtkTotalCells  = vtkTotalPoints;
  int vtkTotalConns  = vtkTotalPoints;
  int Ncells = Npoints;
#else
  int vtkTotalPoints = this->K * Npoints;
  int vtkTotalCells  = this->K * Ncells;
  int vtkTotalConns  = (this->EToV.num_cols()+1) * this->K * Ncells;
  int Ncells = this->N * this->N;
#endif

  //-------------------------------------
  // 1. Write the VTK header details
  //-------------------------------------
  fprintf(fp, "# vtk DataFile Version 2");
  fprintf(fp, "\nNDGFem simulation nodes (high-order cubature)");
  fprintf(fp, "\nASCII");
  fprintf(fp, "\nDATASET UNSTRUCTURED_GRID\n");
  fprintf(fp, "\nPOINTS %d double", vtkTotalPoints);

  int newNpts=0;

  //-------------------------------------
  // 2. Write the vertex data
  //-------------------------------------
  const DMat& cx=m_cub.x;
  const DMat& cy=m_cub.y;
  for (int k=1; k<=this->K; ++k) {
    for (int n=1; n<=Npoints; ++n) {
      fprintf(fp, "\n%20.12e %20.12e %6.1lf", cx(n,k), cy(n,k), 0.0);
    }
  }

  //-------------------------------------
  // 3. Write the element connectivity
  //-------------------------------------

  // Number of indices required to define connectivity
  fprintf(fp, "\n\nCELLS %d %d", vtkTotalCells, 2*vtkTotalConns);


  // TODO: write element connectivity to file
  // FIXME: out-putting as VTK_VERTEX
  int nodesk=0;
  for (int k=0; k<this->K; ++k) {       // for each element
    for (int n=1; n<=Npoints; ++n) {
      fprintf(fp, "\n%d", 1);           // for each triangle
      for (int i=1; i<=1; ++i) {        // FIXME: no connectivity
        fprintf(fp, " %5d", nodesk);    // nodes in nth triangle
        nodesk++;                       // indexed from 0
      }
    }
  }


  //-------------------------------------
  // 4. Write the cell types
  //-------------------------------------

  // For each element (cell) write a single integer 
  // identifying the cell type.  The integer should 
  // correspond to the enumeration in the vtk file:
  // /VTK/Filtering/vtkCellType.h

  fprintf(fp, "\n\nCELL_TYPES %d", vtkTotalCells);

  for (int k=0; k<this->K; ++k) {
    fprintf(fp, "\n");
    for (int i=1; i<=Ncells; ++i) {
    //fprintf(fp, "5 ");            // 5:VTK_TRIANGLE
      fprintf(fp, "1 ");            // 1:VTK_VERTEX
      if (! (i%10))
        fprintf(fp, "\n");
    }
  }
  
  // add final newline to output
  fprintf(fp, "\n");
  fclose(fp);
}
Пример #26
0
    long long runCount( const char *ns, const BSONObj &cmd, string &err, int &errCode ) {
        // Lock 'ns'.
        Client::Context cx(ns);

        NamespaceDetails *d = nsdetails(ns);
        if (NULL == d) {
            err = "ns missing";
            return -1;
        }

        BSONObj query = cmd.getObjectField("query");
        long long count = 0;
        long long skip = cmd["skip"].numberLong();
        long long limit = cmd["limit"].numberLong();

        if (limit < 0) {
            limit = -limit;
        }
        
        // count of all objects
        if (query.isEmpty()) {
            return applySkipLimit(d->numRecords(), cmd);
        }

        CanonicalQuery* cq;
        // We pass -limit because a positive limit means 'batch size' but negative limit is a
        // hard limit.
        if (!CanonicalQuery::canonicalize(ns, query, skip, -limit, &cq).isOK()) {
            uasserted(17220, "could not canonicalize query " + query.toString());
            return -2;
        }

        Runner* rawRunner;
        if (!getRunner(cq, &rawRunner).isOK()) {
            uasserted(17221, "could not get runner " + query.toString());
            return -2;
        }

        auto_ptr<Runner> runner(rawRunner);

        try {
            const ScopedRunnerRegistration safety(runner.get());
            runner->setYieldPolicy(Runner::YIELD_AUTO);

            Runner::RunnerState state;
            while (Runner::RUNNER_ADVANCED == (state = runner->getNext(NULL, NULL))) {
                ++count;
            }

            // Emulate old behavior and return the count even if the runner was killed.  This
            // happens when the underlying collection is dropped.
            return count;
        }
        catch (const DBException &e) {
            err = e.toString();
            errCode = e.getCode();
        } 
        catch (const std::exception &e) {
            err = e.what();
            errCode = 0;
        } 

        // Historically we have returned zero in many count assertion cases - see SERVER-2291.
        log() << "Count with ns: " << ns << " and query: " << query
              << " failed with exception: " << err << " code: " << errCode
              << endl;

        return -2;
    }
Пример #27
0
 GCReference* GCReference::Globalize() {
   GCReference *r = new PersistentGCReference(this);
   r->root(cx());
   return r;
 }