Blaise 92 UK Compressed

Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

BLAISE PASCAL MAGAZINE 92

Multi Platform / Object Pascal / Internet / JavaScript / WebAssembly / Pas2Js / Databases


CSS Styles / Progressive Web Apps
Android / IOS / Mac / Windows & Linux

End To End encryption / By Chris Hoffman


VirtualBox Problem / By Detlef Overbeek
Cartoon / By Jerry king
Max Box RSS Feeds of BBC News / By Max Kleiner
Quantum Computing / By Detlef Overbeek
A Combinations counter / By David Dirkse
Hashi Logic Puzzles / By David Dirkse
RegEx / By Michael van Canneyt
Galactic Center Sonification / By M. Russo, A. Santaguida
Code Snippets Find Easter Date / By Detlef Overbeek
Code Snippets Icons on form / By Detlef Overbeek
Web Service Part 1/ By Danny Wind
Lazarus:New edition of the free version of WebCore for Mac / By Mattias Gaertner
USB HID support in kbmMW #2 – 24×7 stability on Win10 / By KimboMadsen
DELPHI Revelations #6 – Delphi Bugs – Generics compiler bug / By KimboMadsen
BLAISE PASCAL MAGAZINE 92
Multi platform /Object Pascal / Internet / JavaScript / WebAssembly / Pas2Js / Databases
CSS Styles / Progressive Web Apps
Android / IOS / Mac / Windows & Linux

ARTICLES
From Your Editor page 4
End To End encryption / By Chris Hoffman page 6
VirtualBox Problem / By Detlef Overbeek page 10
Cartoon / By Jerry king page 11
Max Box RSS Feeds of BBC News / By Max Kleiner page 12
Quantum Computing / By Detlef Overbeek page 16
A Combinations counter / By David Dirkse page 31
Hashi Logic Puzzles / By David Dirkse page 34
RegEx / By Michael van Canneyt page 41
Galactic Center Sonification /By M. Russo, A. Santaguida page 50
Code Snippets Find Easter Date / By Detlef Overbeek page 52
Code Snippets Icons on form / By Detlef Overbeek page 55
Web Service Part 1/ By Danny Wind page 60
Lazarus:New edition of the free version of WebCore for Mac page 70
By Mattias Gaertner
USB HID support in kbmMW #2 – 24×7 stability on Win10 page 75
DELPHI Revelations #6 – Delphi Bugs – Generics compiler bug page 81
By KimboMadsen

Google qubit sculpture


Google's Sycamore quantum computing
chip has 54 qubits in a two-dimensional
array. Running a program on the chip
means changing the configuration of the
qubits. This sculpture symbolizes the
different states of the qubits with
different layers as time passes.

ADVERTISERS
The new LibStick page 5
Super Offer page 30
Subsription +Lazarus Handbook - hardcover page 40
Lazarus Handbook - Pocket (softcover) page 49
Delphi 10.4.2 available page 58
Barnsten Online FMX Power trainingen page 59
Subscription + Library USB Stick page 70
Delphi Company page 83
Componnets4Developers page 85/86

Pascal is an imperative and procedural programming language, which Niklaus Wirth designed (left below) in 1968–69
and published in 1970, as a small, efficient language intended to encourage good programming practices using
structured programming and data structuring. A derivative known as Object Pascal designed for object-oriented
programming was developed in 1985. The language name was chosen to honour the Mathematician, Inventor of the
first calculator: Blaise Pascal (see top right).
Niklaus Wirth Publisher: PRO PASCAL FOUNDATION in collaboration © Stichting Ondersteuning Programmeertaal Pascal - Netherlands

Blaise Pascal Magazine 92 2021 2


Contributors
Stephen Ball Peter Bijlsma -Editor
http://delphiaball.co.uk peter @ blaisepascal.eu
@DelphiABall
Dmitry Boyarintsev Michaël Van Canneyt, Marco Cantù
dmitry.living @ gmail.com michael @ freepascal.org www.marcocantu.com
marco.cantu @ gmail.com
David Dirkse Benno Evers Bruno Fierens
www.davdata.nl b.evers @ everscustomtechnology.nl www.tmssoftware.com
E-mail: David @ davdata.nl bruno.fierens @ tmssoftware.com

Holger Flick
holger @ flixments.com

Primož Gabrijelčič Mattias Gärtner Peter Johnson


primoz @ gabrijelcic.org [email protected] http://delphidabbler.com
delphidabbler @ gmail.com
Max Kleiner John Kuiper Wagner R. Landgraf
www.softwareschule.ch john_kuiper @ kpnmail.nl wagner @ tmssoftware.com
max @ kleiner.com
Vsevolod Leonov Andrea Magni www.andreamagni.eu
[email protected] andrea.magni @ gmail.com
www.andreamagni.eu/wp
Paul Nauta PLM Solution Architect Kim Madsen
CyberNautics www.component4developers.com
paul.nauta @ cybernautics.nl

Boian Mitov Jeremy North


mitov @ mitov.com jeremy.north @ gmail.com

Detlef Overbeek - Editor in Chief Howard Page Clark Heiko Rompel


www.blaisepascal.eu hdpc @ talktalk.net info @ rompelsoft.de
editor @ blaisepascal.eu

Wim Van Ingen Schenau -Editor Peter van der Sman Rik Smit
wisone @ xs4all.nl sman @ prisman.nl rik @ blaisepascal.eu

Bob Swart B.J. Rao Daniele Teti


www.eBob42.com contact @ intricad.com www.danieleteti.it
Bob @ eBob42.com d.teti @ bittime.it

Anton Vogelaar Danny Wind Siegfried Zuhr


ajv @ vogelaar-electronics.com dwind @ delphicompany.nl siegfried @ zuhr.nl

Editor - in - chief
Detlef D. Overbeek, Netherlands Tel.: Mobile: +31 (0)6 21.23.62.68
News and Press Releases email only to [email protected]
Editors Correctors
Peter Bijlsma, W. (Wim) van Ingen Schenau, Rik Smit Howard Page-Clark, Peter Bijlsma
Trademarks All trademarks used are acknowledged as the property of their respective owners.
Caveat Whilst we endeavour to ensure that what is published in the magazine is correct, we cannot accept responsibility for any errors or omissions.
If you notice something which may be incorrect, please contact the Editor and we will publish a correction where relevant.
Subscriptions ( 2019 prices ) Internat. Internat.
excl. VAT incl. 9% VAT Shipment
Printed Issue
€ 155,96 € 250 € 80,00
±60 pages
Electronic Download Issue
€ 64,20 € 70
60 pages
Printed Issue inside Holland (Netherlands)
Member and donator of IKIPEDI W A
€ 240,00 € 70,00 Member of the Royal Dutch Library
±60 pages
Subscriptions can be taken out online at www.blaisepascal.eu or by written order, or by sending an email to [email protected]
Subscriptions can start at any date. All issues published in the calendar year of the subscription will be sent as well.
Subscriptions run 365 days. Subscriptions will not be prolonged without notice. Receipt of payment will be sent by email.
Subscriptions can be paid by sending the payment to:
ABN AMRO Bank Account no. 44 19 60 863 or by credit card or Paypal
Name: Pro Pascal Foundation-Foundation for Supporting the Pascal Programming Language (Stichting Ondersteuning Programeertaal Pascal)
IBAN: NL82 ABNA 0441960863 BIC ABNANL2A VAT no.: 81 42 54 147 (Stichting Programmeertaal Pascal)
Subscription department
Edelstenenbaan 21 / 3402 XA IJsselstein, The Netherlands
Mobile: + 31 (0) 6 21.23.62.68 [email protected]
Copyright notice
All material published in Blaise Pascal is copyright © SOPP Stichting Ondersteuning Programeertaal Pascal unless otherwise noted and may not be copied, distributed
or republished without written permission. Authors agree that code associated with their articles will be made available to subscribers after publication by placing it
on the website of the PGG for download, and that articles and code will be placed on distributable data storage media. Use of program listings by subscribers for
research and study purposes is allowed, but not for commercial purposes. Commercial use of program listings and code is prohibited without the written permission
of the author.

Blaise Pascal Magazine 92 2021 3


From your editor
Dear Reader, Delphi came wit and update: 10.4.2 Sydney. In
here is our February issue of this year. the next issue I will dive into that version and
Especially in this issue is an article about the write an article about updating without loosing
Easter holidays all your installed components. They will soon
and what influence they actually have on many come with a new version of the Community
holidays. Just for fun and out of curiosity. edition.
I never understood all these changes each
year again and therefore the funny behaviour Components4Developers has announced its
of the planned dates...always changing. Next new version 5.14 and Kim Madsen wrote an
year even on my birthday… article to secure your USB HID’ s, which could
become necessary, and of course there is a lot
On the cover you find a beautiful cube of other articles that might find your interest.
constructed by google for quantum purposes.
It looks like All new things happening and this beautiful
an artificial diamond of science. The quantum weather makes me feel like spring is in the air.
era has definitively made its entrance into our Refreshing, it already smells like the first
world. flowers.
I suppose the actual large-scale application of
it will take a few more “days”. The article I Lets enjoy spring!
wrote about this is actually to make you aware
of the becoming more and more reliable of Detlef
that science.
But it is already in use by many experiments
and BMW is making progress to solve the
problem of buying parts the cheapest way,
finding still the nearest supplier to Europe and
best product.
Since they are using a huge number of parts
this is monstrous a task that a normal
computer can not solve in a short period of
time.

I have a lot of great news to announce:


Lazarus has released its newest stable
version: see page 70.
The final arrival of the TMS WebCore for free
under the macOS Version Big Sure is
described.
One of the members of the Lazarus team
(Martin Friebe) has been able to create a
special WebForm for Lazarus that will enable
you to create your webforms and applications
with “What you see is what you get:
WYSIWIG”.
We will go on developing that during the year
and I will update you about this fantastic new
feture constantly. But for now it is still under
construction. There is more to come.

Blaise Pascal Magazine 93 2021 4


ADVERTISEMENT

L I B R A R Y 2 0 2 0

89
90
87
88
86
85 51 52 53
84 50 54
55 49 26 27 28
83 29 25
48 56
81 30 24
82 47 9 10 11 57
12 31
80 46 23 8 1
2 13 32 58
78 22 7 3
79 45 14 33
21 4 59
77 44 6
20 5 15 34
75 60
76 43 19 16 35
18 17 61
73 42 36
74
41 37 62
72 40 39 38
71 69 63
70 67 64
68 66 65

ALL CODE ABOUT THE USE

BLAISE PASCAL MAGAZINE


ALL ISSUES IN ONE FILE

Editor in Chief: Detlef Overbeek


BLAISE PASCAL MAGAZINE Edelstenenbaan 21 3402 XA
IJsselstein Netherlands
BLAISE PASCAL MAGAZINE

procedure procedure
var var
begin begin
for I := 1 to 9 do for I := 1 to 9 do
begin Prof Dr.Wirth, Creator of Pascal Programming language begin
... ...
end end
end; end;
Prof Dr.Wirth, Creator of Pascal Programming language Blaise Pascal, Mathematician
[email protected] Prof Dr.Wirth, Creator of Pascal Programming language Blaise Pascal, Mathematician

The new LibStick (1)


(on USB Card - 90 Issues)
€ 60,-- ex vat / including shipment
END-TO-END ENCRYPTION PAGE 1/4
BY CHRIS HOFFMAN

Your devices are using various forms of


encryption all the time.

For example, when you access your online


banking website—or any website using HTTPS,
which is most websites these days—the
communications between you and that website
are encrypted so that your network operator,
internet service provider, and anyone else
snooping on your traffic can’t see your banking
password and financial details.

Wi-Fi uses encryption, too.


That’s why your neighbors can’t see everything
you’re doing on your Wi-Fi network—assuming
that you use a modern Wi-Fi security
standard that hasn’t been cracked,
anyway.
Encryption is also used to secure
This article was taken out of the following your data. Modern devices such as
address: iPhones, Android phones, iPads,
https://www.howtogeek.com/711656/ Macs, Chromebooks, and Linux systems (but
what-is-end-to-end-encryption-
not all Windows PCs) store their data on your
and-why-does-it-matter/
local devices in Encryption “in Transit” and “at
INTRODUCTION Rest”: Who Holds the Keys?
End-to-end encryption (E2EE) ensures that So encryption is everywhere, and that’s great.
your data is encrypted (kept secret) until it But when you’re talking about communicating
reaches an intended recipient. Whether you’re privately or storing data securely, the question
talking about end-to-end encrypted is: Who holds the keys?
messaging, email, file storage, or anything For example, let’s think about your Google
else, this ensures that no one in the middle account. Is your Google data—your Gmail
can see your private data. emails, Google Calendar events, Google Drive
In other words: If a chat app offers end-to- files, search history, and other data—secured
end encryption, for example, only you and the with encryption?
person you’re chatting with will be able to
read the contents of your messages. In this Well, yes. In some ways.
scenario, not even the company operating the
chat app can see what you’re saying. Google uses encryption to secure data “in
transit.” When you access your Gmail account,
ENCRYPTION BASICS
First, let’s start with the basics of encryption. for example, Google connects via secure
Encryption is a way of scrambling (encrypting) HTTPS.
data so that it can’t be read by everyone. This ensures that no one else can snoop on the
Only the people who can unscramble communication going on between your device
(decrypt) the information can see its contents. and Google’s servers.
If someone doesn’t have the decryption key, Your internet service provider, network
they won’t be able to unscramble the data and operator, people within range of your Wi-Fi
view the information. network, and any other devices between you
and Google’s servers can’t see the contents of
(This is how it’s supposed to work, of your emails or intercept your Google account
course. Some encryption systems have password.
security flaws and other weaknesses.)

BLAISE PASCAL MAGAZINE 92 2021 6


END-TO-END ENCRYPTION PAGE 2/4
Google also uses encryption to secure data So yes, those systems may protect your data.
“at rest.” Before the data is saved to disk on But that’s not encryption protecting your
Google’s servers, it is encrypted. data from Google.
Even if someone pulls off a heist, sneaking It’s just Google’s policies protecting your
into Google’s data center and stealing some data.
hard drives, they wouldn’t be able to read the Don’t get the impression that this is all about
data on those drives. Google.
It’s not—not at all.
Both encryption in transit and at rest are Even Apple, so beloved for its privacy stances,
important, of course. They’re good for does not end-to-end encrypt iCloud backups.
security and privacy. In other words:
It’s much better than sending and storing the Apple keeps keys that it can use to decrypt
data unencrypted! everything you upload in an iCloud backup.
But here’s the question:
Who holds the key that can decrypt this data? HOW END-TO-END ENCRYPTION WORKS
The answer is Google. Now, let’s talk chat apps.
Google holds the keys. For example: Facebook Messenger. When you
contact someone on Facebook Messenger,
Since Google holds the keys, this means that the messages are encrypted in transit between
Google is capable of seeing your you and Facebook, and between Facebook and
data—emails, documents, files, calendar the other person.
events, and everything else. The stored message log is encrypted at rest by
Facebook before it’s stored on Facebook’s
If a rogue Google employee wanted to snoop servers.
on your data—and yes, its But Facebook has a key.
happened—encryption wouldn’t stop them. Facebook itself can see the contents of your
messages.
If a hacker somehow compromised Google’s
systems and private keys (admittedly a tall THE SOLUTION IS END-TO-END
order), they would be able to read everyone’s ENCRYPTION.
data. With end-to-end encryption, the provider in
the middle—whoever you replace Google or
If Google was required to turn over data to a Facebook with, in these examples—will not be
government, Google would be able to access able to see the contents of your messages.
your data and hand it over.
They do not hold a key that unlocks your
Other systems may protect your data, of private data. Only you and the person you’re
course. Google says that it has implemented communicating with hold the key to access
better protections against rogue engineers that data.
accessing data. Your messages are truly private, and only you
Google is clearly very serious about keeping and the people you’re talking to can see
its systems secure from hackers. them—not the company in the middle.
Google has even been pushing back on data
requests in Hong Kong, for example.

BLAISE PASCAL
Blaise Pascal MAGAZINE
Magazine 92 2021
91 2021 7
END-TO-END ENCRYPTION PAGE 3/4

WHY IT MATTERS In a sense, this is arguably “end-to-end”


End-to-end encryption offers much more encryption—except that you’re on both ends.
privacy. For example, when you have a
conversation over an end-to-end encrypted No one else—not even the company that
chat service like Signal, you know that only you makes the password manager—holds a key
and the person you’re talking to can view the that lets them decrypt your private data.
contents of your communications.
You can use the password manager without
However, when you have a conversation over a giving the password manager company’s
messaging app that isn’t end-to-end employees access to all your online banking
encrypted—like Facebook Messenger—you passwords.
know that the company sitting in the middle of
the conversation can see the contents of your ANOTHER GOOD EXAMPLE:
communications. If a file storage service is end-to-end
encrypted, that means that the file storage
IT’S NOT JUST ABOUT CHAT APPS. provider can’t see the contents of your files.
For example, email can be end-to-end
encrypted, but it requires configuring PGP If you want to store or sync sensitive files with
encryption or using a service with that built in, a cloud service—for example, tax returns that
like ProtonMail. have your social security number and other
Very few people use end-to-end encrypted sensitive details—encrypted file storage
email. services are a more secure way to do that than
End-to-end encryption gives you confidence just dumping them in a traditional cloud
when communicating about and storing storage service such as Dropbox, Google
sensitive information, whether it’s financial Drive, or Microsoft OneDrive.
details, medical conditions, business
documents, legal proceedings, or just intimate
personal conversations you don’t want anyone ONE DOWNSIDE:
else having access to. Don’t Forget Your Password!
There’s one big downside with end-to-end
END-TO-END ENCRYPTION ISN’T JUST ABOUT encryption for the average person:
COMMUNICATIONS If you lose your decryption key, you lose
access to your data.
End-to-end encryption was traditionally a term Some services may offer recovery keys that
used to describe secure communications you can store, but if you forget your password
between different people. and lose those recovery keys, you can no
However, the term is also commonly applied to longer decrypt your data.
other services where only you hold the key that
can decrypt your data.with a secret only you That’s one big reason that companies like
know. Apple, for example, might not want to end-to-
end encrypt iCloud backups.
For example, password managers
such as 1Password, BitWarden, Since Apple holds the encryption key, it can let
LastPass, and Dashlane are end-to- you reset your password and give you access
end encrypted. to your data again.
The company can’t rummage through
your password vault—your passwords
are secured

