Example #1
0
void PageRuntimeAgent::reportExecutionContextCreation()
{
    Vector<std::pair<JSC::ExecState*, SecurityOrigin*>> isolatedContexts;
    for (Frame* frame = &m_inspectedPage->mainFrame(); frame; frame = frame->tree().traverseNext()) {
        if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
            continue;
        String frameId = m_pageAgent->frameId(frame);

        JSC::ExecState* scriptState = mainWorldExecState(frame);
        notifyContextCreated(frameId, scriptState, 0, true);
        frame->script().collectIsolatedContexts(isolatedContexts);
        if (isolatedContexts.isEmpty())
            continue;
        for (size_t i = 0; i< isolatedContexts.size(); i++)
            notifyContextCreated(frameId, isolatedContexts[i].first, isolatedContexts[i].second, false);
        isolatedContexts.clear();
    }
}
Example #2
0
String ImageBuffer::toDataURL(const String& mimeType, const double* quality) const
{
    if (m_size.isEmpty())
        return "data:,";

    enum {
        EncodeJPEG,
        EncodePNG,
    } encodeType = mimeType.lower() == "image/png" ? EncodePNG : EncodeJPEG;

    // According to http://www.w3.org/TR/html5/the-canvas-element.html,
    // "For image types that do not support an alpha channel, the image must be"
    // "composited onto a solid black background using the source-over operator,"
    // "and the resulting image must be the one used to create the data: URL."
    // JPEG doesn't have alpha channel, so we need premultiplied data.
    RefPtr<ImageData> imageData = encodeType == EncodePNG
        ? getUnmultipliedImageData(IntRect(IntPoint(0, 0), m_size))
        : getPremultipliedImageData(IntRect(IntPoint(0, 0), m_size));

    ASSERT(imageData && imageData->width() == m_size.width() && imageData->height() == m_size.height());

    Vector<char> output;
    const char* header;
    if (encodeType == EncodePNG) {
        if (!compressRGBABigEndianToPNG(imageData->data()->data()->data(), m_size, output))
            return "data:,";
        header = "data:image/png;base64,";
    } else {
        if (!compressRGBABigEndianToJPEG(imageData->data()->data()->data(), m_size, output))
            return "data:,";
        header = "data:image/jpeg;base64,";
    }

    Vector<char> base64;
    base64Encode(output, base64);

    output.clear();

    Vector<char> url;
    url.append(header, strlen(header));
    url.append(base64);

    return String(url.data(), url.size());
}
Example #3
0
void WebEditorClient::checkGrammarOfString(StringView text, Vector<GrammarDetail>& details, int* badGrammarLocation, int* badGrammarLength)
{
    details.clear();
    *badGrammarLocation = -1;
    *badGrammarLength = 0;

    COMPtr<IWebEditingDelegate> ed;
    if (FAILED(m_webView->editingDelegate(&ed)) || !ed.get())
        return;

    initViewSpecificSpelling(m_webView);
    COMPtr<IEnumWebGrammarDetails> enumDetailsObj;
    if (FAILED(ed->checkGrammarOfString(m_webView, text.upconvertedCharacters(), text.length(), &enumDetailsObj, badGrammarLocation, badGrammarLength)))
        return;

    while (true) {
        ULONG fetched;
        COMPtr<IWebGrammarDetail> detailObj;
        if (enumDetailsObj->Next(1, &detailObj, &fetched) != S_OK)
            break;

        GrammarDetail detail;
        if (FAILED(detailObj->length(&detail.length)))
            continue;
        if (FAILED(detailObj->location(&detail.location)))
            continue;
        BString userDesc;
        if (FAILED(detailObj->userDescription(&userDesc)))
            continue;
        detail.userDescription = String(userDesc, SysStringLen(userDesc));

        COMPtr<IEnumSpellingGuesses> enumGuessesObj;
        if (FAILED(detailObj->guesses(&enumGuessesObj)))
            continue;
        while (true) {
            BString guess;
            if (enumGuessesObj->Next(1, &guess, &fetched) != S_OK)
                break;
            detail.guesses.append(String(guess, SysStringLen(guess)));
        }

        details.append(detail);
    }
}
Example #4
0
bool blInteriorProxy::preLight(LightInfo * light)
{
    // create shadow volume of the bounding box of this object
    InteriorInstance * interior = getObject();
    if(!interior)
        return(false);

    if(light->getType() != LightInfo::Vector)
        return(false);

    // reset
    mLitBoxSurfaces.clear();

    const Box3F & objBox = interior->getObjBox();
    const MatrixF & objTransform = interior->getTransform();
    const VectorF & objScale = interior->getScale();

    // grab the surfaces which form the shadow volume
    U32 numPlanes = 0;
    PlaneF testPlanes[3];
    U32 planeIndices[3];

    // grab the bounding planes which face the light
    U32 i;
    for(i = 0; (i < 6) && (numPlanes < 3); i++)
    {
        PlaneF plane;
        plane.x = BoxNormals[i].x;
        plane.y = BoxNormals[i].y;
        plane.z = BoxNormals[i].z;

        if(i&1)
            plane.d = (((const float*)objBox.minExtents)[(i-1)>>1]);
        else
            plane.d = -(((const float*)objBox.maxExtents)[i>>1]);

        // project
        mTransformPlane(objTransform, objScale, plane, &testPlanes[numPlanes]);

        planeIndices[numPlanes] = i;

        if(mDot(testPlanes[numPlanes], light->getDirection()) < gParellelVectorThresh)
            numPlanes++;
    }
Example #5
0
void LayerForceWidget::Init(SceneEditor2* scene, ParticleEmitter* emitter, ParticleLayer* layer, uint32 forceIndex, bool updateMinimized)
{
    if (!layer || layer->forces.size() <= forceIndex)
    {
        return;
    }

    this->emitter = emitter;
    this->layer = layer;
    this->forceIndex = forceIndex;
    SetActiveScene(scene);

    blockSignals = true;

    float32 emitterLifeTime = emitter->GetLifeTime();
    float32 lifeTime = Min(emitterLifeTime, layer->endTime);
    ParticleForce* curForce = layer->forces[forceIndex];

    Vector<QColor> colors;
    colors.push_back(Qt::red);
    colors.push_back(Qt::darkGreen);
    colors.push_back(Qt::blue);
    Vector<QString> legends;
    legends.push_back("force x");
    legends.push_back("force y");
    legends.push_back("force z");
    forceTimeLine->Init(layer->startTime, lifeTime, updateMinimized, true, false);
    forceTimeLine->AddLines(PropLineWrapper<Vector3>(PropertyLineHelper::GetValueLine(curForce->GetForce())).GetProps(), colors, legends);
    forceTimeLine->EnableLock(true);

    legends.clear();
    legends.push_back("force variable x");
    legends.push_back("force variable y");
    legends.push_back("force variable z");
    forceVariationTimeLine->Init(layer->startTime, lifeTime, updateMinimized, true, false);
    forceVariationTimeLine->AddLines(PropLineWrapper<Vector3>(PropertyLineHelper::GetValueLine(curForce->GetForceVariation())).GetProps(), colors, legends);
    forceVariationTimeLine->EnableLock(true);

    forceOverLifeTimeLine->Init(0, 1, updateMinimized, true, false);
    forceOverLifeTimeLine->AddLine(0, PropLineWrapper<float32>(PropertyLineHelper::GetValueLine(curForce->GetForceOverlife())).GetProps(), Qt::blue, "forces over life");

    blockSignals = false;
}
Example #6
0
void CFStencil::buildPeriodicVector(Vector<Box>& a_periodicVector,
                                    const ProblemDomain& a_fineDomain,
                                    const DisjointBoxLayout& a_fineBoxes)
{
  Box periodicTestBox(a_fineDomain.domainBox());
  if (a_fineDomain.isPeriodic())
    {
      for (int idir=0; idir<SpaceDim; idir++)
        {
          if (a_fineDomain.isPeriodic(idir))
            {
              periodicTestBox.grow(idir,-1);
            }
        }
    }
  a_periodicVector.clear();
  a_periodicVector.reserve(a_fineBoxes.size());

  LayoutIterator lit = a_fineBoxes.layoutIterator();
  for (lit.reset(); lit.ok(); ++lit)
    {
      const Box& box = a_fineBoxes[lit()];
      a_periodicVector.push_back(box);
      // if periodic, also need to add periodic images
      // only do this IF we're periodic and box
      // adjacent to  the domain box boundary somewhere
      if (a_fineDomain.isPeriodic()
          && !periodicTestBox.contains(box))
        {
          ShiftIterator shiftIt = a_fineDomain.shiftIterator();
          IntVect shiftMult(a_fineDomain.domainBox().size());
          Box shiftedBox(box);
          for (shiftIt.begin(); shiftIt.ok(); ++shiftIt)
            {
              IntVect shiftVect = shiftMult*shiftIt();
              shiftedBox.shift(shiftVect);
              a_periodicVector.push_back(shiftedBox);
              shiftedBox.shift(-shiftVect);
            } // end loop over periodic shift directions
        } // end if periodic
    }
  a_periodicVector.sort();
}
Example #7
0
bool SQLiteStatement::returnDoubleResults(int col, Vector<double>& v)
{
    v.clear();

    if (m_statement)
        finalize();
    if (prepare() != SQLITE_OK)
        return false;

    while (step() == SQLITE_ROW)
        v.append(getColumnDouble(col));
    bool result = true;
    if (m_database.lastError() != SQLITE_DONE) {
        result = false;
        LOG(SQLDatabase, "Error reading results from database query %s", m_query.ascii().data());
    }
    finalize();
    return result;
}
Example #8
0
Animate * GamePlay::CreateAnimationFromPlist(cocos2d::SpriteFrameCache * spritesCache, std::string spriteShortName, int nAnimFrames)
{
	if (spritesCache == nullptr)
		return nullptr;
	Vector<SpriteFrame*> animFrames;
	animFrames.clear();
	animFrames.reserve(nAnimFrames);
	for (auto i = 1; i < nAnimFrames + 1; i++)
	{
		char spriteNamechr[64];
		sprintf(spriteNamechr, "%s_%02d.png", spriteShortName.c_str(), i);
		SpriteFrame * frame = spritesCache->getSpriteFrameByName(std::string(spriteNamechr));
		if (frame)
			animFrames.pushBack(frame);
	}

	Animation * animation = Animation::createWithSpriteFrames(animFrames, 0.1f);
	return Animate::create(animation);
}
void ResourceLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
{
    OwnPtr<WebKit::WebURLLoader> loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
    ASSERT(loader);

    WebKit::WrappedResourceRequest requestIn(request);
    requestIn.setAllowStoredCredentials(storedCredentials == AllowStoredCredentials);
    WebKit::WrappedResourceResponse responseOut(response);
    WebKit::WebURLError errorOut;
    WebKit::WebData dataOut;

    loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut);

    error = errorOut;
    data.clear();
    RefPtr<SharedBuffer> buffer = dataOut;
    if (buffer)
        buffer->moveTo(data);
}
Example #10
0
void WebProcess::didClose(CoreIPC::Connection*)
{
#ifndef NDEBUG
    m_inDidClose = true;

    // Close all the live pages.
    Vector<RefPtr<WebPage>> pages;
    copyValuesToVector(m_pageMap, pages);
    for (size_t i = 0; i < pages.size(); ++i)
        pages[i]->close();
    pages.clear();

    gcController().garbageCollectSoon();
    memoryCache()->setDisabled(true);
#endif    

    // The UI process closed this connection, shut down.
    RunLoop::main()->stop();
}
static void parseKeySplines(const String& parse, Vector<UnitBezier>& result)
{
    result.clear();
    if (parse.isEmpty())
        return;
    const UChar* cur = parse.characters();
    const UChar* end = cur + parse.length();

    skipOptionalSVGSpaces(cur, end);

    bool delimParsed = false;
    while (cur < end) {
        delimParsed = false;
        float posA = 0;
        if (!parseNumber(cur, end, posA)) {
            result.clear();
            return;
        }

        float posB = 0;
        if (!parseNumber(cur, end, posB)) {
            result.clear();
            return;
        }

        float posC = 0;
        if (!parseNumber(cur, end, posC)) {
            result.clear();
            return;
        }

        float posD = 0;
        if (!parseNumber(cur, end, posD, false)) {
            result.clear();
            return;
        }

        skipOptionalSVGSpaces(cur, end);

        if (cur < end && *cur == ';') {
            delimParsed = true;
            cur++;
        }
        skipOptionalSVGSpaces(cur, end);

        result.append(UnitBezier(posA, posB, posC, posD));
    }
    if (!(cur == end && !delimParsed))
        result.clear();
}
Example #12
0
void OmxDecoder::ReleaseAllPendingVideoBuffersLocked()
{
  Vector<BufferItem> releasingVideoBuffers;
  {
    Mutex::Autolock autoLock(mPendingVideoBuffersLock);

    int size = mPendingVideoBuffers.size();
    for (int i = 0; i < size; i++) {
      releasingVideoBuffers.push(mPendingVideoBuffers[i]);
    }
    mPendingVideoBuffers.clear();
  }
  // Free all pending video buffers without holding mPendingVideoBuffersLock.
  int size = releasingVideoBuffers.size();
  for (int i = 0; i < size; i++) {
    MediaBuffer *buffer;
    buffer = releasingVideoBuffers[i].mMediaBuffer;
#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
    android::sp<Fence> fence;
    int fenceFd = -1;
    fence = releasingVideoBuffers[i].mReleaseFenceHandle.mFence;
    if (fence.get() && fence->isValid()) {
      fenceFd = fence->dup();
    }
    MOZ_ASSERT(buffer->refcount() == 1);
    // This code expect MediaBuffer's ref count is 1.
    // Return gralloc buffer to ANativeWindow
    ANativeWindow* window = static_cast<ANativeWindow*>(mNativeWindowClient.get());
    window->cancelBuffer(window,
                         buffer->graphicBuffer().get(),
                         fenceFd);
    // Mark MediaBuffer as rendered.
    // When gralloc buffer is directly returned to ANativeWindow,
    // this mark is necesary.
    sp<MetaData> metaData = buffer->meta_data();
    metaData->setInt32(kKeyRendered, 1);
#endif
    // Return MediaBuffer to OMXCodec.
    buffer->release();
  }
  releasingVideoBuffers.clear();
}
bool SharedBufferChunkReader::nextChunk(Vector<char>& chunk,
                                        bool includeSeparator) {
    if (m_reachedEndOfFile)
        return false;

    chunk.clear();
    while (true) {
        while (m_segmentIndex < m_segmentLength) {
            char currentCharacter = m_segment[m_segmentIndex++];
            if (currentCharacter != m_separator[m_separatorIndex]) {
                if (m_separatorIndex > 0) {
                    ASSERT_WITH_SECURITY_IMPLICATION(m_separatorIndex <=
                                                     m_separator.size());
                    chunk.append(m_separator.data(), m_separatorIndex);
                    m_separatorIndex = 0;
                }
                chunk.append(currentCharacter);
                continue;
            }
            m_separatorIndex++;
            if (m_separatorIndex == m_separator.size()) {
                if (includeSeparator)
                    chunk.appendVector(m_separator);
                m_separatorIndex = 0;
                return true;
            }
        }

        // Read the next segment.
        m_segmentIndex = 0;
        m_bufferPosition += m_segmentLength;
        m_segmentLength = m_buffer->getSomeData(m_segment, m_bufferPosition);
        if (!m_segmentLength) {
            m_reachedEndOfFile = true;
            if (m_separatorIndex > 0)
                chunk.append(m_separator.data(), m_separatorIndex);
            return !chunk.isEmpty();
        }
    }
    ASSERT_NOT_REACHED();
    return false;
}
Example #14
0
void FEMorphology::platformApplyGeneric(PaintingData* paintingData, int yStart, int yEnd)
{
    Uint8ClampedArray* srcPixelArray = paintingData->srcPixelArray;
    Uint8ClampedArray* dstPixelArray = paintingData->dstPixelArray;
    const int radiusX = paintingData->radiusX;
    const int radiusY = paintingData->radiusY;
    const int width = paintingData->width;
    const int height = paintingData->height;

    ASSERT(radiusX <= width || radiusY <= height);
    ASSERT(yStart >= 0 && yEnd <= height && yStart < yEnd);

    Vector<unsigned char> extrema;
    for (int y = yStart; y < yEnd; ++y) {
        int yStartExtrema = std::max(0, y - radiusY);
        int yEndExtrema = std::min(height - 1, y + radiusY);

        for (unsigned colorChannel = 0; colorChannel < 4; ++colorChannel) {
            extrema.clear();
            // Compute extremas for each columns
            for (int x = 0; x < radiusX; ++x)
                extrema.append(columnExtremum(srcPixelArray, x, yStartExtrema, yEndExtrema, width, colorChannel, m_type));

            // Kernel is filled, get extrema of next column
            for (int x = 0; x < width; ++x) {
                if (x < width - radiusX) {
                    int xEnd = std::min(x + radiusX, width - 1);
                    extrema.append(columnExtremum(srcPixelArray, xEnd, yStartExtrema, yEndExtrema + 1, width, colorChannel, m_type));
                }

                if (x > radiusX)
                    extrema.remove(0);

                // The extrema original size = radiusX.
                // Number of new addition = width - radiusX.
                // Number of removals = width - radiusX - 1.
                ASSERT(extrema.size() >= static_cast<size_t>(radiusX + 1));
                dstPixelArray->set(pixelArrayIndex(x, y, width, colorChannel), kernelExtremum(extrema, m_type));
            }
        }
    }
}
Example #15
0
	void ClearThreads()
	{
		for(JobThread* t : m_threadPool)
		{
			t->Terminate();
			delete t;
		}
		m_lock.lock();
		// Unregister jobs
		for(auto job : m_jobQueue)
		{
			job->m_sheduler = nullptr;
		}
		for(auto job : m_finishedJobs)
		{
			job->m_sheduler = nullptr;
		}
		m_threadPool.clear();
		m_lock.unlock();
	}
