Beispiel #1
0
bool loadThemeFromBlob(const QString &themeBlob,
    QHash<QString, QPicture> &partPictures,
    QHash<QPair<QString, int>, QColor> &colors)
{
    QFile blob(themeBlob);
    if (!blob.open(QIODevice::ReadOnly)) {
        qWarning() << __FUNCTION__ << ": Could not read blob: " << themeBlob;
        return false;
    }
    QDataStream blobIn(&blob);

    quint32 version;
    blobIn >> version;

    if (version != blobVersion) {
        qWarning() << __FUNCTION__ << ": Invalid blob version: " << version << " ...expected: " << blobVersion;
        return false;
    }

    QByteArray data;
    blobIn >> data;
    data = qUncompress(data);
    QBuffer dataBuffer(&data);
    dataBuffer.open(QIODevice::ReadOnly);
    QDataStream dataIn(&dataBuffer);

    int colorsCount;
    dataIn >> colorsCount;
    for (int i = 0; i < colorsCount; ++i) {
        QPair<QString, int> key;
        dataIn >> key;
        QColor value;
        dataIn >> value;
        colors.insert(key, value);
    }

    int picturesCount;
    dataIn >> picturesCount;
    for (int i = 0; i < picturesCount; ++i) {
        QString key;
        dataIn >> key;
        QPicture value;
        dataIn >> value;
        value.setBoundingRect(QRect(0, 0, pictureSize, pictureSize)); // Bug? The forced bounding rect was not deserialized.
        partPictures.insert(key, value);
    }

    if (dataIn.status() != QDataStream::Ok) {
        qWarning() << __FUNCTION__ << ": Invalid data blob: " << themeBlob;
        return false;
    }
    return true;
}
Beispiel #2
0
bool vgg_process::process(cv::Mat image_in, string &name, float &conf)
{
    int i=0, j=0, k=0;
    int top5_idx[5];
    float mean_val[3] = {103.939, 116.779, 123.68}; // bgr mean

    // input
    float output[1000];
    vector<Blob<float>*> input_vec;
    Blob<float> blob(1, 3, IMAGE_SIZE, IMAGE_SIZE);

    cv::Mat image_small(cv::Size(IMAGE_SIZE, IMAGE_SIZE), CV_8UC3);

    cv::resize(image_in, image_small, cv::Size(IMAGE_SIZE, IMAGE_SIZE));

    for (k=0; k<3; k++)
        {
            for (i=0; i<IMAGE_SIZE; i++)
                {
                    for (j=0; j< IMAGE_SIZE; j++)
                        {
                            blob.mutable_cpu_data()[blob.offset(0, k, i, j)] = (float)(unsigned char)image_small.data[i*image_small.step+j*image_small.channels()+k] - mean_val[k];
                        }
                }
        }

    input_vec.push_back(&blob);

    // forward propagation
    float loss;

    const vector<Blob<float>*>& result = caffe_test_net.Forward(input_vec, &loss);

    // copy output
    for(i=0; i<1000; i++)
        {
            output[i] = result[0]->cpu_data()[i];
        }

    get_top5(output, top5_idx);

    char str[256];
    sprintf(str, "%s", label[top5_idx[0]]);
    name = str;

    conf = output[0];

    if (conf < 0.3)
        return false;
    else
        return true;
}
Beispiel #3
0
void stringtbl::deinit()
{
	if(fp)
	{
		for(ssize_t i = 0; i < ST_LRU; i++)
		{
			if(lru[i].string)
				free((void *) lru[i].string);
			if(lru[i].binary.exists())
				lru[i].binary = blob();
		}
		fp = NULL;
	}
}
Beispiel #4
0
EncodedJSValue JSC_HOST_CALL jsFileReaderPrototypeFunctionReadAsDataURL(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (!thisValue.inherits(&JSFileReader::s_info))
        return throwVMTypeError(exec);
    JSFileReader* castedThis = static_cast<JSFileReader*>(asObject(thisValue));
    FileReader* imp = static_cast<FileReader*>(castedThis->impl());
    Blob* blob(toBlob(exec->argument(0)));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());

    imp->readAsDataURL(blob);
    return JSValue::encode(jsUndefined());
}
Beispiel #5
0
blob variant::as_blob()const
{
   switch( get_type() )
   {
      case null_type: return blob();
      case blob_type: return get_blob();
      case string_type:
      {
         const string& str = get_string();
         if( str.size() == 0 ) return blob();
         if( str.back() == '=' )
         {
            std::string b64 = base64_decode( get_string() );
            return blob( { std::vector<char>( b64.begin(), b64.end() ) } );
         }
         return blob( { std::vector<char>( str.begin(), str.end() ) } );
      }
      case object_type:
      case array_type:
         FC_THROW_EXCEPTION( bad_cast_exception, "Invalid cast from ${type} to Blob", ("type",get_type()) );
      default:
         return blob( { std::vector<char>( (char*)&_data, (char*)&_data + sizeof(_data) ) } );
   }
}
Beispiel #6
0
int main(int argc,char **argv)
{
	Debug.SetLevel(TRACE);
	try
	{
		if(argc>1)
		{
			BinaryBlob blob(argv[1]);
		}
#if 0
		ConfigFile conf;
		ProfileManager pm(&conf,"[Colour Management]");
		pm.SetInt("DefaultCMYKProfileActive",1);

		CMSProfile *src=pm.GetProfile(CM_COLOURDEVICE_DEFAULTRGB);
		CMSProfile *dst=pm.GetProfile(CM_COLOURDEVICE_DEFAULTCMYK);

		if(src)
			Debug[TRACE] << "Using source profile: " << src->GetMD5()->GetPrintableDigest() << std::endl;
		if(dst)
			Debug[TRACE] << "Using dest profile: " << dst->GetMD5()->GetPrintableDigest() << std::endl;

		DeviceLinkList devicelinks;
		Debug[TRACE] << "Got devicelink list with " << devicelinks.size() << " entries" << std::endl;

		DeviceLinkList devicelinksfiltered(src,dst);
		Debug[TRACE] << "Got filtered devicelink list with " << devicelinksfiltered.size() << " entries" << std::endl;
		
		DeviceLink dltest;
		dltest.SetString("Description","Test devicelink");
		dltest.SetString("SourceProfile",pm.FindString("DefaultRGBProfile"));
		dltest.SetString("DestProfile",pm.FindString("DefaultCMYKProfile"));

		if(argc>1)
			dltest.CreateDeviceLink("/usr/local/bin/:/usr/bin",pm);

		if(src)
			delete src;
		if(dst)
			delete dst;
#endif
	}
	catch (const char *err)
	{
		Debug[ERROR] << "Error: " << err << std::endl;
	}
	return(0);
}
Beispiel #7
0
inline int get_data_blob::operator()(int req, size_t col, variant& var)
{
  T_CCI_BIT data;
  int ind(-1);
  const int r(lib::singleton().p_cci_get_data(req, int(col + 1), CCI_A_TYPE_BIT, &data, &ind));
  if (lib::error(r) || ind < 0)
    var = null_t();
  else
  {
    var = blob_t();
    blob_t& blob(::boost::get<blob_t>(var));
    blob.resize(data.size);
    if (!blob.empty()) memcpy(blob.data(), data.buf, data.size);
  }
  return r;
} // get_data_blob::
Beispiel #8
0
bool deltaint_dtable::iter::prev()
{
	blob value = base->valid() ? base->value() : blob();
	bool valid = base->prev();
	if(valid)
	{
		exists = base->meta().exists();
		if(value.exists())
		{
			assert(value.size() == sizeof(uint32_t));
			current -= value.index<uint32_t>(0);
		}
	}
	/* else don't change exists */
	return valid;
}
Beispiel #9
0
    static void RunBuilderTest(skiatest::Reporter* reporter, SkTextBlobBuilder& builder,
                               const RunDef in[], unsigned inCount,
                               const RunDef out[], unsigned outCount) {
        SkFont font;

        unsigned glyphCount = 0;
        unsigned posCount = 0;

        for (unsigned i = 0; i < inCount; ++i) {
            AddRun(font, in[i].count, in[i].pos, SkPoint::Make(in[i].x, in[i].y), builder);
            glyphCount += in[i].count;
            posCount += in[i].count * in[i].pos;
        }

        sk_sp<SkTextBlob> blob(builder.make());
        REPORTER_ASSERT(reporter, (inCount > 0) == SkToBool(blob));
        if (!blob) {
            return;
        }

        SkTextBlobRunIterator it(blob.get());
        for (unsigned i = 0; i < outCount; ++i) {
            REPORTER_ASSERT(reporter, !it.done());
            REPORTER_ASSERT(reporter, out[i].pos == it.positioning());
            REPORTER_ASSERT(reporter, out[i].count == it.glyphCount());
            if (SkTextBlobRunIterator::kDefault_Positioning == out[i].pos) {
                REPORTER_ASSERT(reporter, out[i].x == it.offset().x());
                REPORTER_ASSERT(reporter, out[i].y == it.offset().y());
            } else if (SkTextBlobRunIterator::kHorizontal_Positioning == out[i].pos) {
                REPORTER_ASSERT(reporter, out[i].y == it.offset().y());
            }

            for (unsigned k = 0; k < it.glyphCount(); ++k) {
                REPORTER_ASSERT(reporter, k % 128 == it.glyphs()[k]);
                if (SkTextBlobRunIterator::kHorizontal_Positioning == it.positioning()) {
                    REPORTER_ASSERT(reporter, SkIntToScalar(k % 128) == it.pos()[k]);
                } else if (SkTextBlobRunIterator::kFull_Positioning == it.positioning()) {
                    REPORTER_ASSERT(reporter, SkIntToScalar(k % 128) == it.pos()[k * 2]);
                    REPORTER_ASSERT(reporter, -SkIntToScalar(k % 128) == it.pos()[k * 2 + 1]);
                }
            }

            it.next();
        }

        REPORTER_ASSERT(reporter, it.done());
    }
