Personal Journal

Public Journal

Read the latest posts from Personal Journal. To add your blog posts to this page, set your blog settings to “Public”

from Paul Sutton

Worlds oldest shipwreck

How the world's deepest shipwreck was found – BBC Future

This is a really interesting article from the BBC Futures website, US navy ship sunk during a battle with the Japanese navy during WWII has been found deep in the Ocean 70+ years after it was lost at sea.

As the article suggests 'We know more about outer space than the Oceans', however, there is another article following on from this on how NASA are using what we are learning about deep sea exploration and using that to help with space exploration. If you scroll down the page then you should find:-

Why Nasa is exploring the deepest oceans on Earth

Which gives more information, it shows how an interest or experience in what would seem very different, can be applied elsewhere, so an Oceanographer for example can work with NASA to help explore planetary systems.

So perhaps some very exciting things to come in the future.

 
Read more...

from Paul Sutton

Demo of Physics Ideas

I am in a slow process of collecting some materials for the Five DIY physics demos from Symmetry Magazine. So far I have:-

  • String
  • Rubber Balls
  • Small metal ball bearings
  • Rubber Sheet
  • Ping pong balls

With a 30cm x 30cm sheet of 1mm thick rubber. This can be used to demonstrate space and a ball or other object placed on this will bend the sheet around it.

The image from Open Clip art – sort of illustrates this in terms of a black hole.

warping

This makes sense if you understand the physics, just hard to explain here.

I need some tennis balls, but I can pick them up easy enough. Hopefully I can do some of this at the next STEM group meeting, if not it is something that can be undertaken in a school, where I can get help from teachers & technicians. I don't think a TA is expected to do the whole demo :)

I am not sure if I can get hold of iron sand easily, but a school can though.

On a sort of related note, chemistry related I have downloaded a worksheet to investigate neutralisation of toothpaste from the Royal Society of Chemistry education resources. Again this could be useful when working in a school.

 
Read more...

from Adept Clipping Path

Just how to get a top-quality image manipulation service at affordable expenses?

A knowledgeable image manipulation service can quickly establish your e-commerce service in a different way from your leading competitors. In the contemporary age, the shopping clothes fields are just one of the quickest expanding sectors on the global internet.

Because of this, they frequently need a high-grade image manipulation service at affordable expenses for their SEO-optimized internet sites or online selling stores.

As a result, you can effortlessly obtain high-grade photo adjustment services at affordable expenses from the most experienced group of Adept Trimming Course. So, begin reading from now. Delighted Understanding!!

There are generally 3 kinds of picture control solutions: Neck Joint Ghost Mannequin Sleeve Joint

1 #. Neck Joint: The central principle of the neck joint is that after the mannequin is gone, the area's back part will be vacant. Additionally, the clothes will be hidden without the back section. The back part of the gown commonly contains some places such as tags, dimension info, and also the company logo, and other things.

Skilled Trimming Course has a lots of professional groups for digital picture manipulation solutions that will supply the best top quality results and also preserve a long-term relationship.

Currently, Skilled Clipping Course is providing the neck joint image manipulation service at the most affordable price arrays starting from $1.00 per photo. 2 #. Ghost Mannequin:

The ghost mannequin is one of the most appealing kinds of photoshop image control services. You might need a solitary symptom of the clothing without using the mannequin or a 360 ° turning. Both of the requirements are split as well as joined in the same way.

Nonetheless, we may call for photos from different perspectives by rotating the garments with the ghost mannequin for the 360 ° rotation.

Therefore, you can obtain the premium ghost mannequin under image control services from Adept Clipping Path at budget-friendly costs that usually start from $1.00 per photo.

3 #. Sleeve Joint: It's a type of mannequin result used to complete the overall visual aspect. Nonetheless, this is usually relevant for sleeve garments. In this situation, the complete clothing and also the behind of the sleeves without the mannequin can be called for. Like the previous ghost mannequin solution, we'll efficiently link the back location for sleeves.

By comparison, you will get the top-quality sleeve joint under image manipulation service at the cheapest rates from us, Adept Clipping Course. The rate initially begins with $1.50 per image.

Finally

The art of changing any kind of item picture through utilizing various processes and techniques to acquire desired outcomes is called photo manipulation. For that reason, the top notch image manipulation service is a have to for maturing your e-commerce organization quickly.

We have an appealing pipe of Photoshop specialists who can integrate 2 or even more pictures into a single image according to our client's expectations.

So, declare our top-notch picture manipulation solutions at your affordable budget plan. Pleased image manipulation service !!