Example #16
0
void ContentState::getOpenElementInfo(Vector<OpenElementInfo> &v,
				      const StringC &rniPcdata) const
{
  v.clear();
  v.resize(tagLevel_);
  unsigned i = tagLevel_;
  for (IListIter<OpenElement> iter(openElements_);
       !iter.done() && i > 0;
       iter.next()) {
    OpenElementInfo &e = v[--i];
    e.gi = iter.cur()->type()->name();
    const LeafContentToken *token = iter.cur()->currentPosition();
    if (token && !token->isInitial()) {
      e.matchIndex = token->typeIndex() + 1;
      const ElementType *type = token->elementType();
      e.matchType = type ? type->name() : rniPcdata;
    }
    e.included = iter.cur()->included();
  }
}
Example #17
0
int runGetTableList(NDBT_Context* ctx, NDBT_Step* step)
{
    table_list.clear();
    ndbout << "Looking for tables ... ";
    for (int i = 0; i<NDBT_Tables::getNumTables(); i++)
    {
        const NdbDictionary::Table* tab =
            GETNDB(step)->getDictionary()
            ->getTable(NDBT_Tables::getTable(i)
                       ->getName());
        if (tab != NULL)
        {
            ndbout << tab->getName() << " ";
            table_list.push_back(BaseString(tab->getName()));
        }
    }
    ndbout << endl;

    return NDBT_OK;
}
Example #18
0
    const T& GravityIterator<T>::Iterate(void)
    {
        Vector acceleration;
        acceleration.clear();
        for (typename VectorList::const_iterator i = m_masses.begin(); i != m_masses.end(); ++i) {
            const Vector displacement = (*i) - m_position;
            const double distance = norm_2(displacement);
            const Vector displacement_unit_vec = displacement / distance;
            const Vector force = displacement_unit_vec / (distance * distance);
            acceleration += force;
        }
	const double time_step = m_acc_step / norm_2(acceleration);
        m_velocity *= pow(1.0 - m_damping, time_step);
	m_velocity += acceleration * time_step;
        m_position += m_velocity * time_step;
	if (m_accumulator00) {
	    m_accumulator00->Accumulate( Fractal::Geometry::Vector2ToVector4(Value()), time_step );
	}
        return Value();
    }