blob index_blob::flatten() const
{
	if(!modified)
		return base;
	if(!resized)
	{
		blob_buffer buffer(base);
		size_t offset = count * sizeof(uint32_t);
		/* hopefully avoid copying by breaking sharing before modifying */
		base = blob();
		for(size_t i = 0; i < count; i++)
		{
			if(indices[i].modified)
			{
				assert(!indices[i].delayed);
				buffer.overwrite(offset, indices[i].value);
				indices[i].modified = false;
			}
			offset += indices[i].value.size();
		}
		modified = false;
		base = buffer;
	}
	else
	{
		size_t offset = count * sizeof(uint32_t);
		for(size_t i = 0; i < count; i++)
			offset += indices[i].value.size();
		blob_buffer buffer(offset);
		for(size_t i = 0; i < count; i++)
		{
			/* we use 0 for "does not exist" so other sizes are incremented by 1 */
			uint32_t size = indices[i].exists() ? indices[i].size() + 1 : 0;
			indices[i].modified = false;
			buffer << size;
		}
		offset = count * sizeof(uint32_t);
		for(size_t i = 0; i < count; i++)
			/* use get(i) rather than indices[i].value in case they are delayed */
			buffer.append(get(i));
		modified = false;
		resized = false;
		base = buffer;
	}
	return base;
}
Beispiel #11
0
mbus::Blob
DocumentProtocol::encode(const vespalib::Version &version, const mbus::Routable &routable) const
{
    mbus::Blob blob(_routableRepository->encode(version, routable));
        // When valgrind reports errors of uninitialized data being written to
        // the network, it is useful to be able to see the serialized data to
        // try to identify what bits are uninitialized.
    if (LOG_WOULD_LOG(spam)) {
        std::ostringstream message;
        document::StringUtil::printAsHex(
                message, blob.data(), blob.size());
        LOG(spam, "Encoded message of protocol %s type %u using version %s serialization:\n%s",
            routable.getProtocol().c_str(), routable.getType(),
            version.toString().c_str(), message.str().c_str());
    }
    return blob;
}
Beispiel #12
0
MIRANDA_HOOK_EVENT(ME_DB_EVENT_ADDED, wParam, lParam)
{
	UNREFERENCED_PARAMETER(wParam);
	MEVENT hDbEvent = (MEVENT)lParam;

	DBEVENTINFO dbei = { 0 };
	dbei.cbSize = sizeof(dbei);
	dbei.cbBlob = db_event_getBlobSize(hDbEvent);
	if (-1 == dbei.cbBlob)
		return 0;

	mir_ptr<BYTE> blob((LPBYTE)mir_alloc(dbei.cbBlob));
	dbei.pBlob = blob;
	db_event_get(hDbEvent, &dbei);

	// if event is in protocol that is not despammed
	if (plSets->ProtoDisabled(dbei.szModule))
		return 0;

	// event is an auth request
	if (!(dbei.flags & DBEF_SENT) && !(dbei.flags & DBEF_READ) && dbei.eventType == EVENTTYPE_AUTHREQUEST) {
		MCONTACT hcntct = DbGetAuthEventContact(&dbei);

		// if request is from unknown or not marked Answered contact
		//and if I don't sent message to this contact
		if (db_get_b(hcntct, "CList", "NotOnList", 0) && !db_get_b(hcntct, pluginName, answeredSetting, 0) && !IsExistMyMessage(hcntct)) {
			if (!plSets->HandleAuthReq.Get()) {
				char *buf = mir_utf8encodeW(variables_parse(plSets->AuthRepl.Get(), hcntct).c_str());
				CallContactService(hcntct, PSS_MESSAGE, 0, (LPARAM)buf);
				mir_free(buf);
			}

			// ...send message
			char *AuthRepl = mir_u2a(variables_parse(plSets->AuthRepl.Get(), hcntct).c_str());
			CallProtoService(dbei.szModule, PS_AUTHDENY, hDbEvent, (LPARAM)AuthRepl);
			mir_free(AuthRepl);

			db_set_b(hcntct, "CList", "NotOnList", 1);
			db_set_b(hcntct, "CList", "Hidden", 1);
			if (!plSets->HistLog.Get())
				db_event_delete(0, hDbEvent);
			return 1;
		}
	}
	return 0;
}
Beispiel #13
0
int ArrayWorker<T>::Partition(const std::vector<Blob>& kv,
  std::unordered_map<int, std::vector<Blob> >* out) {
  CHECK(kv.size() == 1 || kv.size() == 2 || kv.size() == 3);
  for (int i = 0; i < num_server_; ++i) (*out)[i].push_back(kv[0]);
  if (kv.size() >= 2) {
    CHECK(kv[1].size() == size_ * sizeof(T));
    for (int i = 0; i < num_server_; ++i) {
      Blob blob(kv[1].data() + server_offsets_[i] * sizeof(T),
        (server_offsets_[i + 1] - server_offsets_[i]) * sizeof(T));
      (*out)[i].push_back(blob);
      if (kv.size() == 3) {// update option blob
        (*out)[i].push_back(kv[2]);
      }
    }
  }
  return num_server_;
}
Blob MomentCalculation2::getMomentsInaBlob(Mat boxImage, Mat cmaskImage, string blobId,string profileId){


	cvtColor(boxImage, boxImage, CV_BGR2HSV);
	//Average
	HumanProportions prop;

	int boxHeight = boxImage.rows;
	double ratio = (double)boxHeight / (double)prop.height;
	int region1Height = (int)(((double)prop.head) * ratio);
	int region2Height = (int)(((double)prop.gait) * ratio);
	int region3Height = (int)(((double)prop.leg)	* ratio);

	string placement = "Top";
	Region region1(placement, 0, 0, region1Height, boxImage.cols);
	MomentCalculation2 mcalc;
	MomentAverage momentAverage1 = mcalc.getAverageColourInConvexRegion(boxImage, cmaskImage, &region1);
	MomentStandardDeviation momentStandardDeviation1 = mcalc.getStandardDeviationInConvexRegion(boxImage, cmaskImage, &region1, &momentAverage1);
	MomentSkewness momentSkewness1 = mcalc.getSkewnessnInConvexRegion(boxImage, cmaskImage, &region1, &momentAverage1);
	region1.setMoments(&momentAverage1, &momentStandardDeviation1, &momentSkewness1);


	placement = "Middle";
	Region region2(placement, 0, 0, region2Height, boxImage.cols);
	MomentAverage momentAverage2 = mcalc.getAverageColourInConvexRegion(boxImage, cmaskImage, &region2);
	MomentStandardDeviation momentStandardDeviation2 = mcalc.getStandardDeviationInConvexRegion(boxImage, cmaskImage, &region2, &momentAverage2);
	MomentSkewness momentSkewness2 = mcalc.getSkewnessnInConvexRegion(boxImage, cmaskImage, &region2, &momentAverage2);
	region2.setMoments(&momentAverage2, &momentStandardDeviation2, &momentSkewness2);

	placement = "Bottum";
	Region region3(placement, 0, 0, region3Height, boxImage.cols);
	MomentAverage momentAverage3 = mcalc.getAverageColourInConvexRegion(boxImage, cmaskImage, &region3);
	MomentStandardDeviation momentStandardDeviation3 = mcalc.getStandardDeviationInConvexRegion(boxImage, cmaskImage, &region3, &momentAverage3);
	MomentSkewness momentSkewness3 = mcalc.getSkewnessnInConvexRegion(boxImage, cmaskImage, &region3, &momentAverage3);
	region3.setMoments(&momentAverage3, &momentStandardDeviation3, &momentSkewness3);


	Blob blob(blobId, boxImage.rows, boxImage.cols);
	blob.human_id_actual = profileId;
	blob.addRegion(&region1);
	blob.addRegion(&region2);
	blob.addRegion(&region3);

	return blob;
}
Beispiel #15
0
    void onDraw(SkCanvas* canvas) override {
        for (unsigned b = 0; b < SK_ARRAY_COUNT(blobConfigs); ++b) {
            SkAutoTUnref<const SkTextBlob> blob(this->makeBlob(b));

            SkPaint p;
            SkPoint offset = SkPoint::Make(SkIntToScalar(10 + 300 * (b % 2)),
                                           SkIntToScalar(20 + 150 * (b / 2)));

            canvas->drawTextBlob(blob, offset.x(), offset.y(), p);

            p.setColor(SK_ColorBLUE);
            p.setStyle(SkPaint::kStroke_Style);
            SkRect box = blob->bounds();
            box.offset(offset);
            canvas->drawRect(box, p);

        }
    }