FREQUENTLY ASKED QUESTION: 1. How much can I charge for my normal image manipulation service? It can differ from one person to another. Nonetheless, you can charge $25—$ 150 each hour for picture modifying, depending on your previous experience, skill degree, the complexity of edits, turnaround time, and the number of pictures you have already finished.

  1. How do you select the most knowledgeable clipping path service provider?

For choosing one of the most effective clipping course service providers, you can use the following pointers: Ask in your professional network for referrals. Talk about with your buddies, colleagues, email your peers or blog post on social media systems. Trying to find an expert provider in your area. Have a look at all outsourced service industries. Read all relied on as well as popular market publications.

 
Read more...

from Paul Sutton

Searching for information – Debian release notes

One essential skill is to be able to search for information. This is expected of people before they ask questions. In looking for Debian release notes I tried a search on the Debian website, only to find a link to Debian 3, and also Debian 12 which is the next release.

release notes

If you get a similar issues, I would suggest redoing the search in something like DduckDuckGo or similar . Searx, is a privacy respecting meta data search engine.

Links

TAGS

#Debian,#Website,#Search,#ReleaseNotes,#Results


Donate using Liberapay

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License

 
Read more...

from Adept Clipping Path

Image Masking Service: The Secret Things You Required To Know First

Today, image masking service is one of the most valuable as well as renowned options in visual communication. It's important because greater than 40% of online clients today anticipate to see their things on a clear uniform background.

Nonetheless, an active professional photographer will certainly not supply all of his product pictures with a white background. You have come to the spot if you're trying to find a vital image masking service. Below, dealing with Adept Cutting Course will certainly conserve you added time by focusing on your company's development.

To get more information about a trusted image masking service, keep checking out till the end. Pleased Knowing!!

What Is Image Masking? Photo masking, frequently called layer masking, is an image modifying procedure for exposing or concealing areas of a product photo. Nonetheless, clipping paths are commonly used for background elimination.

Essentially, layer masking is needed when the image has challenging soft edges, shapes, numerous spins, and also curves. Furthermore, hair covering up in Photoshop plays an important function to address countless issues.

Exactly How Do Picture Masking Services Job Effectively?

Even digital photographers, style as well as magazine designers, and also e-commerce online marketers frequently call for picture covering up solutions for the highest results.

When the topic is fur, fire, or hair, spectacles, feather, fires, highlights, lights, chiffon, muslin, or a covering, you need to select significantly much more detail. Consequently, you require to use Adobe Photoshop hair covering up services to increase precision as well as obtain the maximum results.

That Will Obtain The Leading Take Advantage Of Image Masking Providers?

Before posting the photographs to the ecommerce shop, removing the history is vital. Photoshop masking makes life much easier for all photo editors when working with a task including pet features. Therefore, ecommerce local business owner need to use this expert service to make sure that their item photos fulfill their sector needs.

Aside from that, clients of photography studios likewise require clipping courses and also image masking services. It is difficult for them to supply in a timely manner because they have numerous photographs to process. Art specialists are always looking for aesthetically appealing pictures that are perfect.

Furthermore, publishing companies always require image concealing remedies for online and also offline cultural and also creative pictures.

Reasons that You Should Work With Us For Picture Masking Services: Adept Clipping Course

The adhering to are a few of the leading reasons for making use of a knowledgeable image masking service:

We have 150+ knowledgeable photo editors on staff with over 8 years of experience in this field. We on a regular basis complete this sort of job with no hold-up.

You will receive a high-quality customized photograph under your reasonable spending plan from us.

We can provide you with high quality guarantee at a lower expense than other service providers.

We have three changes of service carriers readily available 24 hr a day, 7 days a week, as well as 24/7/365 annually.

Our average distribution time is 24 hr, however we provide same-day solution at a slightly greater rate than usual for urgent orders.

We do not bill a cost till our client is totally completely satisfied.

Reformatories abound.

We usually offer a big discount rate if you can get any kind of picture.

Consumer contentment is our leading concern.

Image Masking Service [Finally]

In summary, photo masking in Photoshop is very valuable and also renowned for expert or trade applications like advertisements, flyers, journals, brochures, brochures, and also web sites.

By contrast, a competent professional photographer will never catch every image perfectly or effectively. Bothersome facets can harm picture quality. So, it's a sensible point to utilize an excellent image masking service.

If you're a shopping business owner or agency, you'll require a picture masking option to make your product look even more sharp, clear, as well as attracting to customers. Additionally, you'll call for an image masking service if your product picture is unclear.

Nobody will buy your things if they aren't clean or enticing to the eye. As a result, a knowledgeable image concealing service is necessary to produce even more customers.