BLAISE PASCAL
Blaise Pascal MAGAZINE
Magazine 92 2021
91 2021 8
END-TO-END ENCRYPTION PAGE 4/4

This is a consequence of the fact that Apple However, if a ProtonMail user emails someone
holds the encryption key and can, from a using a different service, they’ll need to set up
technical perspective, do whatever it likes PGP to use encryption. (Note that encrypted
with your data. email doesn’t encrypt everything: While the
If Apple didn’t hold the encryption key for you, message body is encrypted, for example,
you wouldn’t be able to recover your data. subject lines aren’t.)
Imagine if, every time someone forgets a
password to one of their accounts, their data RELATED: What Is Signal, and Why Is Everyone
in that account would be wiped out and Using It?
become inaccessible.
End-to-end encryption is important.
Forget your Gmail password? Google would
have to erase all your Gmails to give you your If you’re going to have a private
account back. That’s what would happen if conversation or send sensitive
end-to-end encryption was used everywhere. information, don’t you want to make
sure that only you and the person
Examples of Services That Are End-to-End you’re talking to can see your
Encrypted messages?

Here are some basic communication services


that offer end-to-end encryption.
This isn’t an exhaustive list—it’s just a short
introduction.

For chat apps, Signal offers end-to-end


encryption for everyone by default.
Apple iMessage offers end-to-end encryption,
but Apple gets a copy of your messages with
the default iCloud backup settings.

WhatsApp says that every conversation is end-


to-end encrypted,

Some other apps offer end-to-end encryption


as an optional feature that you have to enable
manually, including Telegram and Facebook
Messenger.
For end-to-end encrypted email, you can use
PGP—however, it’s complicated to set up.

Thunderbird now has integrated PGP support.

There are encrypted email services like


ProtonMail and Tutanota that store your emails
on their servers with encryption and make it
possible to more easily send encrypted emails.
For example, if one ProtonMail user emails
another ProtonMail user, the message is
automatically sent encrypted so that no one
else can see its contents.

BLAISE PASCAL
Blaise Pascal MAGAZINE
Magazine 92 2021
91 2021 9
VIRTUAL BOX PROBLEM

Since I build a new computer having a AMD Ryzen CPU


and installed Windows on it I found it very
disappointing my VirtualBox doesn’t work on that any
more.
I found out it actually it’s very simple to be solved:
in the settings of the BIOS go to Advanced CPU
Settings and than it will come up with the SVM Mode:
this is set standard to disable, but it needs to be
enabled. Problem gone.
From our Technical advisor: Cartoons from Jerry King

Blaise Pascal Magazine 92 2021 11


RSS FEEDS of
BBC NEWS Page1/7 maXbox
maXbox of course software libraries exist to read the
Author: Max Kleiner RSS format and present RSS headlines on
"Time goes, you say?
webpages and other online applications like in
Ah, no! alas, time stays, we go." our script example with SimpleRSS. So you can
feed a memo or text component in your form.

In the XML baseline you see this:


At its core, RSS refers to simple text files <? xml version ="1.0 " ?>
- <rdf:RDF xmlns:rdf=
(XML/RDF) with more or less important,
"http://www.w3.org/1999/02/22-rdf-syntax-ns#“
updated information - news pieces, articles, xmlns="http://purl.org/rss/1.0/">
weather info, opinion mining that sort of - <!-- XML Generated by SimpleRSS
thing. http://simplerss.sourceforge.net at Sat, 15 Jan 2021 11:43:18 -->
- <channel xmlns="" rdf:about="">
In the following I want to show this topic <title>Title Required</title>
thing with the BBC-News feeder. News feeds <link>Link Required</link>
<description>Description Required</description>
allow you to see when websites have added
- <items>
new content. You can get the latest <rdf:Seq />
headlines and video in one place, as soon as </items>
it’s published, without having to visit the </channel>
</rdf:RDF>
websites you have taken the feed from.

BBC News as our example provides feeds for This structure is a convention and suitable for a
both the desktop website as well as for our record:
type
mobile site and the most popular feeds are TRSSItem2 = record
listed here: FPubDate: TDate;
https://www.bbc.co.uk/news/10628494 FLink: string;
FTitle: string;
FDescription: string;
end;
First we define the URL to get the content
from:
Const
RSS_NewsFeed = 'http://feeds.bbci.co.uk/news/world/rss.xml';

RSS is an XML based document format for The FPubDate made me a bit upset because I
syndicating news and other timely news-like had to convert it in TRFC822DateTime Format .
information. This specified date-time value, while technically
It provides headlines, URLs to the source valid, is likely to cause interoperability issues.
document and brief description information in
an easy to understand and use format. The value specified must meet the Date and
RSS based “News Readers” and “News Time specifications as defined by RFC822, with
Aggregators” allow the display of RSS the exception that the year should be expressed
headlines on workstation desktops. as four digits.
Users of RSS content use apps called feed The syntax is like (all single spaced and no
'readers' or 'aggregators' (newer versions of comments):
Web browsers offer built in support for RSS
feeds): a user subscribes to a feed by entering <pubDate>Wed, 02 Oct 2020 08:00:00 EST</pubDate>
<pubDate>Wed, 02 Oct 2020 13:00:00 GMT</pubDate>
the link of the RSS feed into their RSS feed
reader;

Blaise Pascal Magazine 92 2021 12