Beispiel #16
0
int simple_ctable::find(const dtype & key, colval * values, size_t count) const
{
	blob row = base->find(key);
	if(!row.exists())
	{
		for(size_t i = 0; i < count; i++)
			values[i].value = blob();
		return 0;
	}
	/* not super efficient, but we can fix it later */
	index_blob sub(column_count, row);
	for(size_t i = 0; i < count; i++)
	{
		assert(values[i].index < column_count);
		values[i].value = sub.get(values[i].index);
	}
	return 0;
}
Beispiel #17
0
void Marker3DTracker::updateFeatureTracking()
{
    if(isTracking()) {
        ImageLabeler::ConnectedComponent blob(_labeler->getBlobAt(_trackedFeaturePosition + _trackedFeatureSpeed, _trackedFeatureClass, _lookupRadius)); // predict new position linearly
        if(blob.classCount[_trackedFeatureClass] > 0 && blob.centerOfMass.distance(_trackedFeaturePosition) <= _lookupRadius) {
            // successful tracking
            _trackedFeatureSpeed = blob.centerOfMass - _trackedFeaturePosition;
            _trackedFeatureSpeed.x = std::floor(_trackedFeatureSpeed.x);
            _trackedFeatureSpeed.y = std::floor(_trackedFeatureSpeed.y);
            _trackedFeaturePosition = blob.centerOfMass;
            _trackedFeaturePosition.x = std::floor(_trackedFeaturePosition.x);
            _trackedFeaturePosition.y = std::floor(_trackedFeaturePosition.y);
            _trackedFeatureArea = blob.pixels.size();
        }
        else
            endFeatureTracking();
    }
}
Beispiel #18
0
void mdeath::blobsplit(monster *z)
{
    int speed = z->speed - rng(30, 50);
    g->m.spawn_item(z->posx(), z->posy(), "slime_scrap", 1, 0, calendar::turn, rng(1, 4));
    if (speed <= 0) {
        if (g->u_see(z)) {
            //  TODO:  Add vermin-tagged tiny versions of the splattered blob  :)
            add_msg(m_good, _("The %s splatters apart."), z->name().c_str());
        }
        return;
    }
    monster blob(GetMType((speed < 50 ? "mon_blob_small" : "mon_blob")));
    blob.speed = speed;
    // If we're tame, our kids are too
    blob.friendly = z->friendly;
    if (g->u_see(z)) {
        if(z->type->dies.size() == 1) {
            add_msg(m_good, _("The %s splits in two!"), z->name().c_str());
        } else {
            add_msg(m_bad, _("Two small blobs slither out of the corpse."), z->name().c_str());
        }
    }
    blob.hp = blob.speed;
    std::vector <point> valid;

    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            bool moveOK = (g->m.move_cost(z->posx() + i, z->posy() + j) > 0);
            bool monOK = g->mon_at(z->posx() + i, z->posy() + j) == -1;
            bool posOK = (g->u.posx != z->posx() + i || g->u.posy != z->posy() + j);
            if (moveOK && monOK && posOK) {
                valid.push_back(point(z->posx() + i, z->posy() + j));
            }
        }
    }

    int rn;
    for (int s = 0; s < 2 && !valid.empty(); s++) {
        rn = rng(0, valid.size() - 1);
        blob.spawn(valid[rn].x, valid[rn].y);
        g->add_zombie(blob);
        valid.erase(valid.begin() + rn);
    }
}
Beispiel #19
0
    // Verify that text-related properties are captured in run paints.
    static void TestPaintProps(skiatest::Reporter* reporter) {
        SkFont font;
        // Kitchen sink font.
        font.setSize(42);
        font.setScaleX(4.2f);
        font.setTypeface(ToolUtils::create_portable_typeface());
        font.setSkewX(0.42f);
        font.setHinting(SkFontHinting::kFull);
        font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
        font.setEmbolden(true);
        font.setLinearMetrics(true);
        font.setSubpixel(true);
        font.setEmbeddedBitmaps(true);
        font.setForceAutoHinting(true);

        // Ensure we didn't pick default values by mistake.
        SkFont defaultFont;
        REPORTER_ASSERT(reporter, defaultFont.getSize() != font.getSize());
        REPORTER_ASSERT(reporter, defaultFont.getScaleX() != font.getScaleX());
        REPORTER_ASSERT(reporter, defaultFont.getTypefaceOrDefault() != font.getTypefaceOrDefault());
        REPORTER_ASSERT(reporter, defaultFont.getSkewX() != font.getSkewX());
        REPORTER_ASSERT(reporter, defaultFont.getHinting() != font.getHinting());
        REPORTER_ASSERT(reporter, defaultFont.getEdging() != font.getEdging());
        REPORTER_ASSERT(reporter, defaultFont.isEmbolden() != font.isEmbolden());
        REPORTER_ASSERT(reporter, defaultFont.isLinearMetrics() != font.isLinearMetrics());
        REPORTER_ASSERT(reporter, defaultFont.isSubpixel() != font.isSubpixel());
        REPORTER_ASSERT(reporter,
                        defaultFont.isEmbeddedBitmaps() != font.isEmbeddedBitmaps());
        REPORTER_ASSERT(reporter, defaultFont.isForceAutoHinting() != font.isForceAutoHinting());

        SkTextBlobBuilder builder;
        AddRun(font, 1, SkTextBlobRunIterator::kDefault_Positioning, SkPoint::Make(0, 0), builder);
        AddRun(font, 1, SkTextBlobRunIterator::kHorizontal_Positioning, SkPoint::Make(0, 0),
               builder);
        AddRun(font, 1, SkTextBlobRunIterator::kFull_Positioning, SkPoint::Make(0, 0), builder);
        sk_sp<SkTextBlob> blob(builder.make());

        SkTextBlobRunIterator it(blob.get());
        while (!it.done()) {
            REPORTER_ASSERT(reporter, it.font() == font);
            it.next();
        }

    }