Be pleased with the image masking service!!

 
Read more...

from Paul Sutton

Use pastebin from command line

Use pastebin from command line

Quite often, when you have a problem where, in order to get help you need to paste the contents of a file,or command output so that it can be shared, for example on IRC (Chat) or a forum, this can be challenging to begin with.

As it is depreciated that you paste more than 2 lines in to IRC chat. The way round this is to use a service called pastebin. Debian [1] has it's own service for this [2]. There is a tool called pastebinit which is really helpful from the command line.

The first step is to switch to the root user. Sear for and install the package pastebinit as per below.

Search

root@Desktop:/home/user# apt search pastebinit
Sorting... Done
Full Text Search... Done
pastebinit/stable 1.5.1-1 all
  command-line pastebin client

Install

root@Desktop:/home/user# apt install pastebinit
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  linux-image-5.10.0-7-amd64 linux-image-5.10.0-8-amd64
Use 'apt autoremove' to remove them.
The following NEW packages will be installed:
  pastebinit
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 46.6 kB of archives.
After this operation, 342 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian bullseye/main amd64 pastebinit all 1.5.1-1 [46.6 kB]
Fetched 46.6 kB in 0s (342 kB/s)
Selecting previously unselected package pastebinit.
(Reading database ... 190310 files and directories currently installed.)
Preparing to unpack .../pastebinit_1.5.1-1_all.deb ...
Unpacking pastebinit (1.5.1-1) ...
Setting up pastebinit (1.5.1-1) ...
Processing triggers for man-db (2.9.4-2) ...
root@Desktop:/home/user# 

Once complete switch back to normal user (usually type exit)

user@Desktop:~$ cat /etc/apt/sources.list > pastebinit
user@Desktop:~$ cat /etc/apt/sources.list | pastebinit
https://paste.debian.net/1228146/

In this example I have used the cat command and piped the contents in to pastebinit, this has given me a url to paste in to chat, (or copy manually)

Open this in a browser and you and others can see the contents, and people can help you further.

paste bin it output

This is really useful too if you are stuck at the command prompt, without a graphical interface.

Links

1 Debian 2 pastebin – debian 3 Paignton Library STEM Group TAGS

#Debian,#GNULinux,#Paste,#Text,#Pastebin,#Share,#Troubleshooting


Donate using Liberapay

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License

 
Read more...

from Marion Petersen

Dependable Homebuyers is a local home buying company in Baltimore, MD. We buy houses in any condition and any situation. If you want to sell your house fast, give us a call at (443) 266-6247 and we’ll provide you a cash offer within 24 hours.

Dependable Homebuyers 1402 Belt St, Baltimore, MD 21230 (443) 266-6247

Website: https://www.google.com/maps?cid=15265249344206879829

Our Business Pages:

https://www.facebook.com/dependablehomebuyersbaltimore

https://twitter.com/bmorehousebuyer

https://www.instagram.com/dependablehomebuyersbaltimore/

https://www.linkedin.com/company/dependable-homebuyers-baltimore/about/

https://www.youtube.com/channel/UCJsaBo_VWobCKL4QTTLoLgQ/about

 
Read more...

from World Wide News

Как именно открыть онлайн-казино: основные факторы

Онлайн-казино — прибыльная организация, которая при правильной стратегии не только легко окупит первоначальные затраты, но и начнет приносить регулярную прибыль. Многие задаются вопросом, как открыть онлайн-казино и при этом не прогореть? Стоит рассмотреть это более подробно.

Компания

Прежде чем приступить к запуску онлайн-казино, вы должны позаботиться о том, чтобы найти, как и лучшие онлайн-казино https://dochub.com.ua/, программное обеспечение высочайшего качества. Это означает, что потенциальному предпринимателю необходимо:

рассмотреть предложения от востребованных бизнесов; проанализировать общий опыт выбранных фирм в сфере гемблинга; изучить мнения о товарах, которые предлагает компания.

Опытные бизнесмены советуют не экономить на приобретении софта для онлайн-казино. Выбор должен быть предоставлен проверенным производителям, ведь именно ведущие поставщики обещают бесперебойную работу систем.

Игровой материал

Другой период связан с подбором спортивных поставщиков, которые будут регулярно представлять новые азартные развлечения. Лучше определиться с предприятиями, в ассортименте которых есть:

общие слоты; покер; рулетка; карточные мероприятия; бинго; баккара.

В последнее время востребована деятельность с торговцами пребыванием, что также следует изучить.

Игровая лицензия

Обязательным элементом, который обязательно должны учитывать те, кто хотел бы начать свое собственное веб-казино, является подписка на игорную лицензию. Перед получением официального файла следует внимательно изучить особенности игорной организации и глубже изучить выбранную сферу.