Example #19
0
void WebEditorClient::getGuessesForWord(const String& word, const String& context, const VisibleSelection&, Vector<String>& guesses)
{
    guesses.clear();

    COMPtr<IWebEditingDelegate> ed;
    if (FAILED(m_webView->editingDelegate(&ed)) || !ed.get())
        return;

    COMPtr<IEnumSpellingGuesses> enumGuessesObj;
    if (FAILED(ed->guessesForWord(BString(word), &enumGuessesObj)))
        return;

    while (true) {
        ULONG fetched;
        BString guess;
        if (enumGuessesObj->Next(1, &guess, &fetched) != S_OK)
            break;
        guesses.append(String(guess, SysStringLen(guess)));
    }
}
Example #20
0
void Vector<V>::swap(Vector v2)
{
	//swaps the values
	V temp[50];
	int tempSize = v2.size();
	for (int i = 0; i < v2.size(); i++) {
		temp[i] = v2.at(i);
	}

	//clears the content in v2
	v2.clear();
	for (int i = 0; i < size(); i++) {
		v2.push_back(at(i));
	}
	//the clear() is used to set the vector size back to 0,
	clear();
	for (int i = 0; i < tempSize; i++) {
		push_back(temp[i]);
	}
}
Example #21
0
int main() {
    while(true){
        string nameFile  = getLine("Enter the file name: ");
        ifstream file(nameFile);
        if(file.fail()){
            cout << "You entered not valid file name. Try again." << endl;
        }else{
            int rank = getInteger ("Enter Makarov index: ");
            parseText(file, rank);
            string popularSeed = counterSeed();
            createRandomText(popularSeed);

            /*Clear all containers */
            mapTextChars.clear ();
            allSeeds.clear ();
            file.close ();
        }
    }
    return 0;
}
void PublicURLManager::revoke(const String& uuid)
{
    // A linear scan; revoking by UUID is assumed rare.
    Vector<String> urlsToRemove;
    for (auto& registryUrl : m_registryToURL) {
        URLRegistry* registry = registryUrl.key;
        URLMap& registeredURLs = registryUrl.value;
        for (auto& registeredUrl : registeredURLs) {
            if (uuid == registeredUrl.value) {
                KURL url(ParsedURLString, registeredUrl.key);
                executionContext()->removeURLFromMemoryCache(url);
                registry->unregisterURL(url);
                urlsToRemove.append(registeredUrl.key);
            }
        }
        for (unsigned j = 0; j < urlsToRemove.size(); j++)
            registeredURLs.remove(urlsToRemove[j]);
        urlsToRemove.clear();
    }
}
void SearchPopupMenuWin::loadRecentSearches(const AtomicString& name, Vector<String>& searchItems)
{
    if (name.isEmpty())
        return;

#if USE(CF)
    searchItems.clear();
    RetainPtr<CFArrayRef> items(AdoptCF, reinterpret_cast<CFArrayRef>(CFPreferencesCopyAppValue(autosaveKey(name).get(), kCFPreferencesCurrentApplication)));

    if (!items || CFGetTypeID(items.get()) != CFArrayGetTypeID())
        return;

    size_t size = CFArrayGetCount(items.get());
    for (size_t i = 0; i < size; ++i) {
        CFStringRef item = (CFStringRef)CFArrayGetValueAtIndex(items.get(), i);
        if (CFGetTypeID(item) == CFStringGetTypeID())
            searchItems.append(item);
    }
#endif
}
Example #24
0
bool LevelDBDatabase::safeGet(const LevelDBSlice& key, Vector<char>& value, bool& found, const LevelDBSnapshot* snapshot)
{
    found = false;
    std::string result;
    leveldb::ReadOptions readOptions;
    readOptions.verify_checksums = true; // FIXME: Disable this if the performance impact is too great.
    readOptions.snapshot = snapshot ? snapshot->m_snapshot : 0;

    const leveldb::Status s = m_db->Get(readOptions, makeSlice(key), &result);
    if (s.ok()) {
        found = true;
        value.clear();
        value.append(result.c_str(), result.length());
        return true;
    }
    if (s.IsNotFound())
        return true;
    LOG_ERROR("LevelDB get failed: %s", s.ToString().c_str());
    return false;
}
Example #25
0
bool Elasticity::evalSol2 (Vector& s, const Vectors& eV,
                           const FiniteElement& fe, const Vec3& X) const
{
  Vec3* pBuf = nullptr;
  if (pDirBuf)
  {
    // Store principal stress directions in the internal buffer
    size_t ifirst = pDirBuf->size();
    pDirBuf->resize(ifirst+2);
    pBuf = pDirBuf->data() + ifirst;
  }

  // Evaluate the stress tensor
  if (fe.detJxW == 0.0)
  {
    // Singular point, just return an empty vector for now
    s.clear();
    return true;
  }
  else if (!this->evalSol(s,eV,fe,X,true,pBuf))
    return false;
#if SP_DEBUG > 2
  else if (pBuf)
    std::cout <<"Elasticity::evalSol2("<< X <<"): "
	      <<" Pdir1 = "<< pBuf[0] <<", Pdir2 = "<< pBuf[1] << std::endl;
#endif

  // Additional result variables?
  for (int i = 1; i <= material->getNoIntVariables(); i++)
    s.push_back(material->getInternalVariable(i,nullptr,fe.iGP));

  // Find the maximum values for each quantity. This block must be performed
  // serially on multi-threaded runs too, due to the update of the maxVal array
  // which is a member of the Elasticity class. Therefore the critical pragma.
#pragma omp critical
  for (size_t j = 0; j < s.size() && j < maxVal.size(); j++)
    if (fabs(s[j]) > fabs(maxVal[j].second))
      maxVal[j] = std::make_pair(X,s[j]);

  return true;
}
Example #26
0
bool Player::init() {

	_player = Sprite::create("res/image/anim1/stay1.png");
	_player->setAnchorPoint(Vec2(0.5, 0));

	Vector<SpriteFrame*> frameVector;
	for (int i = 1; i <= 5; i++) {

		char pngName[260] = { 0 };
		sprintf(pngName, "res/image/anim1/stay%d.png", i);
		frameVector.pushBack(SpriteFrame::create(pngName, Rect(0, 0, 54, 58)));

	}
	StayAnimation = Animation::createWithSpriteFrames(frameVector, 0.1);
	StayAnimation->setRestoreOriginalFrame(false);
	StayAnimation->setLoops(10000);
	StayAnimate = Animate::create(StayAnimation);

	StayAnimate->retain();

	//2
	frameVector.clear();
	for (int i = 1; i <= 5; i++) {

		char pngName[260] = { 0 };
		sprintf(pngName, "res/image/anim1/walk%d.png", i);
		frameVector.pushBack(SpriteFrame::create(pngName, Rect(0, 0, 54, 58)));
	}
	WalkAnimation = Animation::createWithSpriteFrames(frameVector, 1);
	WalkAnimation->setRestoreOriginalFrame(false);
	WalkAnimation->setLoops(10000);
	WalkAnimate = Animate::create(WalkAnimation);


	/**
	 * 在析构函数中进行释放,否则会被自动释放;导致空指针
	 */
	WalkAnimate->retain();

	return true;
}
Example #27
0
	void output(const string& file="../data/track1/final/rec_log_test.txt.sorted"){
		LOG()<<__FUNCTION__<<" begins"<<endl;
        int cnt=0;
		ifstream fin;	fin.open(file.c_str());
        int s,t,ok,last;
        Vector tmp; 
		while(fin>>s>>t>>ok>>t){
			if(s!=last){
                vector<int> rec=findMaxIndex(tmp,3);
                printf("%d,",last);
                for(int i=0;i<rec.size();i++){
                    printf("%d ",rec[i]);
                }
                printf("\n");
                tmp.clear();
            }
            tmp[t]=users[last].scores[t];
            logRecordLoaded(cnt);
        }
		LOG()<<__FUNCTION__<<" ends"<<endl;
    }