Beispiel #20
0
	void savePrefab(const Path& path) override
	{
		auto& selected_entities = m_editor.getSelectedEntities();
		if (selected_entities.size() != 1) return;

		Entity entity = selected_entities[0];
		u64 prefab = getPrefab(entity);
		if (prefab != 0) entity = getPrefabRoot(entity);

		FS::OsFile file;
		if (!file.open(path.c_str(), FS::Mode::CREATE_AND_WRITE))
		{
			g_log_error.log("Editor") << "Failed to create " << path.c_str();
			return;
		}

		Array<Entity> entities(m_editor.getAllocator());
		gatherHierarchy(entity, true, entities);
		OutputBlob blob(m_editor.getAllocator());
		SaveEntityGUIDMap entity_map(entities);
		TextSerializer serializer(blob, entity_map);

		serializePrefab(m_universe, entities[0], path, serializer);

		file.write(blob.getData(), blob.getPos());

		file.close();

		if (prefab == 0)
		{
			m_editor.beginCommandGroup(crc32("save_prefab"));

			Transform tr = m_universe->getTransform(entity);
			m_editor.destroyEntities(&entities[0], entities.size());
			auto* resource_manager = m_editor.getEngine().getResourceManager().get(PrefabResource::TYPE);
			auto* res = (PrefabResource*)resource_manager->load(path);
			FS::FileSystem& fs = m_editor.getEngine().getFileSystem();
			while (fs.hasWork()) fs.updateAsyncTransactions();
			instantiatePrefab(*res, tr.pos, tr.rot, tr.scale);

			m_editor.endCommandGroup();
		}
	}