Следует отметить, что не абсолютно все места позволяют вам иметь дело с лицензией. Общие юрисдикции:

Хорошая Британия; Кюрасао; Гибралтар; Олдерни.

Также вы можете получить себе лицензию на ведение игорной деятельности на острове Мэн. При выборе документа желательно учитывать популярность, срок действия и стоимость бумаги.

Система затрат

Онлайн-казино должно быть не только увлекательным и азартным, но и удобным для зарегистрированных пользователей. Прежде чем начать бизнес, вы должны тщательно продумать способы оплаты, которые будут доступны игрокам, а также установить ограничения на ввод и вывод средств.

Лучшим ответом для владельца игорной организации будет заключение договоров с несколькими платежными системами. Это увеличит рынок и повысит привлекательность платформы. Часто такими способами являются банковские карты, цифровые кошельки и портативные операторы.

Сайт

Очевидно, что онлайн-казино не сможет работать, если система не будет создана и запущена. При работе официального сайта игорной команды необходимо учитывать:

Дизайн. Он должен быть не просто красивым, но еще и привлекательным и качественным. интерфейс. Важно, что фактически новый посетитель официального сайта веб-казино может легко найти указанный раздел. Заполнение. Основной уровень сайта, скорее всего, будет занимать азартные развлечения: от рулетки до карточных активностей и обычных слотов. Поэтому предпочтительнее предлагать фильтрацию и области, где могут быть собраны лучшие слоты, новый период и другие классы.

Не так давно появилась возможность использовать шаблоны, которые на данный момент дают все необходимое для надежной работы платформы. Несколько предприятий также готовы бороться за прогресс и запуск уникальной платформы.

Повышение

Последним периодом развития игорной организации является маркетинг. Важно тщательно продумать план продвижения, с помощью которого, вероятно, удастся заманить гостей на сайт и завоевать доверие перечисленных пользователей. Часто в веб-казино начинаются приятные бонусы, что приводит к росту регистраций на официальном сайте игорной команды и увеличивает опыт работы системы в целом. Также продвигать казино можно в общих социальных сетях, на форумах или в тематических группах.

Онлайн-казино — это хорошо известная организация, которая будет приносить постоянный доход. Однако перед запуском собственной персональной системы вам необходимо будет учесть множество дополнительных моментов и подготовить необходимые документы для совершения законных действий.

 
Читать дальше...

from Rapid City Tours

My XO Adventures

What are the best Black Hills Tours? It's the Black Hills Guided Tours that are the most unforgettable and also extensive of the location. Our Mount Rushmore tours include more than monoliths. A few of the animals seen on the tour are Bison (Buffalo), Pronghorn, Antelope, Grassy Field Dogs, Bighorn Sheep, Burros as well as a range of birds! My XO Adventures is a Black Hills Excursion Company that has the ability to accessibility places and also viewpoints that the large Black Hills bus tours aren't able to reach. We pick you up and also drop you off directly from your lodgings in Rapid City, Keystone or Custer and also take you to right into the Black Hills of South Dakota. On our Mt Rushmore Tours, (generally our initial quit), we accompany you the whole way, offering info on its development and definition. We spend time below on the Grand Overlook and also the Visitors Facility. If you're up for it take a short walking on the Presidential Route Mt Rushmore for some unbelievable sights. Leaving the memorial we delight in attractive vistas of Iron Hill Roadway and after that on Custer State Park. The Custer State Park Tours we provide are like nothing else. This is where we venture off into the wild animals loop roadway to see the animals as well as right here the tales of the Black Hills History. Custer State Park comprises 71,000 acres of the Black Hills as well as is full of granite optimals, wildlife, and adventure. As soon as you have actually taken in all the appeal Custer State Park has to offer we appreciate an outing lunch and then onto needles eye tunnel. Said to be impossible to build, Needles Freeway takes us directly through the Needle's Eye passage as well as on Sylvan Lake in Custer State Park. Long before inhabitants came through this location, this was and still is the land of the Lakota. The Black Hills are exceptionally sacred to the Lakota. Crazy Equine Memorial and also the indigenous individuals of this land work hard to maintain the stories and practices active. This Memorial is yet unfinished, as well as you'll learn more about the progression of the monolith in addition to the family members as well as workers involved in its creation. When you're trying to find Guided Tours of the Black Hills, you've found a firm and also individuals that are passionate about this little slice of paradise. For each excursion acquired, we give away a part of the proceeds to The Indian University of North America at Crazy Equine Memorial. To the right we have actually given a map of Custer State Park in South Dakota. Some visitors map Custer State Park by themselves by hiking the many trails it gives.