RSS FEEDS of
BBC NEWS Page2/7 maXbox
There, of course, is knowledge
on the web, but in my case I use //RSS Script Feed Snippet:
with TSimpleRSS.create(self) do begin
a component with specific objects XMLType:= xtRDFrss;
to adapt. But the good news is the IndyHTTP:= TIdHTTP.create(self);
core code is straight and simple: LoadFromHTTP(RSS_NewsFeed);
//LoadFromHTTP(Climatefeed);
writeln('RSSVersion: '+Version)
writeln('SimpleRSSVersion: '+SimpleRSSVersion)
for it:= 0 to items.count-1 do
writeln(itoa(it)+': '+Items[it].title+':
'+items[it].pubdate.getdatetime);
end;

Blaise Pascal Magazine 92 2021 13


RSS FEEDS of
BBC NEWS Page3/7 maXbox
Items are sticked together in
the class TRSSItems and inherits The http provider is by default Indy and we
from TOwnedCollection. can load the feeds as a stream with the
These CollectionItem objects in turn LoadFromHTTP() Method. The RSS Version is
contain their own published child based with 2. These modern supplied RSS
property which descends from documents use the RSS 2.0 format. Each
TCollection and contain their own RSS item links to the html/web documents
TCollectionItem descendant - so a nested are described. Additional technical
TCollection/TCollectionItem scenario. information is available from the following
non-US Government website like BBC News.
The XMLType is based on the RDF proposal.

Blaise Pascal Magazine 92 2021 14


RSS FEEDS of
BBC NEWS Page4/7 maXbox
RDF is a kind of sematic web.
The Semantic Web enables And the output as iterated items from
devices to seek out knowledge RSS-Reader will be (3-day forecast):
distributed throughout the Web, RSSFeedVersion: 2.0
mesh or mix it, and then take action SimpleRSSVersion: ver 0.4 (BlueHippo) Release 1
0: Today: Light Snow, Min Temperature:-5°C (23°F)
based on it. Simply said: Max Temperature: 0°C (32°F): Sat, 15 Jan 2021 10:37:30 Z
The Resource Description Framework 1: Saturday:Light Cloud,Min Temperature:-3°C (27°F)
(RDF) is the W3C standard for encoding Max Temperature:-1°C (30°F):Sat,15 Jan 2021 10:37:30 Z
2: Sunday:Sleet Showers,Min Temperature:-1°C (31°F)
knowledge. After running the script you get Max Temperature:3°C (38°F):Sat,15 Jan 2021 10:37:30 Z
this similar output:
29: Life in a Day: Kevin Macdonald says By the way, weather data have their own
film 'reinforces everyones similarities': format, which is called NWS, and is not to be
Mon, 01 Feb 2021 00:00:57 GMT
confused with RSS and cannot be read by RSS
link: readers and aggregators. These files present
https://www.bbc.co.uk/news/ more detailed information than the RSS feeds
entertainment-arts-55861945 in strings friendly for parsing. Both the RSS
descript: and XML feeds offer URLs to icon images.
Kevin Macdonalds documentary features
personal videos from across the world Conclusion:
- all shot on the same day. Really Simple Syndication (RSS) is a family of web
formats used to publish frequently updated digital
rssitem.title content. Most commonly used to update news
BBC News - World articles, weather reports or traffic services and
rssitem.link other content that changes quickly, RSS feeds may
https://www.bbc.co.uk/news/ also include audio files (PodCasts) or even video
files (VodCasts). SimpleRSS components provides
To build your own provider for example with methods for accessing, importing, exporting and
TLS1.3 or to link with your own working with RSS, RDF, Atom & iTunes Feeds. This
XML-Parser/DOM vendor you can use the library is free software; you can redistribute it
LoadFromStream() method. and/or modify it under the terms of the GNU Lesser
Now the code block for a weather service with General Public License.
HTTPS and LoadFromStream():
Const Weatherfeed5Bern=
'https://weather-broker-cdn.api.bbci.co.uk/en/forecast/rss/3day/2661552';

function GetBlogStream8(const S_API, pData: string;


astrm: TStringStream): TStringStream; Next time I show an an online translation service
begin
HttpGET(S_API, astrm) //maps HTTPS from WinInet_HttpGet
with sentiment analysis:
result:= astrm; Trump's false election fraud claims face a dead end
end; Trumps falsche Wahlbetrugsansprüche stehen vor
einer Sackgasse
strm:= TStringStream.create(''); Trump's valse verkiezingsfraudeclaims lopen dood
strm:= GetBlogStream8(WeatherFeed5Bern,'', strm); Les fausses allégations de fraude électorale de
Trump font face à une impasse
with TSimpleRSS.create(self) do begin
XMLType:= xtRDFrss; // bbcnews: xtRDFrss;
//( xtRDFrss, xtRSSrss, xtAtomrss, xtiTunesrss )'); Ref Script & Component:
//GenerateXML; http://www.softwareschule.ch/
LoadFromStream((strm)); examples/bbcnews.txt
SaveToFile('C:\maXbox\Lazarus\rssbbctest.xml'); http://simplerss.sourceforge.net
writeln('RSSFeedVersion: '+Version) script: 1017_XmlDocRssParser.pas
writeln('SimpleRSSVersion: '+SimpleRSSVersion) Doc:
for it:= 0 to items.count-1 do https://maxbox4.wordpress.com
writeln(itoa(it)+': '+Items[it].title+': http://feedvalidator.org/docs/rss2.html
'+items[it].pubdate.getdatetime); http://web.resource.org/rss/1.0/modules/
strm.Free; content/
end;

Blaise Pascal Magazine 92 2021 15


Quantum Development: Page 1 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet

In this article we summon the latest PART1: QUANTUM VOLUME:


developments of Quantum computing. OVERVIEW OF QUANTIFYING
After having written several articles Of course all these giants will try to be the first
(Issue 62 – Quantum computing, Issue 63 - Part2 Building or the greatest and time has shown that all of
a quantum computer, 66 Majorana, the new solution for them win - now and then.
QantumBits, Issue 73/74 Quantum Internet) I write
Up to this moment there are the well-known
about a new development: larger numbers of names that work on Quantum Computers:
QBits and increased certainty for computations.
QUANTUM COMPUTING u IBM
Quantum computing is the use of is developing a Software language tool for
quantum phenomena such as development: Qiskit
superposition and entanglement to https://qiskit.org/
perform computation. Computers that
perform quantum computations are known v Google
An open source framework for programming
as quantum computers.
quantum computers: Cirq
Cirq is a Python software library for writing,
Quantum computers are believed to be
manipulating, and optimizing quantum
able to solve certain computational
circuits, and then running them on quantum
problems, such as integer factorization
computers and quantum simulators.
(which underlies RSA encryption ), https://quantumai.google/cirq
substantially faster than classical
computers. w Microsoft
The study of quantum computing is a The Quantum Development Kit for Q#
subfield of quantum information science. and Azure Quantum.
The Quantum Development Kit is the
Quantum computing began in the early development kit for Q#, quantum -
1980s, when physicist Paul Benioff focused programming language and
proposed a quantum mechanical model of Azure Quantum, quantum cloud platform.
the Turing machine. Richard Feynman and Build and run Q# programs on quantum
Yuri Manin later suggested that a quantum hardware or formulate solutions that
computer had the potential to simulate execute optimization.
things that a classical computer could not.
x Honeywell
In 1994, Peter Shor developed a quantum uses Microsoft’s Quantum Development
algorithm for factoring integers that had Kit for Q# and Azure Quantum.
the potential to decrypt RSA-encrypted
communications.
Despite ongoing experimental progress
since the late 1990s, most researchers
believe that "fault-tolerant quantum
computing is still a rather distant dream.
In recent years, investment into quantum
computing research has increased in both
the public and private sector.

The article was gathered from various articles about Quantum


Computing, News Items, WikiPedia explanations a full list of Figure 1: The Sycamore chip is composed of 54 qubits,
used information is shown at the end of the article. each made of superconducting loops.Credit: Erik Lucero.

Blaise Pascal Magazine 92 2021 16


Quantum Development: Explanation Page 2 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet

QBit However, whereas the state of a bit can


W A
In quantum computing, a qubit or
IKIPEDI
only be either 0 or 1, the general state of a
quantum bit (sometimes qbit is the basic qubit according to quantum mechanics can
unit of quantum information - the quantum be a coherent superposition of both.
version of the classical binary bit physically
realized with a two-state device. Moreover, whereas a measurement of a
classical bit would not disturb its state,
A qubit is a two-state (or two-level) a measurement of a qubit would
quantum-mechanical system, one of the destroy its coherence and irrevocably
simplest quantum systems displaying the disturb the superposition state. It is
peculiarity of quantum mechanics. possible to fully encode one bit in one
qubit.
Examples include: the spin of the electron in However, a qubit can hold more
which the two levels can be taken as spin up information, e.g. up to two bits using
and spin down; or the polarization of a superdense coding.
single photon in which the two states can be
taken to be the vertical polarization and the In quantum information theory,
horizontal polarization. superdense coding (or dense coding)
is a quantum communication protocol to
In a classical system, a bit would have transmit two classical bits of information
to be in one state or the other. (i.e., either 00, 01, 10 or 11) from a sender
However, quantum mechanics allows the (often called Alice) to a receiver (often called
qubit to be in a coherent superposition of Bob), by sending only one qubit from Alice to
both states simultaneously, a property Bob, under the assumption of Alice and Bob
which is fundamental to quantum mechanics pre-sharing an entangled state.
and quantum computing.
By performing one of four quantum gate
BINARY DIGIT operations on the (entangled) qubit she
A binary digit, characterized as 0 or 1, possesses, Alice can pre-arrange the
W A is used to represent information in
IKIPEDI
measurement Bob makes.
classical computers.
When averaged over both of its states (0,1), After receiving Alice's qubit, operating on the
a binary digit can represent up to one bit of pair and measuring both, Bob has two
Shannon information, where a bit is the classical bits of information.
basic unit of information.
If Alice and Bob do not already share
However, in this article, the word bit is entanglement before the protocol begins,
synonymous with a binary digit. then it is impossible to send two classical
bits using 1 qubit, as this would violate
In classical computer technologies, Holevo's theorem it is an important
a processed bit is implemented by one of limitative theorem in quantum computing,
two levels of low DC voltage, and whilst an interdisciplinary field of physics and
switching from one of these two levels to the computer science.
other, a so-called forbidden zone must be It is sometimes called Holevo's bound, since
passed as fast as possible, as electrical it establishes an upper bound to the amount
voltage cannot change from one level to of information that can be known about a
another instantaneously. quantum state (accessible information).

There are two possible outcomes for the Superdense coding is the underlying
measurement of a qubit - usually taken to principle of secure quantum secret
have the value "0" and "1", like a bit or coding.
binary digit. The necessity of having both qubits to
decode the information being sent eliminates
the risk of eavesdroppers intercepting
messages.

Blaise Pascal Magazine 92 2021 17


Quantum Development: Explanation Page 3/14
Larger volumes, better results, Hot Qbits / Quantum Internet

It can be thought of as the opposite of Notably, quantum computers are believed to


quantum teleportation, in which one be able to quickly solve certain problems that
transfers one qubit from Alice to Bob by no classical computer could solve in any
communicating two classical bits, as long
feasible amount of time - a feat known as
as Alice and Bob have a pre-shared Bell
QUANTUM SUPREMACY.
pair.
The study of the computational complexity of
For a system of n components, a complete problems with respect to quantum computers
description of its state in classical physics is known as quantum complexity theory.
requires only n bits, whereas in quantum
physics it requires 2n complex numbers.

TRANSMONS, ION TRAPS AND


TOPOLOGICAL QUANTUM COMPUTERS.
Progress towards building a physical quantum
computer focuses on technologies such as
transmons, ion traps and topological quantum
computers, which aim to create high-quality
qubits.

These qubits may be designed differently,


depending on the full quantum computer's
computing model, whether quantum logic
gates, quantum annealing, or adiabatic
quantum computation. Figure 2:

There are currently a number of significant


obstacles in the way of constructing useful
quantum computers.
In particular, it is difficult to maintain the
quantum states of qubits as they suffer from
quantum decoherence and state fidelity.
Quantum computers therefore require error
correction.

Any computational problem that can be solved


by a classical computer can also be solved by
a quantum computer.
Conversely, any problem that can be solved by
a quantum computer can also be solved by a
classical computer, at least in principle given
enough time. In other words, quantum
computers obey the Church–Turing thesis.

While this means that quantum computers


provide no additional advantages over
classical computers in terms of computability,
quantum algorithms for certain problems have
significantly lower time complexities than
corresponding known classical algorithms.

Blaise Pascal Magazine 92 2021 18


Quantum Development: IBM Page 4 /14
Larger volumes, better results, Hot Qbits / Quantum Internet

IBM promises 100x faster quantum computers


through new software foundations.
Big Blue's open-source software efforts span the
basics of quantum computing to higher-level
jobs like AI and molecular simulations.

IBM expects it will increase performance of its


complex machines by a factor of 100, a
development that builds on Big Blue's progress
in making the advanced computing hardware.

Much of the software will be written using open-


source technology that outsiders can contribute
to and benefit from, IBM mentions that adding
the improvements will lead to a 100x speedup.

IBM's planned quantum computing software


Figure 3: An IBM quantum computer where you can see releases are part of an effort to hide away as
the processor placed in the container at the bottom.
Stephen Shankland/CNET
much of the quantum computing complexity as
possible for ordinary folks.
IBM Getting a quantum computer to do useful work
says that software development is best done today is intricate, even with specialists like
collaboratively, since open-source approaches Zapata Computing and Cambridge Quantum
are based around the understanding that an Computing.
ecosystem of different human needs drives
the best outcomes - and quantum computing The software speedups could mean jobs that
is no different. took months on a classical computer can be
They expect developers to work in each of finished in a few hours. That would bring
three key segments laying the groundwork for quantum computers closer to fulfilling their
those working higher up in the stack. potential of solving problems out of reach of
• At the lowest level, quantum kernel classical machines.
developers are creating high-performance
quantum circuits with timing and QUANTUM CONNECTION
pulse-level controls. IBM is among competitors like Google, Intel,
• Quantum algorithm developers rely on Microsoft, IonQ, Rigetti Computing and
these circuits to develop groundbreaking Honeywell racing for leadership in quantum
quantum algorithms that might provide an computing.
advantage over present-day classical
computing solutions. Where classical computing technology is
• Finally, quantum model developers apply relatively settled, quantum computers employ
these algorithms to real-world use cases in a wide variety of approaches. It's not yet clear
order to develop quantum models for which among them will prevail as the
chemistry, physics, biology, machine technology fledges from research labs into real-
learning, optimization, or even finance. world use.
Workloads with both quantum and classical
components is not constrained by origin or the At the heart of quantum computers are qubits*,
nature of integration, and a hybrid cloud will data storage and processing elements that can
allow these workloads to run everywhere that store a combination of one and zero. Ú
our cloud native systems run today and in the
future.IBM is developing a Software language
tool for development: Qiskit

Blaise Pascal Magazine 92 2021 19


Quantum Development: IBM Page 5 /14
Larger volumes, better results, Hot Qbits / Quantum Internet

Quantum computers connect qubits through a to the qubits. With a specific sequence of
quantum physics phenomenon called gates, called a circuit, quantum computers can
entanglement that lets a machine encompass perform computations for particular tasks like
an enormous number of possible solutions to simulating molecules or optimizing parts
a problem. purchases, which BMW is trying on its complex
supply chain.
Operating a quantum computer involves
applying a series of manipulations called gates

Blaise Pascal Magazine 92 2021 20


Quantum Development: IBM Page 6/14
Larger volumes, better results, Hot Qbits / Quantum Internet

Figure 4: The IBM roadmap

Blaise Pascal Magazine 92 2021 21


Quantum Development: GOOGLE Page 7 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet

O
n 23 October 2019, Google AI , GOOGLE
in partnership with the after some troubles a new era of computing
U.S. National Aeronautics and Space seems to be here.
Administration (NASA), claimed to have Researchers at Google claim their quantum
performed a quantum computation that is computer has solved a problem that would
infeasible on any classical computer. take even the very best conventional machine
thousands of years to crack.
There are several models of quantum
computers (or rather, quantum computing The milestone, known as QUANTUM
systems), including the quantum circuit model, SUPREMACY, represents a long-sought stride
quantum Turing machine, adiabatic* quantum towards realising the immense promise of
computer, *(relating to or denoting a process quantum computers, devices that exploit the
or condition in which heat does not enter or strange properties of quantum physics to
leave the system concerned) speed up certain calculations.
It shows that quantum computing is really hard
but not impossible.

The paper demonstrates that a quantum


processor consisting of 54 superconducting
quantum bits, or qubits, was able to perform a
random sampling calculation – essentially
verifying that a set of numbers is randomly
distributed – exponentially faster than any
standard computer.

Google’s SYCAMORE device did it in just 3


minutes and 20 seconds, although one of the
Figure 5: qubits had to be turned off as it wasn’t working
properly. It stands by the claims that the
calculation would have taken IBM’s Summit,

Figure 6:

Blaise Pascal Magazine 92 2021 22


Quantum Development: GOOGLE Page 8 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet
It doesn’t mean quantum computers are
ready to tackle real-world problems though –
that remains decades away. Instead, it is a
proof of concept.

We are looking forward to the next milestone:


proof that we have sufficient control over the
qubits that we can overcome the small errors
they accumulate during calculations.

We are now in a phase we call Noisy


Intermediate - Scale Quantum computing,
or NISQ.
Figure 6: TO GET BEYOND THAT, WE NEED TO START
IBM has already pushed back on that claim, DOING ERROR CORRECTION.
insisting that with some clever classical The architecture of the Google chip is already
programming, its machine can solve the optimised for that.
problem in 2.5 days.
Indeed, IBM, which has its own
53-qubit quantum computer,
prefers a higher threshold for
quantum supremacy, which
explains its argument that
Google has not yet reached
the milestone.

But such caveats should not


detract too much from
Google’s achievement.
There wil always be clever
ways to tweak classical
algorithms, but until Google
Figure 7:
has had a chance to digest the methodology
IBM are proposing, it is hard to judge.

We will see more of this sort of back and forth


when it comes to claims of quantum
supremacy.

Even if you accept IBM’s claims at face value,


Google’s quantum computer is still a big step
forward, says Ciarán Gilligan-Lee at University
College London.
Figure 8:

“IBM is claiming that, even when running the


world’s largest computer for two and half days,
and running petabytes of memory, they can
simulate what the quantum chip does in 200
seconds. When you put it into context, it is still
a pretty impressive achievement.”

Blaise Pascal Magazine 92 2021 23


Quantum Development: Honeywell Page 9 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet

Figure 9: Honeywell

QUANTUM VOLUME: Other factors include errors present in the


OVERVIEW OF QUANTIFYING quantum operations used for calculations, how
Measuring the capabilities of a quantum connected the qubits within the system are to
computer requires a measurement that can other qubits, cross-talk between those qubits
summarize this complex operation. and the efficiency of the compiler running the
Quantum Volume is a metric that can be operations.
used to express the effectiveness of a given
quantum computer. Unlike the volume of a cube, Quantum Volume
The various quantum hardware platforms measures are not computed by simple
available today have a wide array of multiplication, but require a complicated set of
specifications, making it difficult to statistical tests.
differentiate the machines’ overall
capabilities. Here are the main components:

IBM developed a simple measurement like u Number of qubits


Quantum Volume, which is absolutely The simplest measure to quantify is the
necessary. The larger the quantum volume, number of physical qubits in the quantum
the more complex problems you can solve. computer.
When Honeywell releasd its quantum In traditional computers, the bits are in a
computer by mid-2020 its quantum volume state of “0” or “1.”
was 128. To compare for that moment the However, in quantum computers, the
maximum was about 50. qubits can be in the states “0” or “1” or
both at the same time.
HOW QUANTUM VOLUME IS CALCULATED
Quite a large variety of factors and complex That’s a property of quantum physics called
calculations determines the Quantum Volume. superposition.
The number of qubits is important because
One factor is the number of qubits in a they are a basic element of the computer.
quantum computer. Qubits are the computing But to determine the quantum computers
bits that take advantage of quantum physics. full capability, two more factors must be
considered.

Blaise Pascal Magazine 92 2021 24


Quantum Development: Honeywell Page 10 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet

v Error rates As the Quantum Volume increases, the ability


When it comes to error rates, like golf, to use quantum computers to solve really
the lower the number the better. complicated problems will accelerate.
The limiting error rate of the system “It means that there will be a lot more things
quantifies how often it gets the wrong that we can do with quantum computing that
answer. we thought were further out on the horizon,”
Error rates encompass systematic errors said analyst Smith-Goodson.
that might not show up in a single qubit.
That comprehensive error rate is important
in determining how often calculations will
be accurate.

w Connectivity of qubits
Lastly, connectivity is a key factor in
determining quantum volume.
Connectivity defines which pairs of qubits
can be entangled in a quantum computer.
Some hardware can directly apply
entanglement operations to any two
physical qubits in the system.
Other hardware can only operate on qubit
pairs that are physically located next to
each other.
When qubits are fully connected, they can
execute algorithms more efficiently,
solving problems with fewer steps and
taking full advantage of the qubits’ limited
coherence time.

Figure 10:

Blaise Pascal Magazine 92 2021 25


Quantum Development: Honeywell Page 11 /14
Larger volumes, better results, Hot Qbits / Quantum Internet

HONEYWELL ACHIEVED A QUANTUM VOLUME The figure of the plot at the bottom-left
OF 128 ON THEIR QUANTUM COMPUTER IN column shows the heavy outcomes for
LATE SEPTEMBER 2020. Honeywell Quantum Solutions’ tests of
What does that really mean? quantum volume and the dates when each test
Quantum volume is a metric that measures passed.
the capabilities and error rates of a quantum All tests are above the 2/3 threshold to pass
W A computer.
IKIPEDI

It expresses the maximum size of square quantum the respective Quantum Volume.
circuits that can be implemented successfully by Circles indicate heavy outcome averages and
the computer. the violin plots show the histogram
The form of the circuits is independent from the distributions. Data colored in blue shows
quantum computer architecture, but compiler can
system performance results and red shows
transform and optimize it to take advantage of the
computer's features. modeled, noise-included simulation data.
Thus, quantum volumes for different White markers are the lower 2-sigma error
architectures can be compared. bounds.
The system successfully passed the Quantum
In 2020, the highest achieved quantum volume Volume 128 test outputting heavy outcomes
(per § IBM's modified definition) rose from 32 for
IBM's computer "Raleigh" to 128 for Honeywell's 71.78% of the time, which is above 2/3
"H1",[2] i.e. quantum circuits of size up to 7×7 threshold with 99.934% confidence. The
have been implemented successfully. average single-qubit fidelity is 99.97(1)% and
the average two-qubit gate fidelity is
This and future increases in the capabilities of 99.54(7)% with fully-connected qubits.
quantum computers will empower customers
to achieve better and more results.

The differentiated technology, exemplified by


the high-fidelity and fully-connected qubits
with mid-circuit measurement* and qubit reuse,
enables the customers to push the frontier of
quantum computing applications. *(Mid-Circuit
Measurement is a unique feature that allows
qubits to be selectively measured at a point
other than the end of a quantum circuit. The
quantum information of a measured qubit
collapses to a classical state (zero or one), but Figure 12: Plot for the heavy out comes
the non-measured qubits retain their quantum The figure above shows the individual heavy
state. ) outcomes for each Quantum Volume 128 run.
The blue line is an average of heavy outcomes
and the red line is the lower 2-sigma error bar
which crosses the 2/3 threshold after 186
circuits.

Figure 11: Plot for the outcomes of the respective


Quantum Volumes

Blaise Pascal Magazine 92 2021 26


Quantum Development: Honeywell Page 12/ 14
Larger volumes, better results, Hot Qbits / Quantum Internet
TRAPPED ION QUANTUM COMPUTER
A trapped ion quantum computer is one
proposed approach to a large-scale quantum
computer.
Ions, or charged atomic particles, can be
confined and suspended in free space using
electromagnetic fields.

Qubits are stored in stable electronic states of


each ion, and quantum information can be
transferred through the collective quantized
motion of the ions in a shared trap (interacting
through the Coulomb force).
Figure 13: First-Generation Ion Trap Lasers are applied to induce coupling between
The new kid in town: the qubit states (for single qubit operations)
The Ion Trap or coupling between the internal qubit states
Currently, Honeywell Quantum Solutions and the external motional states
(part of Honeywell ofcourse) has started (for entanglement between qubits).
testing its first generation of commercial
micro-fabricated trapped-ion qubit devices. The fundamental operations of a quantum
See the image above. computer have been demonstrated
experimentally with the currently highest
These devices, or traps, hold the qubits which accuracy in trapped ion systems.
are integrated into Honeywell’s quantum
computing systems. Promising schemes in development to scale the
Traps are fabricated in the Minneapolis system to arbitrarily large numbers of qubits
microfabrication production facility. include transporting ions to spatially distinct
The first generation of traps incorporates locations in an array of ion traps, building large
includes different arrangements, or entangled states via photonically connected
architectures, of qubits. networks of remotely entangled ion chains, and
The different architectures under evaluation combinations of these two ideas.
include one-dimensional (1D) chains of ions as
well as a scalable design of a two-dimensional This makes the trapped ion quantum computer
(2D) arrays which eliminate qubit count system one of the most promising architectures
limitations imposed by a linear qubit for a scalable, universal quantum computer.
arrangement. one-way quantum computer, and various
Thi provides an enabling component for quantum cellular automata.
Honeywell’s first quantum computer.
The most widely used model is the quantum
The fabrication of traps also demonstrates a circuit. Quantum circuits are based on the
unique feature of our end-to-end quantum quantum bit, or "qubit", which is somewhat
computing technologies. This includes all analogous to the bit in classical computation.
components from the traps that form Qubits can be in a 1 or 0 quantum state, or they
computational qubits to the augmented control can be in a superposition of the 1 and 0 states.
electronics and user interfaces. However, when qubits are measured the result
Honeywell's quantum computer stores of the measurement is always either a 0 or a 1;
processing elements called qubits in a row the probabilities of these two outcomes
along the center of a device called an H trap. depend on the quantum state that the qubits
The company is working on second- were in immediately prior to the measurement.
generation machines that look more like a grid
than a line.

Blaise Pascal Magazine 92 2021 27


Quantum Development: Honeywell Page 13 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet
Over decades of research and development, For developers
Microsoft has achieved advancements across Bring quantum apps to life with the quantum
the quantum stack - including software, development kit for the Q# quantum
applications, devices, and controls. programming language and Azure Quantum. In
this open-source kit, you'll find tools to
Their approach to quantum takes a formulate and run optimization problems on
comprehensive approach to delivering all the large-scale or hardware-accelerated Azure
technology needed to enable commercial compute resources, as well as for developing
impact - encompassing everything from durable quantum apps for quantum hardware.
development to deployment.
Get the quantum development kit:
It includes major ongoing focus to develop the https://azure.microsoft.com/en-gb/resources
topological qubit to help make scalable, /development-kit/quantum-computing/
stable quantum computing a reality.
The development kit for quantum computing
With the Azure Quantum open cloud and optimization
ecosystem you can find a lot of what you might The open-source for Q# and Azure Quantum
need to accelerate your app-development and enables you to develop durable quantum
quantum computing: quantum software, applications for quantum hardware and for
hardware, as well as learning resources for scalable hardware.
developers, researchers, and students. Optimization is a class of problems whose
You can find pre-built optimization solvers that solutions are primary candidates for running on
borrow from quantum principles running on scalable quantum computers.
classical resources, and write quantum The Quantum Development Kit also has tools
algorithms designed to run on quantum to formulate optimization problems to run on
hardware. large-scale or hardware-accelerated computer
resources in Azure.

Figure 14: Microsoft overview of seervices related to Quantum

Blaise Pascal Magazine 92 2021 28


Quantum Development: Quatum Volume Page 14 / 14
Larger volumes, better results, Hot Qbits / Quantum Internet

Quantum Volume and potential - applied to scope


INDUSTRY

INTELLIGENCE Chemicals & Petroleum


Surfactants, Catalysts
RESEARCH
Chemical product design

Chemicals & Petroleum


Oil Shipping / Trucking
Refining Processes Distribution & Logistics
Feedstock To Product Vehicle Routing
Drilling Locations Network Optimization

Scenario Simulation
Freight Forecasting
Irregular Behaviors (ops)
Disruption Management

Distribution Supply chain Financial Services


Seismic Imaging Consumer goods Credit/Asset
Scoring

Financial Services Transaction


Derivalives Pricing Settlement
Diseas Risk PortFolio
Irregular Behaviors
Predictions Management
Artificial (Fraud)
Intelligence & Finance
Machine Learning Recommender Investment
Quality / Control Risk Analysis
Process Planning
Manufacturing
Supply Chain Structural Design
& Fluid Dynamics
Fabrication
Optimization
Health Care
& Life Sciences
Optimization Drug Discovery /
Accelerated Diagnosis International licensing
Clinical Trial Enhancements Protein Structure
Genomic Ananlyis Prediction
Medical / Drug Supply Chain

Manufacturing
Quantum Chemistry
Materials Discovery

Blaise Pascal Magazine 92 2021 29


ADVERTISEMENT

Editor in Chief: Detlef Overbeek


BLAISE PASCAL MAGAZINE Edelstenenbaan 21 3402 XA BLAISE PASCAL MAGAZINE
IJsselstein Netherlands

procedure procedure
var var
begin begin
for I := 1 to 9 do for I := 1 to 9 do
begin Prof Dr.Wirth, Creator of Pascal Programming language begin
... ...
end end
end; end;
[email protected]
Prof Dr.Wirth, Creator of Pascal Programming language Blaise Pascal, Mathematician Prof Dr.Wirth, Creator of Pascal Programming language Blaise Pascal, Mathematician
https://www.blaisepascalmagazine.eu

BLAISE PASCAL MAGAZINE 92


Multi Platform / Object Pascal / Internet / JavaScript / WebAssembly / Pas2Js / Databases
CSS Styles / Progressive Web Apps
Android / IOS / Mac / Windows & Linux

L I B R A R Y 2 0 2 0
90
85
86
87
88
89
VIDEO
51 52 53
84 50 54
49 55
26 27 28
83 25 29
48 56
81 24
10 30
82 47 9 11
31 57
23 8 1 12
80 46

SUPER
2 13 32 58
78 22 7 3
79 45 14 33
21 4 59
77 44 6
5 15 34

OFFER (5)
20 60
75 19 16
76 43 18 17 35
73 61
74 42 36
41 37 62
72

€ 150 ex Vat
40 39 38 Quantum Computing / By Detlef Overbeek
71 69 63 Max Box / Max Kleiner
Fastreport / By Detlef Overbeek
70 67 64 MMX / By Detlef Overbeek and Dennis Zubov
68 66 65 Code Examples / By Detlef Overbeek
New Lazarus PJU Files for Mac By Mattias
Gaertner

free shipping
Installing a package on MacOs
RegEx / By Michael van Canneyt
Sample Project: Lazarus & Delphi Easter
ALL CODE ABOUT THE USE Holidays
Multi Tier a series for the web / By Danny Wind
Chess / By Detlef Overbeek
BLAISE PASCAL MAGAZINE
ALL ISSUES IN ONE FILE
PAGE-CLARK

LAZARUS DAVID DIRKSE


LEARN TO PROGRAM
HOWARD

HANDBOOK
FOR PROGRAMMING WITH FREE PASCAL AND LAZARUS
USING LAZARUS

procedure
;
var
begin

BLAISE PASCAL MAGAZINE


www.blaisepascal.eu

COMPUTER (GRAPHICS)
MATH & GAMES IN
934 PAGES PASCAL

1. One year Subscription 4. Book Learn To Program using Lazarus PDF


2. The newest LIB Stick including 19 lessons and projects
- including Credit Card USB stick 5. Book Computer Graphics Math & Games
3. Lazarus Handbook - Personalized book + PDF including ±50 projects
-PDF including Code
30
A COMBINATIONS COUNTER Page 1/3
By David Dirkse
starter expert Combinatorics is an area of
mathematics primarily concerned with
W A
IKIPEDI
counting, both as a means and an end in
INTRODUCTION obtaining results, and certain properties of finite
In the mathematics field of combinatorics, a structures.
combination is a choice of elements from a It is closely related to many other areas of
mathematics and has many applications ranging
collection. The sequence of choosing is from logic to statistical physics, from
unimportant. evolutionary biology to computer science, etc.
Note that this part of two articles is meant to
preapare the for the second part: \ Insofar as an area can be described by the types
HASHI LOGIC PUZZLES of problems it addresses, combinatorics is
involved with the enumeration (counting) of
An example is where a team of cleaners is specified structures.
chosen from a group. The question is Sometimes referred to as arrangements or
1. How many different choices can we make configurations in a very general sense,
2. How to systematically generate and associated with finite systems.
number these choices They need to be "largest", "smallest" or satisfy
some other optimality criterion.
First some theory.
Combinatorics is a range of linked studies which
For elements we take the characters A,B,C,D,E
have something in common and yet diverge
These 5 elements can be ordered in widely in their objectives, their methods, and the
5.4.3.2.1 = 120 sequences. degree of coherence they have attained.
From ABCDE to EDCBA. One way to define combinatorics is, to describe
its subdivisions with their problems and
Now take the case where the collection techniques. (make the problem smaller, cut it into
segments).
consists of 2 A's and 3 B's.
Combinatorics is well known for the breadth of
To start we make these elements different by the problems it tackles.
attaching an index, so we have Combinatorial problems arise in many areas of
A1,A2,B1,B2,B3 and 120 number of pure mathematics, notably in algebra, probability
theory, topology, and geometry,
sequences again.
as well as in its many application areas.

The A elements can be placed in 2.1 = 2 In the later twentieth century, powerful and
sequences, the B elements in 3.2.1= 6 general theoretical methods were developed,
sequences which actually are the same if the making combinatorics into an independent
sequence is unimportant. branch of mathematics in its own right.

One of the oldest and


For the real number of COMBINATORICS IS USED most accessible parts of
sequences, without the FREQUENTLY IN COMPUTER combinatorics is graph
indexes, we have to divide SCIENCE TO OBTAIN FORMULAS theory, which by itself
120 by 2 and by 6, AND ESTIMATES IN THE ANALYSIS has numerous natural
connections to other
so 120/(2.6)=10 unique areas. Combinatorics is
sequences remain. used frequently in computer science to obtain
formulas and estimates in the analysis of
(AABBB,ABABB,ABBAB,ABBBA,BAABB,BABAB, algorithms.
BABBA,BBAAB,BBABA,BBBAA)
A mathematician who studies combinatorics is
While choosing from a group of people we called a combinatorialist.
may attach character N to a person which is
not chosen and character Y to a person which
is chosen.

If we select 3 people out of a group of 8 then


we notice sequences like YYYNNNNN,
YNNNYYNN. Ú (next page)

Blaise Pascal Magazine 92 2021 31


A COMBINATIONS COUNTER Page 2/3

So the number of combinations equals the


number of ways we can write sequences of
3 Y's and 5 N's which is
8.7.6.5.4.3.2.1/(1.2.3.4.5.1.2.3) = 56.

{division by 3.2.1 and also by 5.4.3.2.1}

In general:
Writing 1.2.3….N as N! (called N faculty)
and the number of combinations of k choices
out of N elements as C(N,k) then C(N,k) = N!
/(k! . (N-k)!) because there are k elements
chosen and N-k element not chosen. Add, Shift, Backup

This project was


started because I
needed a
combinations
counter to solve
logic puzzles called
Hashi, also called
Bridges.
A next article covers
the Hashi project.

It's about elements which are chosen or not.


For this project I choose binary digits 0 (not Flowchart
chosen) and 1 (chosen) , placed in an array of (read 1 for bridges, it was about solving
bytes. Hashi puzzles)

Take the combinations of 3 out of 5:


1: 11100 6: 10011
2: 11010 7: 01110
3: 11001 8: 01101
4: 10110 9: 01011
5: 10101 10: 00111
Indeed, C(5,3) = 5!/(3!)*(2!) = 10

While “counting” from 00000 we notice


three conditions:
1. Adding a 1, so counting
00000,10000,11000,11100:
the first combination
2. Shifting the most right 1:
11100,11010,10011:
three next combinations
3. Backup, if the rightmost digit is 1
a. Remove this digit
b. Search left for 1 digit
c. Shift this digit right
Repeat steps 1..3
The end is reached when the backup finds no
more 1's.

Blaise Pascal Magazine 92 2021 32


A COMBINATIONS COUNTER Page 3/3
function advance : byte;
The counter in action Delphi 7 label loop,Ladd,Lshift,Lback;
begin
Loop:
if p = 8 then goto Lback;
if count = maxcount then goto Lshift;
Ladd:
inc(p);
counter[p] := 1;
inc(count);
if count = maxcount then begin
result := 1;
exit;
end;
goto loop;
Lshift:
counter[p] := 0;
inc(p);
counter[p] := 1;
result := 1;
exit;
Lback:
This is the advance function which produces a counter[p] := 0;
new combination in the counter[ ] array on dec(count);
being called: while (p > 0) and (counter[p] = 0) do dec(p);
if p = 0 then begin
result := 0;
exit; //report end
end;
counter[p] := 0;
inc(p);
counter[p] := 1;
if (8-p) < maxcount - count then goto LBack; //no space for
//next digits
goto Loop;
end;

p : index for counter array.


Count : the number of 1's placed
Maxcount : the maximum number of 1's {k in
C(N,k)}
Note: N = 8 in this program.

Delphi 10.4 Calculation of the number of combinations:


function combinations(n,k : byte) : dword;
//calculate number of combinations
var i : byte;
x : double;
begin
x := 1;
for i := 1 to n-k do x := x * (i+k)/i;
result := round(x);
end;

The function avoids very large intermediate


results.
For higher numbers of N the number of
combinations explodes.
C(40,20) = 137846528800. (rounded to 100's)
Please refer to the source code for details.
Lazarus

Blaise Pascal Magazine 92 2021 33


HASHI LOGIC PUZZLES Page 1/6
By David Dirkse
Below is pictured an initial puzzle (left) and
the solved state (right):
Hashi (Hashiwokakero) also called
Bridges is a Japanese logic puzzle.

Hashiwokakero, Hashi o kakero; literally build


bridges! is a type of logic puzzle published by
Nikoli.
It has also been published in English under the
name Bridges or Chopsticks
(based on a mistranslation:
橋, means bridge;
the hashi of the title,

hashi written with another character, 箸, The circles are islands which have to be
means chopsticks). connected by bridges.
It has also appeared in The Times under the The number in the circle is the sum of bridges
name Hashi. In France, Denmark, the connecting to the island.
Netherlands, and Belgium it is published under A maximum of two bridges may connect two
the name Ai-Ki-Ai. islands. Bridges may not cross.
The puzzle is solved when all bridges have
RULES been installed and all islands are
Hashiwokakero is played on a rectangular grid interconnected.
with no standard size, although the grid itself Hashi puzzles exist in dimensions from 7x7 to
is not usually drawn. 25x25.
Some cells start out with (usually encircled) The difficulty ranges from easy to extreme.
numbers from 1 to 8 inclusive; these are the
"islands". The rest of the cells are empty. PASCAL DELPHI /LAZARUS PROJECT.
The purpose of this Hashi project is to:
The goal is to connect all of the islands by — Replace pencil, eraser and paper
drawing a series of bridges between the — Save and open puzzles
islands. The bridges must follow certain — Supply warnings
criteria: — Supply hints
— They must begin and end at distinct — Supply full solutions
islands, travelling a straight line in between. — Test for multiple solutions
— They must not cross any other bridges
or islands. Coding the puzzle
— They may only run orthogonally The puzzle is divided in squares (fields),
(i.e. they may not run diagonally). a field may contain:
— At most two bridges connect a pair of — nothing
islands. — An island
— The number of bridges connected to each — A horizontal bridge
island must match the number on that — A vertical bridge
island. type TFieldType = (ftNone,ftIsland,ftHbridge,ftVbridge);
The bridges must connect the islands into TField = record
a single connected group. ftype : TFieldType;
Idx : byte; //entry in island list
brCount : byte; //bridgecount for bridge and islands fields
end;
const maxgame = 15; //maximum game size 15x15
maxIsland = 100; //maximum number of islands
var game : array[1..maxgame,1..maxgame] of TField;

Blaise Pascal Magazine 92 2021 34


HASHI LOGIC PUZZLES Page 2/6

This supplies enough information to paint the In this list we see the neighbours vector
game, add/remove islands by mouseclicks, neighbrs[ ] which holds the island list index of
add/remove bridges by mouseclicks or – the 1 to 4 neighbours,
movements. Vector brConn[ ] holds the number of installed
A two dimensional array with hidden islands bridges for directions 1..4.
and bridges however is inconvenient to x,y are the coordinates of the island in the
generate warnings and hints or to recognize a game[ , ] array;
solved puzzle. The byte variable groupNr serves the checking
for a solved puzzle and also the recognition of
It is more convenient to have the islands an isolated island or group of islands. See later.
separately listed in an array.

In above Tfield we notice a variable Idx which


points to an island in the island[ ] list.

Instead of (x,y) to indicate an island in the


game[ . ] array, now one number suffices to
identify an island in the island array.
Also this list holds the number of bridges
installed in each direction and the island
indexes of the neighbours. The island list is
made when play mode is switched on.
type TVector = array[1..4] of byte;//[1] right; [2] up; [3] left; [4]
down
TIsland = record
x,y : byte; //field coords in game array
brCount : byte; //nr of bridges to install There are two type of warnings:
brConn : Tvector; //bridges connected per direction 1. An island is unable to place all of
neighbrs : Tvector; //[right,top,left,down] neighbour
the required bridges
groupNr : byte; //for isolation and solved puzzle testing
end;
var Island : array[1..maxIsland] of TIsland;
IslandCount : byte; //total islands present
BridgeCount : byte; //total bridges added in game
maxBridgeCount : byte; //total bridges to add

NOTE:
the number of bridges to install is the sum of
all islands bridge counts divided by two.
So, if this sum is odd, the puzzle cannot be
solved.
All islands are placed in an Island[ ] list.
Picture below shows an island with 4
neighbours:

The red colored island cannot install 4 bridges.


2. Isolated islands

Blaise Pascal Magazine 92 2021 35


HASHI LOGIC PUZZLES Page 3/6

Before descending into the generation of HINTS


warnings and hints, good notation is Several websites offer Hashi puzzles and
convenient. supply instructions how to solve them.
B is the number of bridges to install at an island. These cases are obvious:
ai {i: 1..4} is the number of bridges (0..2)
that neighbour i is able to supply.
A = a1+a2+a3+a4

NOTE: if a vertical bridge crosses between


horizontally oriented islands, the a value is
zero.
For an island, a warning (type 1) must be
generated if A < B.
To check for isolated groups (warning type 2) , 4 in the corner, 6 on a side, 8 in the center: 2
first the groupNr variable is set to the island list bridges are needed in all directions.
index, so each island has its own unique group At least one bridge must be present in these
number. cases:

Then scanning the island list, the connection


with neighbours 1 and 4 (right, down) is
examined.

If a connection exists, the island with the


highest group number has his group number
replaced by the lowest group number.
3 in the corner, 5 at a side and 7 in the
center require at least one bridge per
Repeating this process until no group number
direction.We feel however that the hints
changes have occurred, the case of a solved
above are in fact examples of one and the
game is where only one group (nr. 1, of course)
same general rule. Let's investigate.
remains.
Starting at an island without any bridge, we
If more than one group remains, the groups are
count for each neighbour the number (a) of
isolated.
bridges it allows to connect. This depends on
To check for isolated groups, a new list is built:
the number of bridges already installed at
const maxgroup = 100; this neighbour, its own bridge count and a
type TGroupData = record possible blockade by bridge crossings.
IsGCount : byte; //islands group count
BrSum : byte; //bridges summed
BrConnected : byte; //actual bridges
end;
var grouplist : array[1..maxgroup] of TGroupData;

IsGcount : number of islands in the group.


brSum : bridges to install in the group.
brConnected : actual number of bridges
installed in the group.
The groupNr variable in the island[ ] list is the
index for the grouplist.

Blaise Pascal Magazine 92 2021 36


HASHI LOGIC PUZZLES Page 4/6

We ask the question: “can we skip painting a FULL SOLUTIONS


bridge in direction 1”? So called extreme puzzles reach a point where
This is the case if directions 2,3,4 supply no hints can be generated.
enough bridges In these cases a so called brute force
B <= a2+a3+a4 or approach always is able to find a solution.
B <= A-a1 so
A-B-a1 >= 0 Brute force means that analytic reasoning is
For direction i, in case of abandoned. Simply all possibilities are tried.
A-B-ai = -1 1 bridge is missing Problem however is how to count all
A-B-ai = -2 2 bridges are missing. possibilities in a systematical way, being sure
So if pi is the number of bridges to paint in that no one is skipped.
direction i we see: Also processing time must be kept within
-pi = A-B-ai reasonable boundaries.
pi = (B-A) + (ai – bi) So, assume we have reached the point in
If bi are the bridges already installed in solving a Hashi puzzle where no hint is found
direction i. but some bridges are still missing.
Negative values of p are replaced by 0. Of all possibly missing bridges a list is
Example: generated. In most cases this list will be
longer than the actual number of bridges that
need to be installed.
If 2 bridges may connect to an island in the
same direction, 2 identical entries are made in
the bridgelist.
type Tline = record
x1,y1,x2,y2 : byte; //islands coords of bridge
end;
TBridge = record
line : Tline; //x1,y1 x2,y2 islands
coordinates in game[ ]
AB : byte; //0: no bridge; 1: bridge present
p1 = p2 = (5-6) + 1 = 0 Skip10 : boolean; //skip double 01-10 counts
p3 = p4 = (5-6) + 2 = 1 end;
var bridgelist : array[1..50] of Tbridge;
maxbridgelist : byte; //top of list
Example (reduced picture)
If the solve button is pressed an entry in the
bridgelist is made for each bridge which may
possibly be added.
Say this are 10 entries for 10 possible bridges.
However, we know how many bridges were
added already, say we have 4 bridges to go.
This means that we have to select 4 bridges
out of 10 in a systematical way to see if any
selection represents a solution.
In math this is known as a combination of 4
out of 10.
This number of combinations is written as
C(10,4) = 10!/(4!)*(6!) = 210.
Please refer to my previous article about
combinations counting.
The skip10 variable in the bridgelist is set for
the second of two identical entries.

37
HASHI LOGIC PUZZLES Page 5/6

In this case bridge selections 01 and 10 are the Hints and warnings are painted directly on
same, so counting must be 00,10,11 skipping paintbox1 of form1.
the 01 selection.(do not select bridges, select
1 bridge, select both bridges). The effect of events from keyboard, mouse or
Byte array CC[ ] is the combinations counter. buttons depends on the gamestate.
1: bridge; 0:no bridge Type TGamestate =
Next picture shows what to do after a CC (gsInitial,gsNew,gsPlaying,gsHintWait
ing,gsSolving);
counter update:
gsNew: allows adding/removing islands in
game[ , ]
gsPlaying : allows adding/removing bridges,
selection of warnings and hints.
gsHintWaiting: a hint is found, waiting for
user decision: install or neglect.
gsSolving: searching for solution in
progress.

For each new combination in CC bridges are Gamestates are updated by procedure
added/removed from the island list and controlmessage(cm : Tcontrolmesage)
game[ , ] This is the central place to change the
Then a check for solution is made. The gamestates.
number of bridges in the bridgelist is limited to Mouse- and keyboard events and also button
40 to avoid extremely long processing times. clicks call the controlmessage procedure with
a message indicating the originator. Then the
Multiple solutions controlmessage procedure, after approval,
These are simply checked by generating more calls a specific procedure to do the job.
combinations and testing for solutions. Procedure controlmessage in fact is a table
When the last combination is reached, like construct of case statements:
no more solutions are possible. Imagine the gamestate as row, the message
type as a column.
This Delphi/ Lazarus project. This structure may look exaggerated at first
The menu buttons are supplied by the (why not performing functions directly in
TDavArrayBtn component, see my Math and the event methods) but centralizing control
Delphi programming book. adds to the clearness and increases
maintainability. The project has 6 units:
The gamesize selection is made by a
TDavRotation button component, which Unit1:
imitates buttons found on labotory equipment. event handling, control,
See an earlier publication. adding/removing islands
Game_unit:
Space in this article is limited so I do not show
for testing of a solved puzzle, warning
code, please refer to the Delphi project.
and hints, adding or removing bridges
Variable gamesize holds the selected size of Paint_unit:
the Hashi puzzle. painting procedures for Gmap bitmap
Array game[1..15,1..15] uses only fields Solve_unit:
1..gamesize. procedures to solve a puzzle by brute
The game is painted in bitmap Gmap, which is force, combinations counter
created in the onCreate event. Progress_unit:
Gmap is copied to Paintbox1 to become procedures to make progress bar in
visible. paintbox progressbox on form1
IO_unit:
procedures to save and open puzzles.

Blaise Pascal Magazine 92 2021 38


HASHI LOGIC PUZZLES Page 6/6

While adding islands in the gsNew gamestate, Clear button


checks are made to keep a distance between If menu:new then all islands are removed.
islands and avoids bridgecounts which are If menu:play then all bridges are removed
too high. Also, islands having bridges
connected cannot be changed. Save/open
The saved hashi files have no extension.
Progressbar For easy recognition, the filename is prefixed
During the search for solution counter by hashi!
CCupdates in the solve_unit counts the
combinations. Solving a puzzle
Maxcombinations (unit1) is the total 1. On your own by adding bridges
number of combinations calculated earlier. 2. Pressing the warning button to report
The value CCupdates/maxcombinations errors
*100 is passed to the setProgress(perc : 3. Pressing the hint button to receive hints
single) procedure in the progress_unit. which solve most puzzles
4. Pressing the Solve button if hints are not
Hashi Help found.
Most buttons are self explanatory.
For bridges added by hints, there is simply no
Adding/removing an island: choice, these bridges are always necessary
Menu: New even in case of multiple solutions.
Mousedown on game places island with The solve button may be pressed any time
bridgecount 1. during play mode.
Next left-mouseclicks increment the It does not change any installed bridge but
bridgecount. Right-mouseclicks decrement the tries to find a solution by adding missing
bridgecount. bridges.
A bridgecount of 0 removes the island. For very hard puzzles, start with adding
bridges indicated by hints and press the solve
Adding/removing bridges button if no hints are found.
Menu: Play
Position mousepointer over island. Press left
mousebutton and hold down while moving
mouse in direction of bridge. If bridge appears,
release mousebutton.
Repeating this procedure adds another bridge.
Also a second bridge may be added by moving
over an existing bridge and pressing the left
mousebutton. Pressing the right-mousebutton
removes the bridge.

Blaise Pascal Magazine 92 2021 39


ADVERTISEMENT

U S K BLAISE PASCAL MAGAZINE 92


Multi Platform / Object Pascal / Internet / JavaScript / WebAssembly / Pas2Js / Databases

ARBOORUSOK
CSS Styles / Progressive Web Apps
Android / IOS / Mac / Windows & Linux

AL

Z PA
SC

LA ND AZA BO
EE
FR
H AL
LAZARUS HANDBOOK 1

IT SC
W PA

HA L AND
G EE
IN FR
MM
LAZARUS HANDBOOK 2
H
GRA W
IT
O
PR NG
R MI
FO
H FO
R
PR
OGR
AM

an
Ca Oue
l v ssa ee
ae ou erb
ich r In Ov
k
t,
ey ng
nn dra
o,
2 Bla
ise
Pa
sca
l
Quantum Computing / By Detlef Overbeek
Max Box / Max Kleiner
Fastreport / By Detlef Overbeek
MMX / By Detlef Overbeek and Dennis Zubov
Code Examples / By Detlef Overbeek
New Lazarus PJU Files for Mac By Mattias
Gaertner
Installing a package on MacOs
RegEx / By Michael van Canneyt
Sample Project: Lazarus & Delphi Easter
rs : Mrtne tlef
o Gä D e
Holidays
th ,
Au ttias inig
e Multi Tier a series for the web / By Danny Wind
Ma n H
Sv
e
Chess / By Detlef Overbeek

Subscription
Combi (4)
Subscription + Lazarus Handbook
(hardcover)

€ 100
Ex Vat 9%
Including shipment !
REG EX USED IN PASCAL PAGE 1/8
By Michael van Canneyt

ABSTRACT
Regular expressions should be a part of every
programmer’s toolbox. Once grasped,
they are easy to use
and can accomplish otherwise
REG EX difficult or time-consuming
tasks for you.
A short introduction
q N(S) f

& PASCAL
starter
in Regular Expressions.

expert

Figure 1: Trapmoth - Own work - Altered by Overbeek


INTRODUCTION A nondeterministic finite automaton (NFA) used as a
construction block for Thompson's construction algorithm
Regular Expressions have been around for converting a regular Kleene Star expression into a NFA.
almost 70 years, and are commonly used to A regular expression (shortened as regex or
perform search and replace operations. regexp; also referred to as rational
They can be found in most IDEs or text editors. W A
expression) is a sequence of characters that
IKIPEDI

Still, surprisingly many people do not know how define a search pattern. Usually such patterns
to use them. Therefor we give a simple are used by string-searching algorithms for "find"
or "find and replace" operations on strings, or for
introduction on how to use them. input validation. It is a technique developed in
In what follows, the POSIX conventions for theoretical computer science and formal language
regular expressions are described. theory.
Some editors and IDEs use slightly different
conventions. The concept arose in the 1950s when the
American mathematician Stephen Cole Kleene
A good overview of all possibilities (and in formalized the description of a regular language.
particular the Perl Compatible Regular The concept came into common use with Unix
Expressions (PCRE)) can be found on the text-processing utilities. Different syntaxes for
wikipedia page: writing regular expressions have existed since
https://en.wikipedia.org/wiki/Regular_expression
the 1980s, one being the POSIX standard and
another, widely used, being the Perl syntax.

Many programmers will be familiar with pattern


Regular
matching for filenames: expressions are
A mechanism used in the FindFirst/Findnext used in search
calls: They allow for simple wildcard engines, search
matching, where * stands for an arbitrary and replace dialogs
of word processors
sequence of characters, and ? stands for a
and text editors, in
single character. text processing
utilities such as sed
Thus ?.pas will match all filenames of 1 and AWK and in
character long with extension .pas , and lexical analysis.
Many programming
System.*.pas will match all filenames that languages provide
start with the System namespace. regex capabilities
Similarly, many programmers fluent in SQL will either built-in or via
know the LIKE operator that allows the libraries.
Figure2: American mathematician
use of % and _ wildcards. Stephen Cole Kleene
So, how to match these filenames with regular
expressions ? Like in filename wildcard
matching, letters and digits (and many symbols)
in a regular expressions match only that
letter or digit. But a regular expression can
contain some special characters.

Blaise Pascal Magazine 92 2021 41


PAGE 2/8
REG EX & PASCAL
Here are some of them: You can specify a range of characters by
ˆ The ˆ matches the beginning of the separating them with a dash, for example a-z
input string (usually a line of text). or 0-9, just as you specify a range in Pascal.
. The dot . matches any single
character. It is equivalent to the ? Thus, the following expression will match all
wildcard in filename matching. .txt filenames that end on -1, -2 or -3:
^.*-[123]\.txt$
* The asterisk matches the previous The following will also do:
element any number of times (also zero). ^.*-[1-3]\.txt$
$ The $ matches the end of a search string
(usually a line of text). The POSIX standard specifies also several
If you want to include a literal dot or asterisk named ranges of character sets.
in your regular expression, you must escape For example
them with a backslash. [:alpha:] denotes all alphanumerical
With these 2 characters, we can already characters, whereas
emulate the filename pattern matching. [:digit:] denotes all digits and
[:space:] denotes whitespace.
The following regular expression: Some languages (notably, Perl) or editors use
^.\.pas$ escaped characters
This will match all filenames with a name of for this: \w means words, \s means spaces etc..
1 character long, and extension .pas.
NOTE that there are no operators to specify
Likewise, the following: case-insensitive or case sensitive match:
^System\..*\.pas$ this kind of property of a search must be
will match all filenames that start with the specified separately.
System namespace.
2 SEARCH AND REPLACE
However, you can do more with Regular The Delphi IDE and the Lazarus IDE both allow
expressions than just emulate file name you to use regular expressions:
wildcard matching. For instance, you might the search (and replace) dialog has a checkbox
want to search for files that are either a .pas ’Regular expression’. When checked, the IDE
file or a .dcu file. To be able to do this, we will interpret the text in the search box as a
need 2 more concepts in Regular Expressions: regular expression.
For example
( ) The brackets mark a subexpression. ^ *F.* : .*;$
Will match all field or variable definitions
| The vertical bar matches the element before starting with an F. (they must have a space
before
or the element after.
and after the colon)
Items\[.*\]:=
To find either a .pas file or a .dcu file, we
will find all assignments to an Items array
can combine these two with
^.*\.pas|dcu$ element.

If you want to find files that end on


-1, -2 or -3 , then you can use the following
operator:
[ ] This will match any letter between the
brackets.
[ˆ ] This will match any letter not between
the brackets

Blaise Pascal Magazine 92 2021 42


PAGE 3/8
REG EX & PASCAL

Figure 3: Search and replace in an Assign method

In the IDE you will usually want to use the Keep the list selected, and in the search and
replace functionality when using regular replace dialog, you can enter the following:
expressions. F{.*} : {.*};
This will match all field definitions in the
When you want to replace the found matches selection.
with something else, you will most likely want Because we used the grouping operators,
to refer to part of the matched term in your we can use the group in the replace text:
replacement text. \0 := Src.\0;
In order to do so, you can use the { } brackets This will replace something like
to group particular parts in your expression. FFirstName : String;
You can refer in your replacement text to these With:
groups by \0 to \9 . FirstName := Src.FirstName;
When we hit ’Replace all’ the IDE will do all
A good example where this can be useful is the replacements, and the result can be seen in
Assign method, which must be implemented figure 4 on page 4/8 of the article, page 44 of
in descendants of TPersistent to copy all the issue.
properties from one to another instance.

The text and the search and replace dialog to


do so are shown in figure 3 on page 3/8 of the
article, page 43 of the issue.
When implementing such a method you start
by copying all private fields that make up
your persistent class to the body of your Assign
method.

Blaise Pascal Magazine 92 2021 43


PAGE 4/8
REG EX & PASCAL
The TRegexpr source code comes with a demo
application REStudio, which is similar
in purpose to RegexBuddy. It needs some care,
but after some small fixes it can be made
to work in Delphi.
The necessary fixes to let it compile in Lazarus
and Delphi Rio (and newer) have been pushed to
the following repository:
https://github.com/mvancanneyt/TRegExpr
When started, it looks like figure 5 on page 5/8
of the article, page 45 of the issue.
Its working is quite simple: in the top
memo, you can enter a regular expression.
The program will give you feedback, so you
will immediately see if the expression is valid.
The bottom memo allows you to enter a text,
and with the Exec.../ExecNext buttons you can
let the regular expression execute its action.

The TRegExpr class is not a component.


It must be created in code, and has the
following properties:

Figure 4: The completed Assign method — Expression


The regular expression.
3 USING REGULAR EXPRESSIONS IN DELPHI — ModifierStr (string)
OR LAZARUS set the regular expression modifier options
Newer versions of Delphi come with the as a string (as one would in Perl or
RegularExpressionsCore unit which contains Javascript). The string consists of a
the TPerlRegEx class. concatenation of the uppercase letter of
It uses an external library which contains the the next properties.
actual implementation of the regular expression — ModifierI (boolean)
engine. The I modifier, for case insensitive search.
— ModifierR (boolean)
The commercial tool RegexBuddy is a GUI The R modifier: enables some extented
program that assists you in creating a regular Russian characters.
expression and can generate the necessary — ModifierS (boolean)
Delphi code for handling the regular The S modifier: when True, the — character
expresssion. also matches a newline.
— ModifierG (boolean)

There is also an open source all-native Object The G modifier: turn on greedy matching.
— ModifierM (boolean)
Pascal implementation of regular expressions:
https://github.com/andgineer/TRegExpr The M modifier: enables multiline mode.
It is implemented by Andrey V. Sorokin, In that mode, the ˆ and $ characters
has been around for a long time, works for all match the beginning and end of each line in
versions of Delphi, and also for Lazarus/Free the search text, not just the beginning and
Pascal. end of the whole search text.
In fact, Free Pascal ships with a version of — ModifierX (boolean)
TRegexpr. Therefor, we’ll use this The X modifier: Allows you to use
implementation to demonstrate how regular comments in your regex using the
expressions can be used. # character.

Blaise Pascal Magazine 92 2021 44


PAGE 5/8
REG EX & PASCAL

Figure 5: RE Studio in action


— SubExprMatchCount (integer) — CompilerErrorPos
the amount of sub expression matches if an error occured during compilation of
after an Exec or ExecNext. your Regular Expression, this gives the
— MatchPos (array of integer) position of the error.
a 0-based array giving you the position of There are many more properties, but the
the subexpressions in the search string. above ones are the main properties.
The 0-th entry is the position of the whole The class also has the following important
regular expression match. methods:
— MatchLen (array of integer)
a 0-based array giving you the lengths of
the subexpressions in the search string.
The 0-th entry is the length of the whole
regular expression match.
— Match (array of string)
a 0-based array giving you the actual
matches of the subexpressions in the
search string. The 0-th entry is the text of
the whole regular expression match.

Blaise Pascal Magazine 92 2021 45


PAGE 6/8
REG EX & PASCAL
function Exec(const AInputString: RegExprString): boolean;
function ExecNext: boolean; overload;
function ExecNext(ABackward: boolean): boolean; overload;
function Substitute(const ATemplate: RegExprString): RegExprString;
procedure Split(const AInputStr: RegExprString; APieces: TStrings);
function Replace(const AInputStr: RegExprString;

const AReplaceStr: RegExprString; AUseSubstitution: boolean = False) // ###0.946 : RegExprString; overload;


function ReplaceEx(const AInputStr: RegExprString; AReplaceFunc: TRegExprReplaceFunction): RegExprString;

— Exec To demonstrate how to search, we create a


Starts a search for matches on small application in Lazarus with a memo
aInputString. Returns true if a match was (mdemo), a button (bsearch)
found. and a TFindDialog (FDRE) . The OnClick
— ExecNext handler of the button shows the find dialog:
Will search for the next occurence. procedure TMainForm.btnSearchClick(Sender: TObject);
If aBackWard is true, the search is done begin
backwards. Returns true if a match was FDRE.Execute;
end;
found.
— Substitute
will replace the text in ATemplate with the This is nothing special.
currently found matches: The OnFind event handler of the find dialog is
The template can contain placeholders for called every time the user clicks the Find
the subexpressions: button in the find dialog. Here we implement
$& or $0 is replaced by the whole match, the logic for searching.
and $1 till $n are replaced by their Because the TRegexpr has 2 methods to
respective subexpression. search, depending on whether it is the first
— Split time you search (Exec) or it is a next search
will split aInputStr into various items split (NextExec), we must keep track of whether
by the regular expression matches, and put it is a new search or the next time a search is
all found items in aPieces. done.
— Replace To do so, we store the regular expression in a
will replace aInputStr all the matches with variable, and if the regular expression has
the AReplaceStr term. If changed, we assume it is a new search:
AUseSubstitution is true, the
procedure TMainForm.FDREFind(Sender: TObject);
replacement term is not treated as a regular var
text, instead it is used as a pattern for the Found : Boolean;
Substitute to replace all items. The function begin
If FDRE.FindText<>FLastRE then
returns the input string with all matches begin
replaced. FreeAndNil(FRE);
— ReplaceEx FRE:=TRegexpr.Create;
will replace aInputStr all the matches with FLastRE:=FDRE.FindText;
FRE.Expression:=FLastRE;
the result of the AReplaceFunc callback; Found:=FRE.Exec(MDemo.Lines.text);
the callback is called for each match in the end
else
input string, and the result of the callback is Found:=FRE.ExecNext;
then used to replace that particular match in if Found then
the input string. This is a very powerful begin
mechanism. MDemo.SelStart:=FRE.MatchPos[0]-1;
MDemo.SelLength:=FRE.MatchLen[0];
end
So, how can we use this class to implement else
search and replace? ShowMessage('Search term not found');
end;

Blaise Pascal Magazine 92 2021 46


PAGE 7/8
REG EX & PASCAL

Figure 6: Search in action

When we find a match, we use the MatchPos This time we use a Delphi program. We drop 2
and MatchLen properties to set the selection TMemo components on it, one for the template
of the memo. (note that Matchpos is 1-based, (MTemplate), one for the result (MResult).
and SelStart is 0-based) If no match is found, We also drop a TValueListEditor
we show a message, but we don’t close the on the form. Here the user can enter the values
dialog. for the template variables. Last item is a
button (Generate) to generate the final text
NOTE that if the user based on the template and the user-provided
changes the text between searches, the matches variables and their values.
will no longer correspond to actual positions, The OnClick event of the button is
so in a real program, it would be best to make implemented with the ReplaceEx call:
the memo readonly while the search is active.
procedure TMainForm.GenerateClick(Sender: TObject);
The result of this can be seen in figure 6 on Var
page 7/8 of the article, page 47 of the issue. Regex : TRegexpr;
To demonstrate the power of the TRegexpr begin
Regex:=TRegexpr.Create;
class, we’ll also implement a small algorithm try
that transforms a template text with some data Regex.Expression:='\{\{[^{}]*\}\}';
placeholders to a ready-to-read text: a kind of MResult.Lines.Text:=
Regex.ReplaceEx(MTemplate.lines.Text,
mailmerge, or the kind of functionality often ReplaceCallback);
found in templating engines such as Mustache. finally
A template engine such as Mustache will replace Regex.Free;
end;
a template {{SomeVariable}} end;
with the value of SomeVariable. Usually more
complex logic is also available, but for this
example, we limit ourselves to simple variables,
which are kept in a Key=Value list.

Blaise Pascal Magazine 92 2021 47


PAGE 8/8
REG EX & PASCAL
As you can see, the code is almost 5 CONCLUSION
disappointingly simple. A regexp instance is Being able to use regular expressions can make
created, the regular expression to find template life a lot easier, both when coding in the IDE
names is entered, and the ReplaceEx is called as in an actual program: The examples
with the MTemplate text as input. The result of presented here hopefully demonstrated that
the function is assigned to the text in MResult. using simple regular expression is really not
difficult and that they can easily be
The real magic happens in the ReplaceCallback implemented in a Delphi or Lazarus program.
callback:
function TMainForm.ReplaceCallBack(Sender: TRegexpr): String;
Var
aMatch,aName : String;
begin
aMatch:=Sender.Match[0];
aName:=Copy(aMatch,3,Length(aMatch)-4);
Result:=vleKeys.Strings.Values[aName];
end;

Again, the function is simple. It could be


implemented as a one-liner, but for clarity, it is
split out in 3 lines: First the regular expression
match is taken, then the curly braces are
Michael van Canneyt has created 2 projects :
stripped off to get the variable name, and the last
one for Delphi and one for Lazarus. They are of
line uses the variable name to look up the
course downloadadble from your login:
replacement value in the value list editor. That’s https://www.blaisepascalmagazine.eu/
it. It is so simple to create a simple templating your-downloads/
engine. The result can be seen in figure 7 on page
8/8 of the article, page 48 of the issue.

Figure 7: A simple template engine in action

Blaise Pascal Magazine 92 2021 48


ADVERTISEMENT

S
ARU

LAZARUS HANDBOOK
S
RU LAZ
AZA ND
LAZARUS HANDBOOK 2

DL L A
AN CA
AL PAS
ASC REE
EP ITHF
FRE
LAZARUS HANDBOOK 1

W
ITH ING
GW MM
MIN ROGRA
AM P
GR FOR
PRO
FOR

+ 9 34
PA
GE
S

Sewn POCKET (2)


50 euro
ex Vat including shipment inc. PDF
LAZARUS HANDBOOK POCKET edition is
also sewn, to make sure you will not lose pages
after a while. It is printed on 100 percent
guaranteed FSC certified Paper

INCLUDED:
bookmark - creditcard - usb stick
which contains the personalized pdf
file of the book and the extra program files. So 934 pages
in two books
you have your electronic as wel the printed book
in one product.

For ordering go to:


https://www.blaisepascalmagazine.eu/product-category/books/

Blaise Pascal Magazine 92 2021 49


Galactic Center Sonification
(Credit: NASA/CXC/SAO/K.Arcand, SYSTEM Sounds (M. Russo, A. Santaguida))

https://chandra.si.edu/photo/2020/sonify/
sonify_galactic_all.mp4

INTRODUCTION:
Sonification is the process that translates data
into sound, and a new project brings the
center of the Milky Way to listeners for the
first time.
The translation begins on the left side of the
image and moves to the right, with the sounds
representing the position and brightness of
the sources.
The light of objects located towards the top of https://chandra.si.edu/photo/2020/sonify/
sonify_casa_all_at_once.mp4
the image are heard as higher pitches while
the intensity of the light controls the volume.

Stars and compact sources are converted to


individual notes while extended clouds of gas
and dust produce an evolving drone.
The crescendo happens when we reach the
bright region to the lower right of the image.
This is where the 4-million-solar-mass
supermassive black hole at the center of the
Galaxy, known as Sagittarius A* (A-star),
resides, and where the clouds of gas and dust
are the brightest.

Users can listen to data from this region,


roughly 400 light years across, either as
"solos" from NASA's Chandra X-ray
Observatory, Hubble Space Telescope, and
Spitzer Space Telescope, or together as an
ensemble in which each telescope plays a
different instrument.
https://chandra.si.edu/photo/2020/sonify/
Each image reveals different phenomena sonify_m16_composite.mp4
happening in this region about 26,000 light
years from Earth.

The Hubble image outlines energetic regions


where stars are being born, while Spitzer's For more detailed information:
infrared data show glowing clouds of dust https://chandra.si.edu/photo/2020/
containing complex structures. sonify/animations.html#M16
X-rays from Chandra reveal gas heated to
millions of degrees from stellar explosions and
outflows from Sagittarius A.

Blaise Pascal Magazine 92 2021 50


ADVERTISEMENT

R USOK S R USOK S
ZADBOARUOOK ZADBOARUOOK
S
AL AL RU
SC SC ZA
PA PA LA

A
L N AZ B W
IT
H
FR
EE

PA
SC
AL
A
L N AZ B W
IT
H
FR
EE

PA
SC
AL
PAS
CA
LA
ND

HA L AND HA L AND
G EE G EE EE

LAZARUS HANDBOOK
IN FR IN FR
MM H MM H FR
RA IT RA IT TH
OG G
W OG G
W WI
PR IN PR IN G
IN
R MM R MM
FO
H FO
R
PR
OG
RA FO
H FO
R
PR
OG
RA

FO
R
PR
OG
RA
MM

+
u th s G ig, D
A ttia in
Ma n H
Sv
e
e
an
l v ssa ee
ae ou erb
ich r In Ov
: M ne tlef
ors ärt e
k
t,
ey ng
nn dra
Ca Oue
o,
2 Bla
ise
Pa
sca
l

th
Au ttias inig
Ma n H
Sv
e
e
,
an
l v ssa ee
ae ou erb
ich r In Ov
: M ne tlef
ors Gärt De
k
t,
ey ng
nn dra
Ca Oue
o,
2 Bla
ise
Pa
sca
l

4
PA
GE
S

93

The books The extra protection cover Including the PDF

HardCover (3)
934 Pages
75 euro ex Vat
including shipment in two books
including. PDF
https://www.blaisepascalmagazine.eu/product-category/books/

Blaise Pascal Magazine 92 2021 51


CODE SNIPPETS Part 8 Find Easterdate LAZARUS Page 1/1
By Detlef Overbeek
starter expert
there was something wrong with the project
settings:
In these code snippets I want to make go to project settings and from there to
interesting code available for everyone, and if Compiler options Ú Config and Target
possible do that for Lazarus and Delphi. One Ú Target-specific options: (see Figure 1)
of the ways to find nice pieces of code is to check the box Win32 gui application(-WG)
search in the example list for projects that Win32 should be understood as Win32 and 64.
comes with Lazarus. Or create things myself
so everybody can use them.
Since I have a vast imagination I can think of
thousands, but they need to have a purpose:
one must learn something out of it that is not
easy to gain and can be an example in other
situations…

In this case it was even more adventurous.


I found three things that are interesting to
understand: the first
Once I tested the Easter-date program I found
that the program under Lazarus had a
command prompt running during the final
starting of the program. Rather annoying,
I want to get rid of that, and than asked Mattias
Gärtner - the Lazarus Guru –and he immediately
had an answer to it: Figure 2: The Easter-date application

Then there is a little


extra to be looked
after:
{$apptype console}
either delete this or
comment it .

Figure 1: Win32 Check

Blaise Pascal Magazine 92 2021 52


CODE SNIPPETS Part 5 Path & CompileDate Page 1/1
FUNCTION TForm1.CalcEasterday(aYear: WORD): TDateTime;
VAR
A, B, C, D, E, F, G, H, I, J, K, L, M, N: INTEGER;
vDay, vMonth: WORD;
BEGIN
A := aYear MOD 19;
B := aYear DIV 100;
C := aYear MOD 100;

D := B DIV 4;
E := B MOD 4;

F := (B + 8) DIV 25;
G := (B - F + 1) DIV 3;
H := (19 * A + B - D - G + 15) MOD 30;
I := C DIV 4;
J := C MOD 4; Figure 3: Google Eggs
K := (32 + 2 * E + 2 * I - H - J) MOD 7;
L := (A + 11 * H + 22 * K) DIV 451; Google had a nice easter logo which I used
M := (H + K - 7 * L + 114) DIV 31;
N := (H + K - 7 * L + 114) MOD 31; here. And now the funny part comes: the
project was developed in Delphi and then
vDay := N + 1; converted to Lazarus. But I did not have the
IF M = 3 THEN vMonth := 3 ELSE vMonth := 4;
Result := EncodeDate(aYear, vMonth, vDay); original file, so I had to recreate it, and if
END; possible make it a even „better“.

procedure TForm1.Listbox1DrawItem(AControl: TWinControl;


The second item is that I wanted to know Index: Integer; ARect: TRect; AState: TOwnerDrawState);
var
how the Easter code algorithm was ts: TTextStyle;
composed, you best take a look your self: begin
Tform.CalcEasterday Listbox1.Canvas.FillRect(ARect);
In this app the Easter related Holidays are ts := Listbox1.Canvas.TextStyle;
ts.Alignment := taCenter;
calculated. For the calculation there is a Listbox1.Canvas.TextRect(ARect, ARect.Left+2, ARect.Top,
Function created which gives the result and a Listbox1.Items[Index], ts);
procedure that sets the final dates end;
Procedure T.FormButton1Click.
In the about box you will find the name of the
PROCEDURE TForm1.Button1CLICK(Sender: TObject); provider. I am not sure, they were the designer
VAR
Easter: TDateTime; of this peace of code. If you are the designer,
aYear : WORD; please make contact!
BEGIN
ListBox1.Clear;
TRY
aYear := StrToInt(Edit1.Text);
EXCEPT
if LanguageButton.Caption = 'English' then
ShowMessage('Fehlerhafte Eingabe des Jahrs!')
else
ShowMessage('Incorrect input of the year!');
Exit;
END;
Easter := CalcEasterday(aYear);
ListBox1.Items.Add(DateToStr(Easter - 46));
ListBox1.Items.Add(DateToStr(Easter - 2));
ListBox1.Items.Add(DateToStr(Easter + 1));
ListBox1.Items.Add(DateToStr(Easter + 39));
ListBox1.Items.Add(DateToStr(Easter + 50));
ListBox1.Items.Add(DateToStr(Easter + 60));
END;

Blaise Pascal Magazine 92 2021 53


CODE SNIPPETS Part 8 Find Easterdate DELPHI Page 1/1

Figure 6: The Google eggs are available for Delphi as wel.

Figure 4: The Delphi Version


Because I want to make these little projects
available, I had to re-design it for Delphi, even
though the original design was already done in
Delphi. But since I discovered this project in
the Lazarus Example list and wanted to review
it, I not only had to redesign it, but also needed
to create some code that was not available for
Delphi which Lazarus does have:
TTextstyle which means you can centre the
text in the listbox, very nice! The third item:
But here is the code to do it in Delphi: not as
easy as in Lazarus, but it still can be done...
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Figure 6: The listbox text is now centered
Rect: TRect; State: TOwnerDrawState);
var
C: TCanvas;
s: string; Christian Feast Days
w: integer; Dependent on Easter Sunday
begin The date of Easter Sunday is
C:=ListBox1.Canvas;
C.FillRect(Rect); crucial for the sequence of the
s:=ListBox1.Items[Index]; Christian liturgical year as many
w:=C.TextWidth(s); Christian feast days are
C.TextRect(Rect, Rect.Left+2+(Rect.Right-Rect.Left-w) div 2, Rect.Top, celebrated at a fixed interval of
Listbox1.Items[Index]);
days (or weeks) before or after
end;
Easter Sunday.

As an extra I set the Delphi version to English, The table at


so you’ll have to translate by using the https://webspace.science.uu.nl/
Language Button. Of course all the code is ~gent0113/easter/easter_text2c
downloadable so you can have a closer look. lists the most important days in the Christian
liturgical year and their relation with the date of
Anyway: Happy Easter! Next year Easter will be
Easter Sunday. Nominally, the dates are given
be on my Birthdate (18 april 2022) for the current (Gregorian) calendar year, but
the dates can be adjusted for any other year in
the Gregorian calendar

Blaise Pascal Magazine 92 2021 54


CODE SNIPPETS Part 9 Icons on Form DELPHI Page 1/2
By Detlef Overbeek
starter expert

In this example - which is somewhat divergent


in Delphi to the original In Lazarus - I want to
show some little pieces of code that can
become handy: How to change your Form icon
on the fly and the use of the Track-bar.

Actually you can read the commentary notes


in the Code example and see what is going on.
Using it is best done by testing...The code
examples are of course available at your
personal Downloadpage:
https://www.blaisepascalmagazine.eu/
your-downloads/

procedure TFrmGUI.BtnFormIcoClick(Sender: TObject);


begin
// Add the application icon under Windows
FrmGUI.Icon.Assign(Image1.Picture.Graphic);
end;

procedure TFrmGUI.FormCreate(Sender: TObject);


begin
// Fetch the Path where the app is hosted and
// insert the variable with that for global use
S:= (ExtractFilePath(Application.ExeName)) ;
end;

procedure TFrmGUI.BtnLoadWinClick(Sender: TObject);


begin
Image1.Picture.LoadFromFile((S) + 'icons' + PathDelim + 'Delphi.ico');
// Extracts the path from where the program starts +subdir +file
Caption := 'Icon found at ' + S + 'icons' + PathDelim + 'Delphi.ico' ;

UpdateTrackbar; // See the procedure


end;

procedure TFrmGUI.BtnOSxClick(Sender: TObject);


begin
ShowMessage('Delphi can not show icons for other OSx')
// A button taken over from the Lazarus version, where this can be done
end;

procedure TFrmGUI.BtnSearch_IconClick(Sender: TObject);


begin

try
If OpenDialog1.Execute
Then Image1.Picture.LoadFromFile(OpenDialog1.FileName);
Caption := 'Icon found at Path: ' + OpenDialog1.FileName;
// Show in the caption area the path
Except
MessageDlg('Loading the icon failed', mtError, [mbOK], 0);
End;

UpdateTrackbar; // See the procedure


end;

Blaise Pascal Magazine 92 2021 55


CODE SNIPPETS Part 9 Icons on Form DELPHI Page 2/2
procedure TFrmGUI.Btn_Hor_VertClick(Sender: TObject);
begin
If Trackbar1.Orientation = trHorizontal
then
begin // Set the orientation of the trackbar
Trackbar1.Orientation := trVertical;

// Change the width of the buttons


BtnLoadWin.left := + (Trackbar1.Width + 2);
BtnLoadWin.width := (BtnLoadWin.Width - 25);

BtnOSx.left := + (Trackbar1.Width + 2);


BtnOSx.width := (BtnOSx.Width - 25);

BtnSearch_Icon.left := + (Trackbar1.Width + 2);


BtnSearch_Icon.width := (BtnSearch_Icon.Width - 25);

BtnFormIco.left := + (Trackbar1.Width + 2);


BtnFormIco.width := (BtnFormIco.Width - 25);

Btn_Hor_Vert.left := + (Trackbar1.Width + 2);


Btn_Hor_Vert.width := (Btn_Hor_Vert.Width - 25);

end
else if Trackbar1.Orientation = trVertical
then
begin
Trackbar1.Orientation := trVertical;

BtnLoadWin.left := + 4;
BtnLoadWin.width := (BtnLoadWin.Width + 26);

BtnOSx.left := + 4;
BtnOSx.width := (BtnOSx.Width + 26);

BtnSearch_Icon.left := + 4;
BtnSearch_Icon.Width := (BtnSearch_Icon.Width + 26);

BtnFormIco.left := + 4;
BtnFormIco.width := (BtnFormIco.width + 26);

Btn_Hor_Vert.left := + 4;
Btn_Hor_Vert.width := (Btn_Hor_Vert.Width + 26);

Trackbar1.Orientation := trHorizontal ;
end;

end;

procedure TFrmGUI.TrackBar1Change(Sender: TObject);


begin
TrackBar1.Position := ((Image1.Picture.Icon.Width)div 2);
end;

procedure TFrmGUI.UpdateTrackBar;
begin
if TrackBar1.Enabled then
begin
TrackBar1.Min := 0;
TrackBar1.Max := 160;
TrackBar1Change(TrackBar1);
end; In the example of the code at the left is the
code written for making sure you can see the
Button width will be changed if you have the
track bar horizontally activated or vertically.
The option Load from OSx is not available
because Delphi does not run on other OSx

Blaise Pascal Magazine 92 2021 56


CODE SNIPPETS Part 9 Icons on Form LAZARUS Page 1/1
starter expert
procedure TForm1.FormCreate(Sender: TObject);
begin
S:= (ExtractFilePath(ParamStrUTF8(0))) ;
This is the Lazarus version of the same end;
project. Here you can use Load from OSX and procedure TForm1.BtnLoadWinClick(Sender: TObject);
it works. I have tried to find the immediate begin
change for the Application Icon but that Image1.Picture.LoadFromFile(ExtractFilePath
(ParamStrUTF8(0)) + 'icons' + PathDelim + 'lazarus.ico');
doesn't work. Would have been a nice // extracts the path where the progarma starts +subdir
feature… Or Not? //+ file
Caption := 'Icon found at '
+ S + 'icons' + PathDelim + 'lazarus.ico' ;

UpdateTrackbar;
end;
You can load a
procedure TForm1.BtnOSxClick(Sender: TObject);
png file or what begin
ever bitmaps. The Image1.Picture.LoadFromFile(ExtractFilePath
(ParamStrUTF8(0)) + 'icons' + PathDelim +
result will however
'lazarus.icns');
be always an icon. Caption := 'Icon found at '
Lazarus has + S + 'icons' + PathDelim + 'lazarus.icns' ;

because of the UpdateTrackbar;


Multiple OSs an end;
extension that can procedure TForm1.BtnFormIcoClick(Sender: TObject);
contain multiple begin
icons: .icns Icon.Assign(Image1.Picture.Graphic);
end;

procedure TForm1.BtnSearch_IconClick
(Sender: TObject);
begin
Try
If OpenDialog1.Execute
Then Image1.Picture.LoadFromFile
(OpenDialog1.FileName);
Caption := 'Icon found at ' + ' Path: '
+ OpenDialog1.FileName;
Except
MessageDlg('Loading the icon failed', mtError, [mbOK], 0);
End;
UpdateTrackbar;
end;

procedure TForm1.TrackBar1Change(Sender: TObject);


begin
if TCustomIcon(Image1.Picture.Graphic).Count >
TrackBar1.Position
then TCustomIcon(Image1.Picture.Graphic).Current :=
TrackBar1.Position;
end;

procedure TForm1.UpdateTrackBar;
begin
TrackBar1.Enabled :=
Image1.Picture.Graphic is TCustomIcon;
if TrackBar1.Enabled then
begin
TrackBar1.Min := 0;
TrackBar1.Max :=
TCustomIcon(Image1.Picture.Graphic).Count - 1;
TrackBar1.Position :=
Here is the loaded TCustomIcon(Image1.Picture.Graphic).Current;
icon from OSX TrackBar1Change(TrackBar1);
end;
end;

Blaise Pascal Magazine 92 2021 57


Online Delphi FMX Power Trainingen

Leer ontwikkelen voor 4 platformen tegelijkertijd -


Windows, macOS, iOS en Android

4 en 5 maart van 09.00-17.00 uur


We starten weer met de trainingen!
Online deze keer, maar met evenveel
enthousiasme en passie én met een
kleine groep deelnemers.
Vooraf krijgen de deelnemers het
Nederlandstalig lesmateriaal toegestuurd.
Om het nog leuker te maken ontvangt u
ook box met versnaperingen om tijdens
de training van te genieten.

Overzicht trainingen

Delphi FMX Power Training op 4 maart


Laat u verrassen over de mogelijkheden van het FMX Framework voor cross-platform
ontwikkeling vanuit één enkele broncode en ga er na deze training zelf mee aan de slag.
Delphi FMX Android Power Training op 5 maart
Bent u al bekend met FMX en klaar voor het ontwikkelen van apps? Deze training gaat specifiek in
op het ontwikkelen van mobile apps met Delphi. Na deze training kunt u direct beginnen. Ook
geschikt als vervolg van de FMX Power training op 4 maart.
Interesse in beide trainingen? Dan krijgt u een combinatie korting.

Deelnemers ontvangen na afloop een certificaat van deelname.

Danny Wind Delphi MVP, trainer en ontwikkelaar


WEB SERVICE PART 1 Page 1/10
By Danny Wind starter expert

INTRODUCTION URL - Uniform Resource Locator


This series of articles is about writing your This is the human readable address that a
own web services server and client in Delphi. resource (a web service) can be found at. An
The approach of all articles is pragmatic. example would be https://duckduckgo.com/.
This first article introduces some of the It’s translated to a physical IP address through
concepts you need to know and shows you DNS. This way the resource can be located
how to create and consume your own web over a TCP/IP network. In analogies an URL
service in Delphi. would be the home address for the house
where your resource lives.
What is a web service? A web service sends
and receives data over the world wide web. URI - Uniform Resource Identifier
Web services mostly communicate over the There is also a thing called URI. This identifies
internet through the HTTP protocol and send a specific resource. If you just go with the idea
and receive data in one of the web formats, that this adds a specific resource identifier to
such as JSON, XML or HTML. retrieve from the URL location, you’re not far
off. An example of an URI is
Why would you want to build a web service? https://duckduckgo.com/index.html. In
Web services are used in almost every app, analogies the URI would be a specific
website and desktop application to get local bookcase inside the house.
and remote data. Web services are also used
for interoperability and import and export. For URL vs URI
instance accounting software usually has an It's fun to debate what is or isn’t an URL, or an
interface to its locally or remotely stored data URI, because the definition in the RFC
using a local or remote web service. Web documents leaves some of it open to different
services are also easily scalable. Start with a interpretations. So you may get into a
simple locally run web service on a laptop and discussion at the coffee machine on URL vs
then scale up into a server park or into the URI, after which you can relax with your cup of
cloud. coffee, as it really doesn't matter. It’s just the
In a sense even a website is a web service. location of your web service.
When you open an URL
(https://www.blaisepascalmagazine.eu/ The protocol used is HTTP, denoted by the
) in your web browser the browser sends a prefix http:. Even if the URL has HTTPS in its
HTTP GET command to the website URL and prefix this is still talking HTTP, it’s just
in response receives data in the form of a encrypted.
HTML page.
HTTP - Hyper Text Transfer Protocol
HTTP is the protocol used to communicate
However, when software developers mention
over TCP/IP with your web service. In analogies
web services, they mostly mean a web service
HTTP is a very limited language used to
that uses REST (REpresentational State
exchange data.
Transfer) over HTTP to send and receive JSON
formatted data. For instance the DuckDuckGo
API that resolves your question into a direct HTTP has nine commands that are used to
answer from WikiPedia, GitHub and more. Just request and receive data. Each of these
try this link in your browser commands has a specific purpose. For web
https://api.duckduckgo.com/
services there are four commands you should
?q=Blaise&format=json&pretty=1
start with.
When you access a web service you supply an
URL combined with an identifier into an URI
for a specific resource.

Blaise Pascal Magazine 92 2021 60


WEB SERVICE PART 1 Page 2/10

HTTP GET Retrieves data from the resource


idempotent, cacheable
usage in our web service SELECT
(get existing record, disallow caching so we get new
data each time)
HTTP POST Appends data to the existing resource
not idempotent, not cacheable/stale
usage in our webservice UPDATE existing
(partial update of fields in a record,
not updating the primary key)
HTTP PUT Replace the existing resource or inserts data as
idempotent, not cacheable/stale a new resource
usage in our web service INSERT new (or REPLACE)
(insert new record with new primary key,
or replace entire record)
HTTP DELETE Deletes the resource
idempotent, not cacheable/stale
usage in our web service DELETE
(delete existing record or return error if it doesn’t exist)

In our article we will use a simplified mapping


of HTTP commands to actions we want our
web service to perform. For more complete
mapping you could take a look at some of the
open source REST web service frameworks
available.

Some Open Source web service frameworks We will not be using these existing frameworks,
MARS Curiosity Framework: instead we will be building a simple web
https://github.com/andrea-magni/MARS service server and client from scratch.
mORMot ORM Framework
https://github.com/synopse/mORMot STARTING THE BUILDING OF THE PROGRAM
WiRL RESTful library on the next page we will create the web service
https://github.com/delphi-blocks/WiRL client.

Figure 1: The Web Service Client to be build

Blaise Pascal Magazine 92 2021 61


WEB SERVICE PART 1 Page 3/10

Start with either a VCL or FireMonkey application


1. Add a Panel and align Top
2. Add a Button to this Panel and rename to ButtonGet, align Right
3. Add an Edit to this Panel and rename to EditURL, align Client
4. Add a Memo to the Form and align Client
5. Add a NetHTTPClient to the Form
6. Add a NetHTTPRequest to the Form and link the Client property to NetHTTPClient
7. Add an OnClick event-handler to the ButtonGet
procedure TFormMain.ButtonGETClick(Sender: TObject);
begin
NetHTTPRequest.MethodString := 'GET';
NetHTTPRequest.URL := EditURL.Text;
NetHTTPRequest.Execute();
end;

8. The HTTP GET request is executed asynchronously, which means the


response will appear at some time in the future. When the response arrives the
OnRequestCompleted event-handler of the NetHTTPRequest will be called.
9. Add an OnRequestCompleted event-handler to the NetHTTPRequest
procedure TFormMain.NetHTTPRequestRequestCompleted(const Sender: TObject;
const AResponse: IHTTPResponse);
begin
MemoResponse.Text := AResponse.ContentAsString;
end;

10. Run and test using a website URL, for instance


https://www.blaisepascalmagazine.eu/
11. The GET will return a HTML page

Figure 2: The result of the GET order event

Blaise Pascal Magazine 92 2021 62


WEB SERVICE PART 1 Page 4/10

12. When you use an URL to a REST endpoint from an existing Web Service,
you get JSON data. Try this URLs in the Web Service Client
https://api.discogs.com/artists/457265
13. The result is JSON data, recognizable due to the curly braces {}

Figure 3: The result is JSON data

14. The next step is to create our own Web Service Server

Figure 4: The Web Service Server Gui

Blaise Pascal Magazine 92 2021 63


WEB SERVICE PART 1 Page 5/10

15. We start with the New Item wizard for Web | Web Server Application

Figure 5: starting with the Web Server Appication: New ÚOtherÚWeb


16. This will allow you to create a web server that runs standalone or as a library in Apache (Linux)
or IIS (Windows). It will process HTTP requests and you can write the code on how it should
respond, with plain text, a JSON string, HTML page or even an image or a file.

Figure 6: Standard for Windows


17. For now we go with Windows. We can add Linux support later on.

Blaise Pascal Magazine 92 2021 64


WEB SERVICE PART 1 Page 6/10

Figure 7: Select the type of WebBroker


18. For now we create a stand-alone GUI application. If we run this wizard
again later on we can combine these options into one Project Group and
share the base code files between these options.

Figure 8: VCL
19. VCL is OK

Blaise Pascal Magazine 92 2021 65


WEB SERVICE PART 1 Page 7/10

Figure 9: The port number

20. Test if the default port is not already taken on your machine.
If it is you can Find Open Port or just try another port, such as 8088 or 8888.
21. Save the files into a separate directory and save the Project as WebServiceServerGUI

Figure 10: Run the Web Service Server GUI

Blaise Pascal Magazine 92 2021 66


WEB SERVICE PART 1 Page 8/10

22. Run the Web Service Server GUI


23. Click on Start, this should open the Windows Firewall configuration, depending on your
local network configuration (Private or Public) you can choose to open the port for
private networks only or for public networks (if you have your computer configured as
such). Please note that when opening it up for public networks would mean the port is
also open when you visit an airport.

Figure 11: The Windows Firewall config

24. Make note of the URL that is then opened in the web browser
http://localhost:8080/
25. Run the Web Service Client and open this URL.
26. The :8080 in this URL is the internet port. An internet port is like a door, each door has its
own number. If the port is opened in the firewall, traffic is allowed through.
27. The localhost in this URL translates to a loopback to this machine. It’s translated to a local
IP address (127.0.0.1) that points to the machine you are running on.

Figure 12: Run the Web Service Client and open this URL.

Blaise Pascal Magazine 92 2021 67


WEB SERVICE PART 1 Page 9/10

28. This is the default handler for the Web Server Service
29. Let’s add a new GET handler to the Web Server Service
30. Open the Web Server Service GUI project and open the WebModuleUnit

Figure 13: WebModuleUnit


31. HTTP requests to the Web Server are mapped to WebActionItems (Action Handlers).
Add a new WebActionItem by clicking the three-dots in the property Actions

Figure 14:

32. Modify MethodType to mtGet and PathInfo to /Number


33. Add an OnAction event-handler to this WebActionItem and code a response
procedure TWebModule1.WebModule1WebActionItemNumberGetAction(Sender:
TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
Response.ContentType := 'application/json; charset=UTF-8';
Response.Content := Random(100).ToString;
end;

Blaise Pascal Magazine 92 2021 68


WEB SERVICE PART 1 Page 10/10

34. Run the Web Service Server, and Start it with the Button
35. Now open the Number URL in the Web Service Client
http://localhost:8080/Number
36. Request a couple of random numbers in the Web Service Client

Figure 15: Opening the Number Url

37. By the way, this is valid JSON, because a Number is a primitive


datatype is where no encapsulation or serialization is needed.

Figure 16:
38. See here also for a brief description of JSON structures
https://www.json.org/json-nl.html
You already have the basis for your own Web Service. You can use this code for example to use the
values from your own weather station via GET requests available and displayed in an Android App.

In the following articles, we will change data in the Web Service by adding a PUT, POST and DELETE.
We will also use more complex JSON structures.

You can download the source code for this article from your subscription webpage:
https://www.blaisepascalmagazine.eu/your-downloads/

Blaise Pascal Magazine 92 2021 69


Lazarus Install free version of Page 1/4
TMSWebcore FOR macOS
By Mattias Gärtner starter expert

WEB
macOS free
TMS WebCore tms

Figure 1: Logo

INTRODUCTION:
We have been developing the free version of
TMS WebCore and that worked fine for Windows
and for Linux. macOS was however a problem. Figure 2/3: the warning that is of no use...
Not because we could not install it, but because NOW BACK TO macOS.
of the manifold popping up of warnings and Here you need to prepare for the usual steps:
requests to accept to use your password.
Up to 8 times per install. That is ridiculous. 1. Install your macOS version of Lazarus.
So we decided to find a way to get it done We have tested this with the version
without all that hassle. Apple has still its very 2.0.11(the latest version was not available
own ideas of protecting and User Interface. yet by writing this article…). The version is
I had promised that about three months a go. a so called trunk version, but works no
It’s a long way to Tipperary, an old song and other than 2.010
especially this project needed quite some time.
But we have solved it. Here is the story of how 2. Download the version of TMS Webcore for
to install it. free from our website or this address
http://downloads.blaisepascal.eu/
The version is downloadable for free from: TMSWebcoreLazarusDemoFree1.5.4.zip
http://downloads.blaisepascal.eu/ (See figure 6 at page 1/7 or issue page 71)
TMSWebcoreLazarusDemoFree1.5.4.zip

By the way: now you also can download the 3. You also need to collect your License
latest stable update(no new features only bugs number: it’s for free available at:
https://www.tmssoftware.com/site/
reduction) of Lazarus from: trialkey.asp
https://sourceforge.net/projects/lazarus/
files/Lazarus%20Windows%2064%20bits/
Lazarus%202.0.12/ 4. Now unzip the download to a directory of
lazarus-2.0.12-fpc-3.2.0-win64.exe/download your choice
or go to:
https://www.lazarus-ide.org/ 5. Start Lazarus

(see figure 4 on the next pageÚ2/4 or 71) 6. Go to Package Ú Open Package file (lpk)
Once you have done this we can start the Úselect in the directory of your choice
installation of the package. First of all: the tmswebcorepkgliblaz.lpk .
installation under Win10 responds with a That file will handle the other .lpk files
message of distrust. Don’t worry, simply click on as well. The package window opens.
the more info text. In the next screen you can
simply run it.

Blaise Pascal Magazine 92 2021 70


Lazarus Install free version of New Lazarus 2012 Page 2/4
TMSWebcore FOR macOS
Figure 4: the header of the lazarus pages

Figure 5: Details about the next version of Lazarus

Blaise Pascal Magazine 92 2021 71


Lazarus Install free version of Installing WebCore Page 3/4
TMSWebcore FOR macOS

Figure 6: The zip file

Figure 7: The package container, use install...

7. choose use / install.


Now you will be asked if you want to
rebuild Lazarus.
After that you should be able to see the
tabs of TMS WebCore. (see figure 8)

Figure 8: The installed components overview of TMS

Blaise Pascal Magazine 92 2021 72


Lazarus Install free version of Installing WebCore Page 4/4
TMSWebcore FOR macOS

Now build a small project and compile that.


Immediately you'll be urged to enter your free
code of TMS.

Try to run the project. If it works: that’s all.


Figure 9: The new simple test project Tested with macOS – Big Sur
immediately the license generator pops up

Figure 10: The License generator

Figure 11:
After that you need to
save the license in that
directory

Figure 12: The running App

Figure 13: The reaction to the click


on the button (ShowMessage)

Blaise Pascal Magazine 92 2021 73


ADVERTISEMENT

BLAISE PASCAL MAGAZINE 92


Multi Platform / Object Pascal / Internet / JavaScript / WebAssembly / Pas2Js / Databases
CSS Styles / Progressive Web Apps

L I B R A R Y 2 0 2 0 Android / IOS / Mac / Windows & Linux

89
90
87
88
86
85 51 52 53
84 50 54
49 55 26 27 28
83 29 25
48 56
81 30
24
82 47 9 10 11 57
12 31
80 46 23 8 1
2 13 32 58
78 22 7 3
79 45 14 33
21 4 59
77 44 6
20 5 15 34
75 60
76 43 19 16 35
18 17 61
73 42 36
74
41 37 62
72 40 39 38
71 69 63
Quantum Computing / By Detlef Overbeek
70 67 64 Max Box / Max Kleiner
68 66 65 Fastreport / By Detlef Overbeek
MMX / By Detlef Overbeek and Dennis Zubov
Code Examples / By Detlef Overbeek
New Lazarus PJU Files for Mac By Mattias
Gaertner
Installing a package on MacOs
ALL CODE ABOUT THE USE RegEx / By Michael van Canneyt
Sample Project: Lazarus & Delphi Easter
Holidays
BLAISE PASCAL MAGAZINE Multi Tier a series for the web / By Danny Wind
ALL ISSUES IN ONE FILE Chess / By Detlef Overbeek

Editor in Chief: Detlef Overbeek


BLAISE PASCAL MAGAZINE Edelstenenbaan 21 3402 XA
IJsselstein Netherlands
BLAISE PASCAL MAGAZINE

procedure procedure
var var
begin begin
for I := 1 to 9 do for I := 1 to 9 do
begin Prof Dr.Wirth, Creator of Pascal Programming language begin
... ...
end end
end; end;
Prof Dr.Wirth, Creator of Pascal Programming language Blaise Pascal, Mathematician
[email protected] Prof Dr.Wirth, Creator of Pascal Programming language Blaise Pascal, Mathematician
https://www.blaisepascalmagazine.eu

1 year Subscription+
the new LibStick
(on USB Card - 90 Issues)
€ 70
ex vat / inc. shipment
USB HID support in kbmMW
#2 – 24×7 stability on Win10 Page 1/6
By Kim Bo Madsen
HOW TO IMPROVE STABILITY OF YOUR USB HID
DEVICES ON WIN10
I’ve noticed when attaching a barcode scanner like
the Honeywell 1300g to the USB port of a computer
running Win10, the scanner works perfectly….
for as long as it is being used, or some additional
hours, until power save mode or a Windows house
keeping kicks in.

After then, the only way to get the scanner to work


again, is to disconnect it physically and reconnect it.
Figure 1: In the Windows power configuration control
First I suspected power save mode of the USB panel, which can be opened by running powercfg.cpl
device. It is important to configure the USB devices
that you want running 24×7, to not adhere to
power save modes.

Turning off power saving for USB devices


This can be done a couple of places. I recommend
updating settings for all the places:
Figure 2: Select Change plan settings for your selected power plan:

Figure 3: Select Change advanced power settings

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 75
USB HID support in kbmMW #2 – 24×7 stability on Win10 Page 2/6

Figure 4:
Change USB selective suspend settings to DISABLED
2. On the specific USB driver in device
Figure 6: Locate
management. Some USB device drivers allows
for defining their power save settings. In the device manager, locate the Universal
Serial Bus controllers section. Each of the USB
Open the device manager hub entries usually have power save options
you can tune or turn off.
Do that for at least the USB hub which you
connected the device to, but I recommend to
do it for all USB hubs to avoid problems if you
one day choose to plug in the USB device into
another port on your computer, which may be
driven by a different built in USB hub.

Figure 5: Open the device manager

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 76
USB HID support in kbmMW #2 – 24×7 stability on Win10 Page 3/6

Right click the USB hub entries, one by one, BUT IT DIDN'T REALLY SOLVE THE PROBLEM
and click Properties After disabling power saving features for the
USB (which is a requirement to do to get a
stable, always running USB device).
I however still experienced problems when the
devices were not used over night.

At first I suspected the kbmMW HID code to be


the culprit, but it turned out it was not.

Instead it turns out that the default Microsoft


driver for Barcode scanners configured in HID
mode, simply dies after some hours of non
use. The exact reason for it to die, is unknown
to me, but I can guess it has to do with some
Win10 scheduled operations, like updates,
system clean up and even power save modes
that may be triggered even though we have
Figure 7: Properties tried our best to disable those.

Figure 8: Alter the setting

Make sure to uncheck “Allow the computer to


turn of this device to save power”.

If you do not see the Power Management tab,


the device do not provide additional features
for setting its power management, and you can
ignore it.

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 77
USB HID support in kbmMW #2 – 24×7 stability on Win10 Page 4/6

Figure 9: Pos HID Barcode Sanner

As you can see, there is a small yellow triangle


on the POS HID Barcode scanner. It is an
indicator of that the Windows HID driver has
stopped communicating with the device. The
device is actually very much alive, and I have
verified that with USB debug/trace/scanner
software, but the driver simply died, and will
not “undie” until the device is reconnected.

Searching high and low for a solution to this


problem found no real solution, using the
driver default used by Windows 10.

However the salvation came, when I


discovered that Win10 also comes with the
older Win7 HID driver installed out of the box.
And that driver does not die randomly.

So the solution is to right click the HID device,


click on the Driver tab, and select Update
driver. Then select “Browse my computer for
driver software”

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 78
USB HID support in kbmMW #2 – 24×7 stability on Win10 Page 5/6

Browse the computer for drivers

Figure 10: Browse the computer

Update drivers - Logitech USB Input Device

Browse your computer for drivers

Search for drivers in this location

Browse
Include subfolders

Let me choose from a list of available drivers on my computer


This list shows available drivers that are compatible with the device, as well as all
drivers in the same category as the device

Figure 11: Searching drivers Next Cancel

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 79
USB HID support in kbmMW #2 – 24×7 stability on Win10 Page 6/6

Update drivers - Logitech USB Input Device

Select the device driver you want to install for the hardware

Select the manufacturer and model of your hardware device, then click Next.
Click Have Disk / CD if an installation disk came with the hardware

The driver is digitally signed. Has floppy disk / CD


Tell me why driver signings are important

Next Cancel

Figure 12: Found

Let it install and voila, your HID driver is now


stable and your device can run 24×7 on
Win10.

I have chosen to do this change also for USB


connected magnetic stripe readers, even
though they seemingly do not use the unstable
Win10 driver from outset, but making the
change to the Win7 driver (which works for
those magnetic stripe readers too), makes me
more confident in those also running 24×7
and I have not had an issue with them with the
older driver.

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 80
DELPHI REVELATIONS #6 – DELPHI BUGS – GENERICS COMPILER BUG 1/2
By Kim Bo Madsen
...
TMyObject = class
This blog post is about a new discovery I have private
made in Delphi, and the way to circumvent it. public
destructor Destroy; override;
THE GENERICS COMPILER BUG end;
I had a weird issue in kbmMW SmartBinding’s ...
implementation
DefineData feature, which is used as a way to live
push external data into kbmMW’s binding ...
destructor TMyObject.Destroy;
mechanism, making it possible to update visual begin
components on the fly based on external data. inherited;
end;

procedure TForm6.FormCreate(Sender: TObject);


var o:TMyObject;
begin
o:=TMyObject.Create;
Binding.DefineData('object',o,true);
o:=TMyObject.Create;
The DefineData method exists in 4 different Binding.DefineData('object',o,true);
overloaded variations, 2 of generic types and Binding.UndefineAllData;
2 of non generic types. end;
function DefineData(const AName:string; const AData:IkbmMWBindingData):TValue; overload;

function DefineData(const AName:string; const AData:TValue; const AManaged:boolean = false):TValue; overload;

function DefineData<T:class>(const AName:string; const AData:T):TValue; overload;

function DefineData<T>(const AName:string; const [ref] AData:T; const AAsReference:boolean):TValue; overload;

DefineData can be told to manage the data Finally UndefineAllData removes all data
provided for it, meaning it is responsible for definitions regardless of names. The second
freeing the data when it is no longer used by instance of TMyObject ought to disappear
the binding framework, which is a powerful here, but alas it did not.
way to leave the responsibility of the lifetime
of the data to SmartBind ….. if it only worked! So OBVIOUSLY there must be a bug in
I discovered that despite my best efforts, DefineData and UndefineAllData.
the data were not automatically freed.
But no, that is not the case.
I looked high and low to made sure that the
intricate internal routines handling all this,
The problem in this case is that the compiler
actually worked, before I realized what the
chooses the wrong overloaded method when
problem was.
it compiles the code.
First some test code showing the use of
DefineData where I noticed it failing:
Stepping into the code, I realised that I
(See right top). stepped into the one with this signature:
function DefineData<T>(const AName:string; const [ref] AData:T; const AAsReference:boolean):TValue;

Basically I create a simple object, defined it to Which you can see is a generic version, and
SmartBind with the argument true, thus should not be selected unless I had used
meaning that SmartBind must take the syntax: Únext page
ownership of the object instance.
Then I created a new one and defined that
under the same name as the previous one,
which should result in the previous TMyObject
should be freed, which did not happen.

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 81
DELPHI REVELATIONS #6 – DELPHI BUGS – GENERICS COMPILER BUG 2/2

Binding.DefineData<TObject>('object',o,true);

It should have selected the one with the


signature:
function DefineData(const AName:string; const AData:TValue; const AManaged:boolean = false):TValue;

Impressively the compiler actually figured out


Usually the compiler would issue a compile
(by the argument given for AData) that the
error, in case multiple overloaded methods
generic type of DefineData should be
matched the parameter list, but not in this
DefineData<TMyObject>. case, which is not a bug, but correct behaviour.
The bug is that it selects the wrong one.
That is impressive, but absolutely not intended.
The compiler should never deduce the generic
As it is calling an incorrect method, it is a rather
type based on the type of a T argument , but
serious bug, which needs to be fixed.
only on what has been given as the type
I have for the moment only tested this issue in
between the generics brackets <> .
10.3.
The only way to circumvent this bug is to make
sure that there are no two methods l
llo asca
(generics or not) that have potentially
compatible argument lists while having the
same method name.

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 82
Bumblebees fly at a speed of 54 km
COMPONENTS
DEVELOPERS 4
Bumblebees are also capable of buzz pollination, in
which they dislodge pollen from the anthers by creating
a resonant vibration with their flight muscles.

In at least some species, once a bumblebee has visited


a flower, it leaves a scent mark on it. This scent mark
deters bumblebees from visiting that flower until the
scent degrades.
This scent mark is a general chemical bouquet that
bumblebees leave behind in different locations (e.g.
nest, neutral, and food sites), and they learn to use this
bouquet to identify both rewarding and unrewarding
flowers, and may be able to identify who else has
visited a flower.
Bumblebees rely on this chemical bouquet more when
Biting open the stem of a flower... the flower has a high handling time, that is, where it
...and using its tongue to drink the nectar. takes a longer time for the bee to find the nectar once
inside the flower.
Bumblebees generally visit flowers that exhibit the bee
pollination syndrome and these patches of flowers may Once they have collected nectar and pollen, female
be up to 1–2 km from their colony. They tend to visit the workers return to the nest and deposit the harvest into
same patches of flowers every day, as long as they brood cells, or into wax cells for storage.
continue to find nectar and pollen there, a habit known Unlike honeybees, bumblebees only store a few days'
as pollinator or flower constancy. worth of food, so are much more vulnerable to food
While foraging, bumblebees can reach ground speeds of shortages. Male bumblebees collect only nectar and do
up to 15 m/s (54 km/h). so to feed themselves. They may visit quite different
flowers from the workers because of their different
Bumblebees use a combination of colour and spatial nutritional needs.
relationships to learn which flowers to forage from.
They can also detect both the presence and the pattern Asynchronous flight muscles
of electric fields on flowers, which occur due to Bees beat their wings about 200 times a second.
atmospheric electricity, and take a while to leak away Their thorax muscles do not contract on each nerve
into the ground. firing, but rather vibrate like a plucked rubber band.
They use this information to find out if a flower has This is efficient, since it lets the system consisting of
been recently visited by another bee. muscle and wing operate at its resonant frequency,
Bumblebees can detect the temperature of flowers, as leading to low energy consumption.
well as which parts of the flower are hotter or cooler Further, it is necessary, since insect motor nerves
and use this information to recognise flowers. generally cannot fire 200 times per second.
After arriving at a flower, they extract nectar using their These types of muscles are called asynchronous
long tongues ("glossae") and store it in their crops. muscles and are found in the insect wing systems in
Many species of bumblebees also exhibit "nectar families such as Hymenoptera, Diptera, Coleoptera,
robbing": instead of inserting the mouthparts into the and Hemiptera. Bumblebees must warm up their
flower in the normal way, these bees bite directly bodies considerably to get airborne at low ambient
through the base of the corolla to extract nectar, temperatures.
avoiding pollen transfer. Bumblebees can reach an
internal thoracic
A bumblebee "nectar robbing" a flower:Pollen is temperature of 30 °C (86 °F)
removed from flowers deliberately or incidentally by using this method.
bumblebees. Incidental removal occurs when
bumblebees come in contact with the anthers of a
flower while collecting nectar. When it enters a flower,
the bumblebee's body hairs receive a dusting of pollen
from the anthers. In queens and workers this is then
groomed into the corbiculae (pollen baskets) on the
hind legs where it can be seen as bulging masses that
may contain as many as a million pollen grains.
Male bumblebees do not have corbiculae and do not
James Lindsey at Ecology of
purposively collect pollen. Commanster, CC BY-SA 2.5,
via Wikimedia Commons

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 84
(advertisement)
kbmMW Professional
& Enterprise Edition v. 5.14.00 released!
COMPONENTS
DEVELOPERS 4
Notice that kbmMemTable v. 7.86.00 or Important notes (changes that may break existing code)

newer is a prerequisite to this update. * Changed default SQLite memo field type to CLOB.
If preprocessor conditional KBMMW_FIX_SQLITE_MEMO_BUG is
This is a combined bugfix and selected new features defined, then CreateOrUpgrade will automatically attempt modifying
release.The release includes: existing tables old MEMO status to CLOB. Prevents unintentional
interpretation of numeric look a like values as numerics.
New stuff
New HTTP and kbmMW server status message - Added support for status methods in
handling support in Smart services kbmMWCustomSmartService and
kbmMWCustomHTTPSmartService. Status methods are smart
— New support for methods that are only triggered when an error or warning status
TkbmMWGenericMagneticStripeReaderHID and is happening. They take both kbmMW native status codes and
TkbmMWGenericBarcodeReaderHID HTTP status codes.
Updated RESTFishFact demo to show examples of how to use.
— New support for pivot based counters in the
- Added QueuedAfterRun and QueuedAfterEnd methods to
ORM kbmMWScheduler.
— New support for transport native file sending for - Added ConcatBytes and BytesZ2String to
HTTP.Sys transport kbmMWPlatformMarshal.
— New support for automatic GZIP compression of - Added global kbmMWCoalesce and kbmMWIsSameVariants
responses from HTTP Smart services global functions in kbmMWGlobal.pas.
— Several feature improvements and fixes. - Added internal thread locking to TkbmMWMemoryStream.
- Added DeleteByName, IndexOfvalue, ContainsValue to
Please check the end of this post for a detailed
TkbmMWHTTPCustomValues.
change list. - Added new TkbmMWMimeTypes class to kbmMWHTTPUtils.pas.
Supports specifying if a mimetype is compressible.
Professional and Enterprise Edition is available for all - Updated compiletool to optionally allow creation of project files
with a current active SAU. If your SAU has run out, for non installed compilers.
please visit our shop to extend it with another 12 - Improved HID support with
months. TkbmMWGenericMagneticStripeReaderHID,
TkbmMWGenericBarcodeReaderHID and added various more
methods like Manufacturers, Products and
Community Edition (CE) can be used as a 60 day ManufactorersAndProducts to extract basic data.
trial, alternatively as a free product, provided the - Added support for pivot based counters in the ORM and
license is followed. connection pool.
Please read license.txt file for details. CE supports a - Added support for transport native file sending for HTTP.Sys
large subset of the Enterprise Edition features, but transport. Will automatically trigger when using
may have technical and artificial limitations in certain HTTPResponseFromFile.
- Added support for automatic GZIP compression of responses
areas. It only supports a specific Delphi/Win32 SKU,
from HTTP Smart services, provided client announce support of it
produce Win32 executables and do not include in call.
source.
Fixes
Please visit - Fixed kbmMWDebugMemory compilation.
https://portal.components4developers.com to - Fixed precise scheduled event shutdown bug.
download. - Fixed SQL rewriting of ALTER TABLE ALTER/MODIFY COLUMN
for ANSI92 and subsequently for IB, MYSQL and ORACLE.
- Fixed exception in kbmMWCustomDataset.pas when
kbmMW is the premiere n-tier product for Delphi, attempting to run nil cursor thru a piped kbmSQL statement.
C++Builder and FPC on Win32, Win64, Linux, Java, - Improved SmartBinding, fixed bugs and stability.
PHP, Android, IOS, .Net, embedded devices, - Fixed SmartBinding bugs for Android.
websites, mainframes and more. - Fixed bugs in kbmMWDateTime related to local date conversion.
- Fixed bug in TkbmMWTCPIPIndyMessagingClientTransport which
Please visit http://www.components4developers.com would cause package data corruption upon IsConnected checking
from a different thread.
for more information about kbmMW.
Changes/minor additions
Components4Developers is a company established in - Refactored and introduced kbmMWCore.pas
1999 with the purpose of providing high quality kbmMWCore.pas amongst others contains TkbmMWInterlocked.
development tools for developers and enterprises. - Added a number of KBMMW_TRANSPORTSTREAM_PARAM_xxxx
The primary focus is on SOA, EAI and systems constants for setting up transport stream parameter options.
integration via our flagship product kbmMW. - Changed SynchronizedAfterRun and SynchronizedAfterEnd back
to not queueing.
- Changed default SQLite memo field type to CLOB.If preprocessor
kbmMW is currently used as the backbone in conditional KBMMW_FIX_SQLITE_MEMO_BUG is defined, then
hundreds of central systems, in hospitals, courts, createOrUpgrade will automatically attempt modifying existing
private, industries, offshore industry, finance, tables old MEMO status to CLOB. Prevents unintentional
telecom, governments, schools, laboratories, interpretation of numeric look a like values as numerics.
rentals, culture institutions, FDA approved medical - Improved TkbmMWPathMatcher to handle escaped characters.
devices, military and more. Will allow for $ and ^ in URL paths for example.
Escape by backslash.
- Improved support for IInterface in kbmMWRTTI.pas

Blaise Pascal Magazine 92 2021 COMPONENTS


DEVELOPERS 4 85
Bernie, Public domain, via Wikimedia Commons

KBMMW PROFESSIONAL AND ENTERPRISE EDITION


V. 5.14 RELEASED!
· New HTTP and kbmMW server status message handling
● RAD Studio XE5 to 10.4.1 Sydney supported support in Smart services
● Win32, Win64, Linux64, Android, IOS 32, IOS 64 and · New support for TkbmMWGenericMagneticStripeReaderHID
OSX client and server support and TkbmMWGenericBarcodeReaderHID
● Native high performance 100% developer defined
application server · New support for pivot based counters in the ORM
● Full support for centralized and distributed load · New support for transport native file sending for HTTP.Sys
balancing and failover transport
● Advanced ORM/OPF support including support of
existing databases
· New support for automatic GZIP compression of responses
from HTTP Smart services
● Advanced logging support
● Advanced configuration framework · Several feature improvements and fixes.
● Advanced scheduling support for easy access to
multithread programming · More features improvements and fixes.
● Advanced smart service and clients for very easy
publication of functionality Please visit
● High quality random functions. http://www.components4developers.com
● High quality pronouncable password generators. for more information about kbmMW
● High performance LZ4 and Jpeg compression
● Complete object notation framework including full
● High speed, unified database access (35+ supported
support for YAML, BSON, Messagepack, JSON and XML
database APIs) with connection pooling, metadata and
● Advanced object and value marshalling to and from
data caching on all tiers
YAML, BSON, Messagepack, JSON and XML
● Multi head access to the application server, via REST/AJAX,
● High performance native TCP transport support
native binary, Publish/Subscribe, SOAP,
● High performance HTTPSys transport for Windows.
XML, RTMP from web browsers, embedded devices, linked
● CORS support in REST/HTML services.
application servers, PCs, mobile devices, Java systems
● Native PHP, Java, OCX, ANSI C, C#, Apache Flex client
and many more clients
support!
● Complete support for hosting FastCGI based applications
kbmMemTable is the fastest and most feature rich in (PHP/Ruby/Perl/Python typically)
memory table for Embarcadero products. ● Native complete AMQP 0.91 support (Advanced Message
● Easily supports large datasets with millions of records Queuing Protocol)
● Easy data streaming support ● Complete end 2 end secure brandable Remote Desktop with
● Optional to use native SQL engine near realtime HD video, 8 monitor support,
● Supports nested transactions and undo texture detection, compression and clipboard sharing.
● Native and fast build in M/D, aggregation/grouping, ● Bundling kbmMemTable Professional which is the fastest
range selection features and most feature rich in memory table for Embarcadero
● Advanced indexing features for extreme performance products.

COMPONENTS
DEVELOPERS 4 DX
EESB, SOA,MoM, EAI TOOLS FOR INTELLIGENT SOLUTIONS. kbmMW IS THE PREMIERE N-TIER PRODUCT FOR DELPHI / C++BUILDER

You might also like