void ShaderEditor::save(const char* path)
{
	FILE* fp = fopen(path, "wb");
	if (!fp)
	{
		Lumix::g_log_error.log("Editor") << "Could not save shader " << path;
		return;
	}

	Lumix::OutputBlob blob(m_allocator);
	blob.reserve(4096);
	for (int i = 0; i < Lumix::lengthOf(m_textures); ++i)
	{
		blob.writeString(m_textures[i]);
	}

	int nodes_count = m_vertex_nodes.size();
	blob.write(nodes_count);
	for(auto* node : m_vertex_nodes)
	{
		saveNode(blob, *node);
	}

	for(auto* node : m_vertex_nodes)
	{
		saveNodeConnections(blob, *node);
	}

	nodes_count = m_fragment_nodes.size();
	blob.write(nodes_count);
	for (auto* node : m_fragment_nodes)
	{
		saveNode(blob, *node);
	}

	for (auto* node : m_fragment_nodes)
	{
		saveNodeConnections(blob, *node);
	}

	fwrite(blob.getData(), blob.getSize(), 1, fp);
	fclose(fp);
}
    void WriteLine(const SkShaper& shaper, const char *text, size_t textBytes) {
        if (!pageCanvas || current_y > config->page_height.value) {
            if (pageCanvas) {
                document->endPage();
            }
            pageCanvas = document->beginPage(config->page_width.value,
                                             config->page_height.value);
            pageCanvas->drawPaint(white_paint);
            current_x = config->left_margin.value;
            current_y = config->line_spacing_ratio.value * config->font_size.value;
        }
        SkTextBlobBuilder textBlobBuilder;
        shaper.shape(&textBlobBuilder, glyph_paint, text, textBytes, SkPoint{0, 0});
        sk_sp<const SkTextBlob> blob(textBlobBuilder.build());
        pageCanvas->drawTextBlob(blob.get(), current_x, current_y, glyph_paint);

        // Advance to the next line.
        current_y += config->line_spacing_ratio.value * config->font_size.value;
    }
            // helper routines to accelerate learning
            int simple_kv_service_impl::get_learn_state(decree start, const blob& learn_req, __out_param learn_state& state)
            {
                ::dsn::binary_writer writer;

                zauto_lock l(_lock);

                int magic = 0xdeadbeef;
                writer.write(magic);

                writer.write(_last_committed_decree.load());

                dassert(_last_committed_decree >= 0, "");

                uint64_t count = static_cast<uint64_t>(_store.size());
                writer.write(count);

                for (auto it = _store.begin(); it != _store.end(); it++)
                {
                    writer.write(it->first);
                    writer.write(it->second);
                }

                auto bb = writer.get_buffer();
                auto buf = bb.buffer();

                state.meta.push_back(blob(buf, static_cast<int>(bb.data() - bb.buffer().get()), bb.length()));
                
                // Test Sample
                if (_test_file_learning)
                {
                    std::stringstream ss;                
                    ss << env::random32(0, 10000);

                    auto learn_test_file = data_dir() + "/test_learning_" + ss.str() + ".txt";
                    state.files.push_back(learn_test_file);
                    
                    std::ofstream fout(learn_test_file.c_str());
                    fout << "DEADBEEF" << std::endl;        
                    fout.close();        
                }

                return 0;
            }