Rapid City Tours

Our Social Pages:
Facebook
Twitter
Instagram
LinkedIn
YouTube

 
Read more...

from qqmrichter

In most programming, dynamic allocation and subsequent freeing of memory resources is normal. In embedded programming, dynamic SRAM allocation from the heap can be an application murderer (largely because having 128KB of SRAM is nigh luxurious and allocating 32KB of that to heap is crazy talk).

The issue that kills is heap fragmentation. If you're dynamically allocating and freeing objects willy-nilly, unless all of the objects happen to be exactly the same size you are going to eventually wind up in the ridiculous position of having enough free SRAM for an object, but no single piece big enough to hold it. Your application dies, starved for memory even though you have plenty of free space.

Response patterns

In response to this, several patterns of memory usage pop up in embedded software. The three most common patterns used by embedded systems programmers are:

  1. All-static, all the time.
  2. One-time dynamic allocation.
  3. Locally-paired allocation and deallocation.

I'll explain both what these patterns are (in brief) and then explain some of the issues each brings to the table: constraints on system capabilities and designs, so that the trade-offs you're bringing to the table when using these are made manifest.

(C++ users, when reading this, should s/malloc/new/ and s/free/delete/ with attendant minor syntax changes as needed in subsequent code reading.)

All-static, all the time

This one is simple and is most common in simpler embedded systems with fixed resources. Consider, for example, a simple device that reads an ADC and periodically calculates stats on the read data, perhaps logging those stats to a UART. Your ADC will, accordingly, need a buffer to write its data into and from which data will be read and analyzed for the reports.

Where do you put your buffer?

You put it in static space:

static uint16_t adc_buffer[64];

When you start your ADC, or analyze its results, your functions take the pointer to that static buffer like this:

start_adc(adc_buffer, 64);

Easy-peasy! If you want to do premature optimization (and thus be evil) you might even foolishly try to make adc_buffer a global variable and forego the trivial extra cost of passing a pointer.

Here's why you don't do that, though.

One-time dynamic allocation

All-static as a strategy works when you have fixed resources known at compile time. But what do you do when the resources can vary at run time and you're not able to predict at compile time? Let's say, for example, that the device mentioned above actually has up to 8 ADCs. You only know, however, which are connected when the software fires up. How do you cope with that?

If you went all-static you'd be declaring your adc_buffer more like this:

static uint16_t adc_buffer[8][64];

Your calls to start or analyze would then pick the right buffer to pass in based on which ADC you're reading:

start_adc(adc_buffer[3], 64);

This is, however, wasteful of resources if you're running in a device that only has 3 ADCs hooked up. A better approach would be something like this:

static uint16_t *adc_buffer;

You'd initialize it at application start-up by doing this:

adc_buffer = malloc(count_active_adcs() * 64);