bool SVGAltGlyphItemElement::hasValidGlyphElements(Vector<AtomicString>& glyphNames) const
{
    // Spec: http://www.w3.org/TR/SVG/text.html#AltGlyphItemElement
    // The ‘altGlyphItem’ element defines a candidate set of possible glyph substitutions.
    // The first ‘altGlyphItem’ element whose referenced glyphs are all available is chosen.
    // Its glyphs are rendered instead of the character(s) that are inside of the referencing
    // ‘altGlyph’ element.
    //
    // Here we fill glyphNames and return true only if all referenced glyphs are valid and
    // there is at least one glyph.
    for (SVGGlyphRefElement* glyph = Traversal<SVGGlyphRefElement>::firstChild(*this); glyph; glyph = Traversal<SVGGlyphRefElement>::nextSibling(*glyph)) {
        AtomicString referredGlyphName;
        if (glyph->hasValidGlyphElement(referredGlyphName)) {
            glyphNames.append(referredGlyphName);
        } else {
            glyphNames.clear();
            return false;
        }
    }
    return !glyphNames.isEmpty();
}
void GonkVideoDecoderManager::ReleaseAllPendingVideoBuffers()
{
  Vector<android::MediaBuffer*> releasingVideoBuffers;
  {
    MutexAutoLock autoLock(mPendingVideoBuffersLock);
    int size = mPendingVideoBuffers.length();
    for (int i = 0; i < size; i++) {
      releasingVideoBuffers.append(mPendingVideoBuffers[i]);
    }
    mPendingVideoBuffers.clear();
  }
  // Free all pending video buffers without holding mPendingVideoBuffersLock.
  int size = releasingVideoBuffers.length();
  for (int i = 0; i < size; i++) {
    android::MediaBuffer *buffer;
    buffer = releasingVideoBuffers[i];
    mDecoder->ReleaseMediaBuffer(buffer);
    buffer = nullptr;
  }
  releasingVideoBuffers.clear();
}
Example #30
0
void PageRuntimeAgent::setReportExecutionContextCreation(ErrorString*, bool enable)
{
    m_state->setBoolean(PageRuntimeAgentState::reportExecutionContextCreation, enable);
    if (!enable)
        return;
    Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts;
    for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
        if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript))
            continue;
        String frameId = m_pageAgent->frameId(frame);

        ScriptState* scriptState = mainWorldScriptState(frame);
        notifyContextCreated(frameId, scriptState, 0, true);
        frame->script()->collectIsolatedContexts(isolatedContexts);
        if (isolatedContexts.isEmpty())
            continue;
        for (size_t i = 0; i< isolatedContexts.size(); i++)
            notifyContextCreated(frameId, isolatedContexts[i].first, isolatedContexts[i].second, false);
        isolatedContexts.clear();
    }
}