Beispiel #24
0
void CSkypeProto::LoadContactsAuth(const NETLIBHTTPREQUEST *response)
{
	if (response == NULL)
		return;

	JSONNode root = JSONNode::parse(response->pData);
	if (!root)
		return;

	const JSONNode &items = root.as_array();
	for (size_t i = 0; i < items.size(); i++)
	{
		const JSONNode &item = items.at(i);
		if (!item)
			break;

		std::string skypename = item["sender"].as_string();
		std::string reason = item["greeting"].as_string();
		time_t eventTime = IsoToUnixTime(item["event_time_iso"].as_string().c_str());

		MCONTACT hContact = AddContact(skypename.c_str());
		if (hContact)
		{
			time_t lastEventTime = db_get_dw(hContact, m_szModuleName, "LastAuthRequestTime", 0);

			if (lastEventTime < eventTime)
			{
				db_set_dw(hContact, m_szModuleName, "LastAuthRequestTime", eventTime);
				delSetting(hContact, "Auth");

				DB_AUTH_BLOB blob(hContact, NULL, NULL, NULL, skypename.c_str(), reason.c_str());

				PROTORECVEVENT pre = { 0 };
				pre.timestamp = time(NULL);
				pre.lParam = blob.size();
				pre.szMessage = blob;

				ProtoChainRecv(hContact, PSR_AUTH, 0, (LPARAM)&pre);
			}
		}
	}
}
int32_t cc_setSigPoint(const uint32_t &type, const uint8_t &model, const uint16_t &x, const uint16_t &y, Chirp *chirp)
{
	RectA region;
	int result; 
	char id[32];
	ColorModel cmodel;

	if (model<1 || model>NUM_MODELS)
		return -1;

	cc_setBounds(type);

	if (g_rawFrame.m_pixels==NULL)
	{
		cprintf("No raw frame in memory!\n");
		return -2;
	}

	result = g_blobs->generateLUT(model, g_rawFrame, Point16(x, y), &cmodel, &region);
  	if (result<0)
	{
		cprintf("Color saturation isn't high enough!\n");
		return result;
	}

	if (chirp)
	{
		BlobA blob(model, region.m_xOffset, region.m_xOffset+region.m_width, region.m_yOffset, region.m_yOffset+region.m_height);
		cc_sendBlobs(chirp, &blob, 1, RENDER_FLAG_FLUSH | RENDER_FLAG_BLEND_BG);
	}

	cmodel.m_type = type;

	// save to flash
	sprintf(id, "signature%d", model);
	prm_set(id, INTS8(sizeof(ColorModel), &cmodel), END);
	prm_setDirty(false); // prevent reload (because we don't want to load the lut (yet) and lose our frame

	cprintf("Success!\n");

	return result;
}
TYPED_TEST(DataTransformTest, TestMeanValue) {
    TransformationParameter transform_param;
    const bool unique_pixels = false;  // pixels are equal to label
    const int label = 0;
    const int channels = 3;
    const int height = 4;
    const int width = 5;
    const int mean_value = 2;

    transform_param.add_mean_value(mean_value);
    Datum datum;
    FillDatum(label, channels, height, width, unique_pixels, &datum);
    Blob<TypeParam> blob(1, channels, height, width);
    DataTransformer<TypeParam> transformer(transform_param, TEST);
    transformer.InitRand();
    transformer.Transform(datum, &blob);
    for (int j = 0; j < blob.count(); ++j) {
        EXPECT_EQ(blob.cpu_data()[j], label - mean_value);
    }
}
MCONTACT CSkypeProto::AddToListByEvent(int, int, MEVENT hDbEvent)
{
	debugLogA(__FUNCTION__);
	DBEVENTINFO dbei = { sizeof(dbei) };
	if ((dbei.cbBlob = db_event_getBlobSize(hDbEvent)) == (DWORD)(-1))
		return NULL;
	if ((dbei.pBlob = (PBYTE)alloca(dbei.cbBlob)) == NULL)
		return NULL;
	if (db_event_get(hDbEvent, &dbei))
		return NULL;
	if (mir_strcmp(dbei.szModule, m_szModuleName))
		return NULL;
	if (dbei.eventType != EVENTTYPE_AUTHREQUEST)
		return NULL;

	DB_AUTH_BLOB blob(dbei.pBlob);
	
	MCONTACT hContact = AddContact(ptrA(blob.get_id()));
	return hContact;
}
Beispiel #28
0
int simple_ctable::remove(const dtype & key, size_t column)
{
	int r = insert(key, column, blob());
	if(r >= 0)
	{
		bool exist = false;
		blob row = base->find(key);
		/* TODO: improve this... it is probably killing us */
		index_blob sub(column_count, row);
		for(size_t i = 0; i < column_count; i++)
			if(sub.get(i).exists())
			{
				exist = true;
				break;
			}
		if(!exist)
			remove(key);
	}
	return r;
}
Beispiel #29
0
void MagickImageExporter::saveToStream(const ImageRawData& image, std::ostream& os) {
    if (image.isNull())
        throw Exception("[MagickImageExporter::save] null image given");

    if (os.fail())
        throw Exception("[MagickImageExporter::save] invalid stream");

    Magick::Blob blob(image.data(), image.dataSize());
    try {
        Magick::Image image;
        image.verbose(true);
        image.magick("DIB");
        image.read(blob);
        image.magick(formatToString(format()));
        image.write(&blob);
        os.write((char*) blob.data(), blob.length());
    } catch (Magick::Exception &e) {
        std::cerr << e.what() << "\n";
        throw Exception("MagickImageExporter::load failed");
    }
}
EXPORT_C void RSearchServerSubSession::GetBatchDocument(TInt aIndex, TRequestStatus& aStatus, TInt aCount)
	{
	PERFORMANCE_LOG_START("RSearchServerSubSession::GetBatchDocument");

	iDocumentSize = 0;
	iReqCount = aCount;
	    
    if (iSizeList)
        {
        delete iSizeList;
        iSizeList = NULL;
        }
    TRAP_IGNORE(iSizeList = STATIC_CAST(TInt *, User::AllocZL(iReqCount * sizeof(TInt))));
    //iDocSizeArray
    TPtr8 blob((TUint8*)iSizeList, iReqCount * sizeof(TInt));
	    
    // Message arguments for the server
    TIpcArgs args(aIndex, aCount, &blob);
    
	SendReceive(ESearchServerGetBatchDocument, args, aStatus );
	}