(I am eliminating a check for that malloc return for clarity. If you don't check the return value of malloc in production code you need to be shot.)

You'd then use it like this, assuming you want the 4th ADC started:

start_adc(adc_buffer+3*64, 64);

(Of course really you'd use a symbolic name like BUFFER_SIZE instead of 64, and a variable like current_buffer instead of 3, but I'm trying to minimize excess code baggage here.)

This is a perfectly safe use of dynamic allocation because it is never freed. It is functionally the same as using static allocation, in terms of heap fragmentation, but it is more flexible in memory assignment. Indeed, for a variety of reasons, I tend to use this instead of static allocation in most of my projects, even simple ones with static resources. (One of the chief reasons: nothing ever stays simple and static over time.)

But it's still not universally applicable.

Locally-paired allocation and deallocation

A common situation I find myself in is having to allocate a temporary buffer to pass into a function for processing. The size of the buffer may vary from call to call and, worse, the buffer may be sizable: like say a 1K buffer. In a typical embedded environment this is far too large an entity to allocate on the stack (as a local variable). On the other hand, it's also a bad thing to have allocated statically. There may be a dozen functions that need this kind of buffering. If each one statically allocated its own (too-large because the size varies unpredictably each iteration) my SRAM would be eaten up before I can even link the app, not to mention run it, and if they tried sharing there's too great a chance that one steps on another's buffer. So we instead do this:

void my_funky_function(void *data, size_t data_bytes)
{
    uint8_t *buffer = malloc(data_bytes);
    do_something_with(data, data_bytes, buffer);
    free(buffer);
}

(Again, eschewing return value checks, etc. for brevity. Check your malloc in production code!)

This works without fragmenting memory, even if do_something_with() uses this same pattern internally, and maybe a further, deeper function also_do_with(). As long as the malloc and free calls are paired and nested this is not a problem.

In the following diagrams, _ is a bit of heap memory that is free. 1 is heap memory used by my_funky_function, 2 is used by do_something_with, and 3 is used by also_do_with, a function called by do_something_with. * is a bit of heap memory that is used by something out of scope.

When my_funky_function is entered, the heap will look something like this:

**_***__**____________________

When the memory for the buffer is allocated, and do_something_with is called, it will look like this:

**_***__**11111_______________

When do_something_with calls also_do_with the heap might look something like this:

**_***22**11111_______________

And finally while also_do_with is running, after its allocation, it might look like this:

**_***22**111113333333________

It's all nice and cosy. And here's the sequence as each function finishes and frees its resources:

**_***22**111113333333________   /* also_do_with() active      */
**_***22**11111_______________   /* do_something_with() active */
**_***__**11111_______________   /* my_funky_function() active */
**_***__**____________________   /* my_funky_function() exited */

In any sane heap implementation, the heap's layout will be identical upon exiting my_funky_function as it was before entering. There's no room for fragmentation and churn because the nested nature of allocation and deallocation ensures that the structure of the heap is reconstructed on the way out.

But...

All of this is fine and dandy and you can make some very nice applications that efficiently use SRAM without fragmentation this way. But there is one increasingly-common use case not represented here that some readers are already champing at the bit to correct.

What happens if you can't know in advance (even at application startup) how many items you need, and/or you can't put everything neatly into nested pairs?

I faced this problem head-on when writing an event queue system. Events in this system contain a lot of information:

  • time due
  • repetition interval
  • callback/coroutine
  • event data

And while there is an API for firing events from pre-allocated memory blocks, this API is inconvenient to use and makes the event system less attractive.

On the other hand, the first rendition of the event system that used calloc to allocate an event's resources, and then called free (both on the event and on its embedded data pointer) after the event's callback had been fired had a major problem: since the point of firing and the point of activation were often separated in time, and since allocating events themselves and event data blocks were interlaced and usually of different sizes, fragmentation of the heap was inevitable. And sure enough my test system would start being unable to allocate new events after only about a thousand iterations of the test.

So what's the solution?

Dynamically static allocation

I borrowed a page from the “One-time dynamic allocation” section above, with a twist: the “one-time” allocation was actually “exponentially-less-frequent multi-time allocation”.

It works like this. Given an event definition:

typedef struct event
{
    uint32_t activation_tick, repetition_interval;
    coroutine_t *callback;
    void *event_data;
    bool in_use;
} event_t;

Declare a pointer to the event_t in the static space of all the event queue management functions:

event_t *allocated_events;
size_t num_allocated_events;
#define INITIAL_SIZE 4

(INITIAL_SIZE is a number I pull out of my butt at first, but later tune according to measured high water marks to keep reallocations to a minimum.)

Allocating a new event in the system now looks something like this (keeping in mind that I'm not checking error returns and such for clarity):

event_t *allocate_event(void)
{
    if (!allocated_events) /* <1> */
    {
        allocated_events = calloc(INITIAL_SIZE, sizeof(event_t *));
        num_allocated_events = INITIAL_SIZE;
    }
retry:
    for (size_t i = 0; i < num_allocated_events; i++) /* <2> */
    {
        if (!allocated_events[i]) /* <3> */
        {
            allocated_events[i] = calloc(1, sizeof(event_t));
            allocated_events[i]->in_use = true;
            return allocated_events[i];
        }
        else if (allocated_events 
             && !allocated_events[i]->in_use) /* <4> */
        {
            allocated_events[i]->in_use = true;
            return allocated_events[i];
        }
    }
    double_allocated_events(); /* <5> */
    goto retry; /* <6> */
}

Wut

This needs some breaking down to explain and justify. (It may help, if you come from OOPsland, to look at the above again attaching the name “object pool” to the technique. Then the key concepts might fall into place, this being, in effect, the procedural precursor to object pools.)

<1> is a check that ensures that there are event slots available at all. If that pointer has not been initialized yet, we make an initial array based on an INITIAL_SIZE that has been selected with an eye toward typical usage patterns observed in the wild. Note that we've allocated an array of pointers to event_t here, not the actual event_t objects themselves!

<2> simply iterates over every item in allocated_events looking for the first available slot. An available slot is either one that hasn't been allocated an event_t object yet (<3>) or one that has been allocated but is no longer in use (<4>).

(I commit the dark evil here of returning from the middle of a function, yes. And I commit an even darker evil later. Both are because the logic is otherwise difficult to follow for no good reason beyond sticking to dogma.)

If that loop finishes, there were no event slots available so I double the size of the array (<5>) and try again (<6>).

(<6> is my second, even darker evil. I use a gasp! goto! Pull my programmer license stat! Even if the goto-less version of this obfuscates intent for no good reason!)

This trick of double-and-retry looks dangerous at first glance, but keep in mind that if the allocation fails, I actually test it in production code, and bug out. This is a very simplified version of the final product specifically to highlight a technique. The way the real code works it's guaranteed that there will be a slot available the second time, or the second time won't even execute.

So, this is a lot to take in. One question that will immediately come to mind is “why are you allocating individual events dynamically instead of making it an array of event_t? The reason for this lies in the secret sauce of double_allocated_events().

Secret sauce

void double_allocated_events(void)
{
    size_t current_size = num_allocated_events;
    size_t new_size = current_size * 2;
    allocated_events = realloc(allocated_events, 
                       new_size * sizeof(event_t *));
    memset(&allocated_events[current_size], 0, 
            current_size * sizeof(event_t *));
}

Events fly through the system as pointers. If you had an array of event_t, the moment realloc is called, there is a very real (almost certain!) chance that events in flight have suddenly been rendered bad. It is for this reason that the array of event slots is an array of pointers, each of which is individually allocated. While in theory this leads to some inevitable heap fragmentation, in practice (if the system is properly tuned with a good INITIAL_SIZE) the number of such reallocations is minimal and thus so is any attendant fragmentation. Even using a small INITIAL_SIZE value (2, say), leads to a minimum amount of fragmentation because the exponential nature of the doubling means your queue of event slots will rapidly grow to the size you need after which it will never have to be allocated again.

Deallocation

Deallocating an event now looks like this:

void deallocate_event(event_t *e)
{
    e->in_use = false;
}

Events are just flagged as available, and the next time a “dynamic” event is needed, an available event is returned.

Improvement

There is room for improvement in the above design. Specific improvements could include:

  1. Linear growth.
  2. Chunked event allocation.
  3. Event availability management.

None of these are currently implemented because the event queue system currently in place more than meets my needs in real-time embedded control. Should this change, however, there are obvious improvements which could be made that will not in any way change the API (and thus the clients) of the event queue system.

Linear growth.

I use a doubling scheme here. This means that if I use a single event past a threshold, I have a lot of slack space. For example with an INITIAL_SIZE of 4, if my high water mark is 5, I will have three event_t * spaces left doing nothing.

This is not a major problem in my systems thus far precisely because the slot array is an array of pointers. The slack space in the above example (taken from real world data) is 12 bytes on my target machine. I'm not yet at the point where I'm counting down to double-digit bytes for eking out memory. If I get there, I can use a different growth scheme like going up by INITIAL_SIZE instead of doubling (possibly using a linked list so that I'm not even reallocating). This will increase the number of (re)allocations (with commensurate risk of fragmentation) in exchange for lower overall memory usage.

Chunked event allocation.

Currently I calloc new events as I grow into the empty slots. Given that this can occur at random points in the execution time, it guarantees a small amount of fragmentation. Again real-world data suggests it's not a problem for me, but should it become a problem, I would improve this with chunk-allocation of events both the first time that the events are allocated and when they're doubled (or otherwise grown).

The technique would be to calloc(count, sizeof(event_t)) and then treat the result as an array of event_t, putting the pointer of each item into the allocated_events array. The advantage of this is that by allocating the chunks all at once I reduce fragmentation opportunities. The disadvantage is that I waste, in the previous example (high water 5 with an INITIAL_SIZE of 4), 60 bytes of RAM (3 unnecessarily-allocated events, each sized 20 bytes).

Event availability management.

Currently I read the event slots from the beginning of the array each time. This wastes a few cycles in a loop (sometimes twice!) which could be mitigated by either keeping track of the lowest available slot and starting from there, or by moving the pointers around to the beginning on availability.

The truth, however, is that allocation time costs are minimal and the code complexity of managing more efficient allocation is not warranted for my problem domain. I deal with events on the multi-millisecond scale. Walking the array of events on allocation is on the multi-microsecond scale. Three orders of magnitude difference in time means that it will be a while before this cost is large enough to warrant the extra complexity.

Summary

Dynamic memory in embedded systems is an application killer if not handled carefully. In this little essay I surveyed three very common techniques to rein in the madness (all static, one-time dynamic, nested allocate/deallocate) and introduced another less common one that also serves to rein in the reign of terror (along with outlining a few ways to enhance even that).

There is really no reason to be afraid of dynamic memory in embedded systems. Just be cautious and creative.

 
Read more...

from DigitalWork

Google Adwords değişen yeni ismi ile Google Ads; internetten müşteri arayan birçok işletme tarafından kullanılan bir reklam türüdür. SEO çalışmalarının zamanla hit kazandıracağı bilindiğinden sektöre yeni giren firmalar veya SEO çalışmaları devam ederken müşteri kazanmak isteyen firmalar google reklamları ile arama sonuçlarında en üstte yer almayı isterler. Google reklamları kullanan birçok kişiden duyacağınız şikâyetler şunlardır; para gidiyor arama arama gelmiyor, çok fazla para gidiyor, istediğim yer dışından arama geliyor, alakasız arama geliyor, parayı artırmama rağmen ilk sıraya çıkamıyorum ve benzeri. Peki, Google reklamları işe yaramıyor mu? Kesinlikle yarıyor. Google reklamları ile düşük maliyetler ile istediği bölgelerden, istediği anahtar kelimelerde tıklama alarak çalışan birçok işletme var. Web Tasarımı, Windows ve Mobil Uygulamalar, Arama Motoru Optimizasyonu, Arama Motoru Reklamı ve Dijital Pazarlama konularında danışmanlık hizmetleri veriyoruz.Web tasarım fiyatları hakkında güncel ve firmanıza özel teklif almak için iletişim bilgilerimizden bize ulaşabilirsiniz. Kurumsal web tasarım müşteri beklentilerini günümüz şartlarına uygun ve gelecekte güncellenebilecek biçimde web siteleri oluşturmayı gerektirmektedir. Web tasarım firmaları arasında bu kriterleri sağlayabildiği ölçüde başarılı olurlar ve geniş müşteri kitlelerine hitap edebilirler.

 
Devamını oku...

from DigitalWork

Burun yüzün merkezinde bulunduğundan yüz güzelliği için önemli bir organdır ve bu yüzden estetik burun ameliyatı tüm dünyada en çok yapılan estetik ameliyatlardan biridir. Burun estetiği burundaki şekil bozukluklarını düzeltmeye yarayan bir ameliyattır. Güzel bir görünüm kişinin kendisini zihnen ve ruhen iyi hissetmesine ve kendine güveninin artmasına neden olur. Burun estetiği fiyatları ortalaması ameliyatın türüne göre değişmektedir. Burun estetiği konusunda uzman doktordan yardım almak isteyen kişiler fiyat konusunda da bilgi sahibi olmak istemektedirler. Burun estetiği fiyatları konusunda birçok kriter etkili olmaktadır. Öncelikle ameliyatın zorluk derecesi bu konuda etkin rol oynamaktadır. Bazı durumlarda burun estetiği ameliyatınızın bir kısmını devlet karşılayabilir. Burun estetiği hakkında ayrıntılı bilgiyi web sitemizde bulabilirsiniz. Rinoplasti ameliyatı ile burun küçültülebilir, gerekirse büyütülebilir ve şekil bozukları düzeltilebilir.

 
Devamını oku...

from DigitalWork

My/Pc Teknoloji olarak; başta İstanbul olmak üzere tüm Marmara bölgesine güvenlik kamera sistemleri, bilgisayar sistemleri, ses ve görüntü sistemleri satış, projelendirme ve kurulum hizmetleri vermekteyiz.

Güvenlik Kamera Sistemleri

Web sitemizde güvenlik kamera sistemleri, güvenlik kamera fiyatları, toptan güvenlik kamerası ve güvenlik kamerası ile ilgili birçok konuda bilgiler bulabilirsiniz. Güvenlik kamera ürün portföyümüz analog hd güvenlik kameraları ile başlamakta üst düzey ip kamera sistemleri, lazer kamera sistemleri gibi tüm ev ve işyeri tiplerine hitap eden ürünlerden oluşmaktadır. İç mekan ve dış mekan kameraların yanı sıra araç kamera sistemleri, plaka tanıma sistemleri de ürün portföyümüzdedir. Güvenlik kamera fiyatları ile ilgili ayrıntılı bilgiyi sitemizde bulabilirsiniz.

Alarm Sistemleri

Güvenlik sistemlerinin ayrılmaz bir parçası olan alarm sistemleri ile ilgili her dalda hizmet vermekteyiz. Alarm sistemlerinde hırsız alarm sistemleri ve yangın alarm sistemleri projelerimiz hem lokal hem de izleme merkezine bağlı olarak kurulabilmektedir. Alarm fiyatları ile ilgili ayrıntılı bilgiyi sitemizde bulabilirsiniz.

 
Devamını oku...