Improver 4

The Improver is a culture concept to improve our life with picture, text and sound.

Improver Sign – The 4 Elements

All songs you can find at:

https://sourceforge.net/projects/maxbox/files/maXbox_Archive/Improver/Improver_4_Edition_2021.zip/download

Play the tunes

  1. Beat the Blues
Beat the Blues G9_1_Vision

2. Play Chess:

Play Chess

3. Cary Copper (White magic):

Copper White Magic

4. Eat Garlic (NowAge)

Nowage Garlic

5. Exerce de Meditation

Meditation piano

6. Practise running (Japan)

Japan Running Shotokai

7. Bett von Nord nach Süd – Zeitraum

Zeitraum Bett

8. Olemos Bruja

Olemos Bruja

9. Listen white noise (Lord of Darkness)

Lord of darkness white noise
Cite du Train 2013
SNCF Quadri-Courant CC 40110 Nice
Capitole Capital
Austria 2008
TEE Gottardo RAe II
TEE Gottardo
Rheingold Sonderfahrt Poster
SBB Katakomben 2015
On SoundCloud

Bella Austria 2021

Holydays not from a Cat a log in Carinthia at August 2021

Second Edition of Cat a Log

Strandpromenade Pörtschach (Magnum Foto Edition von Silvia)

Mein Lieblingsfoto entstand am 31.8.2021 um 18 Uhr in der Wechselzone von Regen zu Wind und Sonne, die noch und noch ihr Handwerk aussendet.

bei Shamandra vor Klagenfurt
Exotic TEE’s

Badenweiler

Das herzhafte und feine Badenweiler trotzt den stürmischen Zeiten. – The hearty and fine Badenweiler defies the stormy times.

Das gute und edle Badenweiler trotzt in stürmischen Zeiten. – The good and noble Badenweiler defies stormy times.

Das gute und edle Badenweiler trotz in stürmischen Zeiten. – The good and noble Badenweiler despite in stormy times.

Badenweiler is a health resort and spa in the Breisgau-Hochschwarzwald district of Baden-Württemberg, Germany, historically in the Markgräflerland. It is 28 kilometers by road and rail from Basel, 10 kilometers from the French border, and 20 kilometers from Mulhouse.

In the wellness oasis further information CASSIOPEIA THERME Thermal baths, sauna area, Roman-Irish bath & wellness oasis Soothing thermal water, a special kind of sauna pleasure, Roman bathing culture, international wellness offers – all of this makes the Cassiopeia Therme so unique.

Therme ca. 26° Celciius

XML Reloaded

There are lot of possibilities if you’re in need to parse or write XML files:

Now here comes another one: VerySimpleXML – a lightweight, one-unit XML reader/writer in under 500 600 lines of code. Use it for small well-formed XML files (like configuration files, etc.).

So we use a configuration file to parse:

http://www.softwareschule.ch/examples/1045_laztest.xml

<CONFIG>
<ProjectOptions>
 <Version Value="7"/>
  <General>
   <Flags>
    <LRSInOutputDirectory Value="False"/>
   </Flags>
   <MainUnit Value="0"/>
   <TargetFileExt Value=""/>
   <Title Value="TestXMLReder"/>
   <Icon Value="0"/>
   <UseXPManifest Value="True"/>
   <ActiveEditorIndexAtStart Value="0"/>
  </General>
  <VersionInfo>
   <ProjectVersion Value=""/>
  </VersionInfo>
 <PublishOptions>
   <Version Value="2"/>
   <IgnoreBinaries Value="False"/>
   <IncludeFileFilter Value="*.
           (pas|pp|inc|lfm|lpr|lrs|lpi|lpk|sh|xml)"/>
   <ExcludeFileFilter Value="*.(bak|ppu|ppw|o|so);*~;backup"/>
 </PublishOptions>
 <RunParams>
  <local>
   <FormatVersion Value="1"/>
   <CommandLineParams Value="/home/alexs/work/fpc/demo10-
                                      xml/TestXMLReder.lpi"/>
   <LaunchingApplication PathPlusParams="/usr/X11R6/bin/xterm -T
           'Lazarus Run Output' -e $(LazarusDir)/tools/runwait.sh
           $(TargetCmdLine)"/>
  </local>
 </RunParams>

We changed class name to reflect unit naming (class is now called
TXmlVerySimple instead TVerySimpleXml) and to avoid single namespace conflict I set CL.AddClassN(CL.FindClass(‘TOBJECTlist’),’TXmlNodeListSimple’); and TXmlNodesimple to it:

procedure TXMLRederFormTreeView1Click(Sender: TObject);
var   Node:TXmlNodesimple; //TDOMNode;
      Item:TListItem;
      i:Integer;
begin
  Edit1.Text:=''; Edit2.Text:='';

  if not Assigned(TreeView1.Selected) then exit;
  Node:= TXmlNodesimple(TreeView1.Selected.Data);
  if not Assigned(Node) then Exit;

  Edit1.Text:=Node.NodeName;
  Edit2.Text:=Node.parent.nodename;
  ListView1.items.BeginUpdate;
  ListView1.Items.Clear;

  if Assigned(Node.Attributes) then
    for i:=0 to Node.Attributes.count-1 do begin
    //if node.ChildNodes.count = 0 then Exit;
       Item:=ListView1.Items.Add;
       TXMLAttribute(Node.attributes[i]).name;
       Item.Caption:= TXMLAttribute(Node.Attributes[i]).name;
       Item.SubItems.Add(TXMLAttribute(Node.Attributes[i]).Value);
       writeln(Node.text);
    end;
  ListView1.items.EndUpdate;
end;

VerySimpleXML supports just a subset of the XML specification

  • load and save from stream or file
  • nodes, childs and attributes
  • UTF-8 and ANSI encoding
  • compact output by setting Xml.Ident := ”;
  • method chaining
  • Parse, save and load files
procedure DoFill(AOwner:TTreeNode; Node:TXmlNodesimple {TDOMNode});
var i: integer;
    AItem:TTreeNode;
begin
  if not Assigned(Node) then exit;
  for i:= 0 to Node.ChildNodes.Count-1 do begin
     AItem:=TreeView1.Items.AddChild(AOwner,
                  TXMLNodesimple(Node.ChildNodes[i]).nodename);
     AItem.Data:= Node.ChildNodes.items[i];
     if not Assigned(TreeView1.Selected) then
       TreeView1.Selected:= AItem;
     DoFill(AItem, TXMLNodesimple(Node.ChildNodes[i]));
  end;
end;

XML-Spec for “well-formed” files requires the attributes wrapped in quotation marks.
VerySimpleXML parses well even without them (if they consist of a single word).

The other non-XML-standard behavior of VerySimpleXML is the usage of the < and > tags inside an attribute or text:
XML spec requires you to write &lt; and &gt; but VerySimpleXML parses well if wrapped in quotation marks.

procedure TXMLRederFormParseDoc;
begin
  //TreeView1:= TTreeView.Create(self);
  TreeView1.Selected:=nil;
  TreeView1.Items.BeginUpdate;
  TreeView1.Items.Clear;
  //DoFill(nil, TDOMNode(FDoc));
  DoFill(nil, TXMLNodesimple(FDoc.root));
  TreeView1.Items.EndUpdate;
  TXMLRederFormTreeView1Click(nil);
  //Treeview1.FullExpand();
end;

Script can be found: http://www.softwareschule.ch/examples/xmldemo2.txt

And a useful blog: http://blog.spreendigital.de/2011/11/10/verysimplexml-a-lightweight-delphi-xml-reader-and-writer/

Some simple usage example:

uses Xml.VerySimple;
 
var
  Xml: TXmlVerySimple;
  Node, Child: TXmlNode;
begin
  Xml:= TXmlVerySimple.Create;
  Xml.LoadFromFile('example.xml');
  Xml.Root.Find('book', 'id', 'bk102').Find('author').Text := 'Dein, Carol Max';
  Node:= Xml.Root.AddChild('book');
  Child:= Node.AddChild('author');
  Child.Text:= 'Barger, Al';
  Child.Attribute['type']:= 'topseller';
  Node.AddChild('title').SetAttribute('lang','en').SetText('A big View');
  Xml.SaveToFile('output.xml');
  Xml.Free;
end;

The Xml.Root.Find() has 3 different signatures, cause in maXbox function overloading don’t works.

{ RegisterMethod(‘Function Find( Name : String) : TXmlNode;’);
RegisterMethod(‘Function Find1( Name, Attribute : String) : TXmlNode;’);
RegisterMethod(‘Function Find2( Name, Attribute, Value : String) : TXmlNode;’);
RegisterMethod(‘Function FindNodes( Name : String) : TXmlNodeList’);
}

Simple Example in a Script

First we define the XML file as a const:

const TESTCONST = 
 '<?xml version="1.0" encoding="UTF-8"?>'
+'<book>                                '
+' <name>A Song of Ice and Fire</name>  '
+' <author>George R. R. Martin</author> '
+' <language>English</language>         '
+' <genre>Epic fantasy</genre>          '
+'</book>                               ';

Then we call the routine to add a child with a new book:

procedure XML_testroutine2;
var
  Xml: TXmlVerySimple;
  Node, Child: TXmlNodeSimple;
  strm: TStream;
begin
  Xml:= TXmlVerySimple.Create;
  strm:= TStringStream.Create('');
  StringtoStream(TESTCONST, strm)
  Xml.LoadFromStream(strm);
  writeln(itoa(strm.size))
  writeln(xml.text)
  Node:= Xml.Root.AddChild('bookdetail');
  Child:= Node.AddChild('author');
  Child.Text:= 'Kleiner, Al';
  Child.Attribute['type']:= 'topseller';
  Node.AddChild('title').SetAttribute('lang','en').SetText('A big View');
  Xml.SaveToFile(exepath+'examples\bookout.xml');
  Xml.Free;
  strm.Free;
  openfile(exepath+'examples\bookout.xml');
end;

Let’s take a look at the modified bookout.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<book>
  <name>A Song of Ice and Fire</name>
  <author>George R. R. Martin</author>
  <language>English</language>
  <genre>Epic fantasy</genre>
  <bookdetail>
    <author type="topseller">Kleiner, Al</author>
    <title lang="en">A big View</title>
  </bookdetail>
</book>

This is a simple XML document. You can understand the data, by just looking at the document.

https://beginnersbook.com/2018/10/xml-example/

Language Config in XML

The beta of Hirsute Hippo (to become 21.04 in April) has now been released, and is available for download. Also for Kubuntu, KDE, and Qt developers.

TEE-Time

Historic train ride for the double anniversary of the RAe TEE II 1053 and SBB Historic The RAe TEE was not only the SBB’s most comfortable train – it was the only one with a separate ladies’ toilet with a make-up corner – it was also the first train in Europe that could run freely under all four electricity systems in Europe.

It also represented a high point of Swiss mechanical engineering and is celebrating its 60th anniversary this year. For the 60th birthday of the international luxury train RAe TEE II 1053, treat yourself to a round trip from Olten at the anniversary price. As in the past, you can refresh yourself at the bar or eat in the dining car.

26.06.2021

TEE Reloaded

Those who are nostalgic about the railways will remember times long past – and everyone who also travels across borders by train should be happy: The once legendary Trans-Europ-Express (TEE) could come back. At least that is what Federal Transport Minister Andreas Scheuer (CSU) wants to initiate on Monday at the EU Transport Ministers’ Conference. This could make rail travel over long distances within Europe more attractive.

The system had already existed for 30 years, it was discontinued in 1987. The sets used consisted exclusively of air-conditioned first-class wagons, speeds of up to 200 kilometers per hour were possible on upgraded routes. The trains of the various European railway companies were painted uniformly in wine red and beige. TEE connections existed between the states of the European Economic Community as well as Austria and Switzerland. They were replaced by the not so comfortable Eurocity.

07.08.2021 TEE Emmental II

Kraftwerk’s minimalist 1976 tribute to the pleasure of long-distance train journeys will likely be familiar to music fans, but to a generation of Europeans, Trans Europe Express remains a byword for fast, luxurious international travel.

Replaced by the patchy and somewhat less glamorous EuroCity brand in 1987, the stylish red and ivory TEE trains were a response to the growth of air travel and the private car in the late 1950s.

In Nieuw-Vennep (the Netherlands) a ‘pop-up’ museum has been created with TRANSPORT as its theme. It is a consolidation of eleven groups all aiming to preserve heritage of forms of mobility They organised themselves as ‘Stichting Nederlands Transport Museum’ in 2017.

DB 103 180–6, SNCF 15013, SBB 11160, SNCB 1801, ÖBB 6010.08, Basel 1977, Digitized from Photo: SBB
DB 103 193–9, SNCF 15015, SBB 11161, SNCB 1801, ÖBB 6010.07 — ModelMax

Python4Delphi

//////////////////////////////////////////////////////////////////////////////

Python4Delphi

___________________________________

maXbox Starter86 – Python for Delphi with Python4Delphi

In a future world you can decide belonging to SkyNet or Darknet, but you can not find the difference between an Android or Avatar cause humans doesn’t exist anymore.

Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). A DLL could be for example the ‘python37.dll’. They let you almost easily execute Python scripts, create new Python modules and new Python types. You can create Python extensions as DLLs and much more like scripting or automating your console. P4D provides different levels of functionality:

  • Low-level access to the Python API
  • High-level bi-directional interaction with Python
  • Access to Python objects using Delphi custom variants (VarPyth.pas)
  • Wrapping of Delphi objects for use in Python scripts using RTTI (WrapDelphi.pas)
  • Creating Python extension modules with Delphi classes, records and functions
  • Generate Scripts in maXbox from a Python engine.

P4D makes it, after some (tough) studies, very easy to use Python as a scripting language for Delphi applications. It also comes with an extensive range of demos and useful (video) tutorials.

So a very first simple approach is to call the Python dll without a wrapper or mapper e.g. call the copyright function:

//if fileExistst(PYDLLPATH+ ‘python37.dll’;

function getCopyRight: PChar;

external ‘Py_GetCopyright@C:\maXbox\EKON25\python37.dll stdcall’;

Then we call the function with a pre-test:

function IsDLLOnSystem(DLLName:string): Boolean;

var ret: integer;

good: boolean;

begin

ret:= LoadLibrary(pchar(DLLNAME));

Good:= ret>0;

if good then FreeLibrary(ret);

result:= Good;

end;

if isDLLOnSystem(PYDLLPATH+PYDLLNAME) then begin

showmessage(‘py dll available’);

writeln(getCopyRight)

end;

Copyright (c) 2001-2019 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.

We also use to invoke a Python script as an embedding const and use the dll functionality of Import(‘PyRun_SimpleString’);

procedure InitSysPath;

var _path: PPyObject;

const Script =

‘import sys’ + sLineBreak+

‘sys.executable = r”%s”‘ + sLineBreak+

‘path = sys.path’ + sLineBreak+

‘for i in range(len(path)-1, -1, -1):’ + sLineBreak+

‘ if path[i].find(“site-packages”) > 0:’ + sLineBreak+

‘ path.pop(i)’ + sLineBreak+

‘import site’ + sLineBreak+

‘site.main()’ + sLineBreak+

‘del sys, path, i, site’;

begin

if VenvPythonExe <> ” then

ExecString(AnsiString(Format(Script, [VenvPythonExe])));

_path := PySys_GetObject(‘path’);

if Assigned(FOnSysPathInit) then

FOnSysPathInit(Self, _path);

end;

How to use Python4Delphi

The best way to learn about how to use P4D is to try the extensive range of demos available. Also studying the unit tests for VarPyth and WrapDelphi can help understand what is possible with these two units and the main PythonEngine.pas.

Lets start with the VarPyth.pas unit.

This allows you to use Python objects like COM automation objects, inside your Delphi source code. This is a replacement, bugfixed of the former PythonAtom.pas that uses the new custom variant types introduced since Delphi6.

You may use these Python Variants in expressions just as you would any other Variants or automation e.g.:

var

a: Integer; v: Variant;

begin

v:= VarPythonEval(‘2 ** 3’);

a:= v;

The functions provided by this unit VarPyth.pas are largely self-explanatory.

What about the WrapDelphi.pas unit?

You can use P4D to create Python extension modules too that expose your own classes and functions to the Python interpreter. You may package your extension with setuptools and distribute it through PyPi. So if you have an existing object or unit in Delphi that you’d like to use in Python but you don’t want to modify that object to make it Python-aware, then you can wrap that object just for the purposes of supplying it to Python with a package.

Using TPyDelphiObject you can wrap any Delphi object exposing published properties and methods. Note that the conditional defines TYPEINFO and METHODINFO need to be on.

As an example, if you have an existing Delphi class simply called TRGBColor:

TRGBColor = class

private

fRed, fGreen, fBlue: Integer;

public

property Red: read fRed write fRed;

property Green: read fGreen write fGreen;

property Blue: read fBlue write fBlue;

end;

You want to use Color within some Python code but you don’t want to change anything about the class. So you make a wrapper inherited from TPyObject that provides some very basic services, such as getting and setting attributes of a Color, and getting a string representation:

TPyColor = class(TPyObject)

private

fColor: TRGBColor;

public

constructor Create( APythonType: TPythonType ); override;

// Py Basic services

function GetAttr(key: PChar): PPyObject; override;

function SetAttr(key: PChar; value:PPyObject): Integer; override;

function Repr: PPyObject; override;

end;

The project in the subdirectory Delphi generates a Python extension module (a DLL with extension “pyd” in Windows) that allows you to create user interfaces using Delphi from within Python. The whole VCL (almost and maybe) is wrapped with a few lines of code! The small demo TestApp.py gives you a flavour of what is possible. The machinery by which this is achieved is the WrapDelphi unit.

The subdirectory DemoModule demonstrates how to create Python extension modules using Delphi, that allow you to use in Python, functions defined in Delphi. Compile the project and run test.py from the command prompt (e.g. py test.py). The generated pyd file should be in the same directory as the Python file. This project should be easily adapted to use with Lazarus and FPC.

The subdirectory RttiModule contains a project that does the same as the DemoModule, but using extended RTTI to export Delphi functions. This currently is not supported by FPC.

The unit PythonEngine.pas is the main core-unit of the framework. You are responsible for creating one and only one TPythonEngine. Usually you just drop it on your main form. Most of the Python/C API is presented as member functions of the engine.

type

TPythonVersionProp = record

DllName : string;

RegVersion : string;

APIVersion : Integer;

end;

Py_BuildValue := Import(‘Py_BuildValue’);

Py_Initialize := Import(‘Py_Initialize’);

PyModule_GetDict := Import(‘PyModule_GetDict’);

PyObject_Str := Import(‘PyObject_Str’);

PyRun_String := Import(‘PyRun_String’);

PyRun_SimpleString := Import(‘PyRun_SimpleString’);

PyDict_GetItemString := Import(‘PyDict_GetItemString’);

PySys_SetArgv := Import(‘PySys_SetArgv’);

Py_Exit := Import(‘Py_Exit’);





Let’s take a last look at the functionality of PyRun_SimpleString mentioned first within the const script.

http://www.softwareschule.ch/examples/1016_newsfeed_sentiment_integrate2.txt

PyRun_SimpleString: function(str: PAnsiChar): Integer; cdecl;

We see that we have to pass a PAnsiChar in cdecl convention and map to ExecString (PyRun_String:):

procedure TPythonEngine.ExecString(const command : AnsiString);

begin

Py_XDecRef( Run_CommandAsObject( command, file_input ) );

end;

_PIC: tutor86_pythondll_spy.png

Conclusion

The P4D library provides a bidirectional bridge between Delphi and Python. It allows Delphi applications to access Python modules and run Python scripts. On the other side it makes Delphi/Lazarus objects, records, interfaces, and classes accessible to Python, giving Python the ability to use this methods.

Before you try the demos please see the Wiki topic “How Python for Delphi finds your Python distribution” at

https://github.com/pyscripter/python4delphi/wiki/FindingPython

You will need to adjust the demos accordingly, to successfully load the Python distribution that you have installed in your PC, e.g. C:\Users\max\AppData\Local\Programs\Python\Python36\.

PythonEngine: The core of Python for Delphi. Provides the Python
API with dll mapper and runtime configuration.

VarPyth: VarPyth wraps Python types as Delphi custom variants.

WrapDelphi: Uses RTTI (in a DLL) so you can use Delphi objects
from Python without writing individual wrapper
classes or methods.

TPythonGUIInputOutput: Provides a Python console you can drop on a form and execute a Python script from a memo.

The TPythonEngine class is the single global engine block shared by all Python code. VarPyth wraps Python types as Delphi custom variants. VarPyth requires at least Delphi v6.

This Tutorials folder contains text and video, webinar tutorials accompanied with slides and demo source code. Next time I’ll show a few bidirectional demos with implementation details.

_PIC: tutor86_Python4Delphilogo.png

Wiki P4D topics

Learn about Python for Delphi

Dealing with internals of Python means also you get the original stack-trace errors back like (TPythonEngine.RaiseError;):

File “C:\Users\max\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py”, line 1304, in _validate_read_indexer

raise KeyError(f”{not_found} not in index”)

KeyError: “[‘id’, ‘links’, ‘published_parsed’, ‘published’, ‘title_detail’, ‘guidislink’, ‘link’, ‘summary_detail’] not in index”

The script can be found:

http://www.softwareschule.ch/examples/1016_newsfeed_sentiment_integrate2.txt

Ref Video:

https://github.com/pyscripter/python4delphi/wiki/FindingPython

You will need to adjust the demos accordingly, to successfully load the Python distribution that you have installed on your computer.

Doc: https://maxbox4.wordpress.com

  Appendix: Catalog of the Demos:

{*—————————————————————————-*)

Demo01  A simple Python evaluator
Demo02  Evaluate a Python expression
Demo03  Defining Python/Delphi vars
Demo04  Defining Python/Delphi vars (advanced case)
Demo05  Defining a new Module
Demo06  Defining a new Type
Demo07  Using Delphi methods as Python functions
Demo08  Using Delphi classes for new Python types
Demo09  Making a Python module as a Dll
Demo10_FireDAC Database demo using FireDAC
Demo11  Using Threads inside Python
Demo16  Using a TDelphiVar or Module methods
Demo17  Using variant arrays of 2 dimensions
Demo19  C++ Builder: this is a replicate of the Delphi Demo05
Demo20  C++ Builder: this is a replicate of the Delphi Demo08
Demo21  Using Events in TPythonModule or TPythonType
Demo22  Using Threading, Windows Console and Command line arguments
Demo23  Using Threading and Delphi log window
Demo25  Using VarPyth.pas
Demo26  Demo8 revisited to allow the new Python type to be subclassed
Demo27  Container indexing
Demo28  Iterator
Demo29  Using Python Imaging Library (PIL)
Demo30  Using Named Parameters
Demo31  Using WrapDelphi to access Delphi Form attributes
Demo32  Demo08 revisited using WrapDelphi
Demo33  Using Threads inside Python
Demo34  Dynamically creating, destroying and recreating PythonEngine. 

PyRun() in maXbox

To run python code direct in a maXbox or whatever script you need to import just 3 DLL functions, above all PyRun_SimpleStringFlags :

This is a simplified interface to PyRun_SimpleString leaving the PyCompilerFlags* argument set to NULL.

1int PyRun_SimpleString(const char *command)
1234567891011const PYDLLPATH = 'C:\maXbox\EKON24\';      PYDLLNAME = 'python37.dll';       PSCRIPTNAME = 'initpy.py';  procedure pyinit();      external 'Py_Initialize@C:\maXbox\EKON24\python37.dll cdecl'; procedure pyexit(retval: integer);      external 'Py_Exit@C:\maXbox\EKON24\python37.dll cdecl';   function pyrun(command :pchar):integer;      external 'PyRun_SimpleString@C:\maXbox\EKON24\python37.dll cdecl';

It depends on your Python Installation, Module-Settings and Path-Environment. Then we can invoke line by line Python commands, e.g. write a text-file on a storage and close the file:

1234567891011if isDLLOnSystem(PYDLLPATH+PYDLLNAME) then begin  showmessage('py dll available');   writeln(getCR)  pyinit();  writeln(itoa(pyrun('import sys')));   writeln(itoa(pyrun('print("this is box")')));       writeln(itoa(pyrun('f=open(r"C:\maXbox\mX47464\maxbox4\test.txt","w")')));  writeln(itoa(pyrun('f.write("Hello PyWorld_, \n")')));  writeln(itoa(pyrun('f.write("This data will be written on the file.")')));   writeln(itoa(pyrun('f.close()')));

If you get a 0 back of pyrun() then its OK.

TEE Animated NET

A Sentiment API

maXbox Starter 82_2 – How to make a Sentiment Analysis, Max Kleiner

“Yesterday I was clever, so I wanted to change the world. Today I am wise, so I am changing myself.” – Rumi

As you way know, we went through the last magazine report on the BBC News feed, line by line in a maXbox shellbook; now we want to equip and enlarge these texts with a sentiment analysis like the following:

11: French MP and billionaire Olivier Dassault dies in helicopter crash:
Sun, 07 Mar 2021 20:04:17 GMT
{"probability": {"neg": 0.46705201547833042, "neutral": 0.81510771060379195, "pos": 0.53294798452166958}, "label": "neutral"}

So the label shows neutral in the middle of possibilities. The english sentiment uses classifiers trained on both twitter sentiment as well as movie reviews from the data sets. The dutch and french sentiment is based on book reviews.
Because of the nature of the text and its categories, the classification we will be doing is a form of sentiment analysis or opinion mining. If the classifier returns pos, then the text expresses a positive sentiment, whereas if we get neg, then the text expresses a negative sentiment.

Web API

This procedure of discovering and classifying opinions expressed in a piece of text (like comments/feedback text/news feed in our case) is called the sentiment analysis. The intended output of this analysis would be to determine whether the producers mindset toward a topic, product, headline or service etc., is in most cases neutral, positive, or negative.
Lets get started with the use of this API:

Const 
  URLSentimentAPI2='http://text-processing.com/api/sentiment/'; 
  
//Our text lines are based on the BBC-News Feed:

  BBCFeed = 'http://feeds.bbci.co.uk/news/world/rss.xml'; 

To call the API we use a late binding OLE Automation from . The text-processing.com API is a simple JSON over HTTP web service for text mining and natural language processing. It is currently free and open for public use without authentication or login, but could be changed in the future. As of JSON we use the delphi4json library to parse the return.

The script you can find at:
http://www.softwareschule.ch/examples/newssentiment2.txt

  XMLhttp:= CreateOleObject('msxml2.xmlhttp')      
  XMLhttp.Open('POST', URLSentimentAPI2, False)   //False: async
  XMLhttp.setRequestHeader('Content-Type','application/json');
  XMLhttp.Send('text='+'"'+textin+'"'+CRLF+'language=english');
  response:=  XMLhttp.responseText; //assign data
  writeln(response)
  writeln('statuscode: '+itoa(XMLhttp.status;))
  XMLhttp:= unassigned;

On success, a 200 OK response will be returned containing a JSON object that looks like:

"probability":
  {"neg": 0.37517484595971884,
   "neutral": 0.091034274541377691,
   "pos": 0.62482515404028116},
   "label": "pos"}

A 503 Throttled response will be returned if you exceed the daily request limit. Using async = false in Open() is not always recommended, but for a few small requests this can be OK. Remember that the script will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.
Anyway we open our XMLhttpObject (which is late binding) as not asynchronous, that is to say, synchronous because we just post a single block of data with send().

The send() method (XMLhttp.Send();) needs more explanation: send() accepts an optional parameter which lets you specify the requests body; this is primarily used for requests such as PUT or POST. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null. I’m not sure if the content-type is the right (text or application), the MIME media type for JSON text is application/json and the default encoding is UTF-8. (Source: RFC 4627).
{content-type: application/json; charset=utf-8}

To analyze some text, we do an HTTP POST to our API with form encoded data containing the text we want to analyze. We get back a JSON object response with 2 attributes label and probability which we parse with a JSON object (more of that in the next number):

with TJson.create() do begin
    clear;
    parse(response);
    cnode:= JsonObject.items[0].name;  //'probability'
    writeln(itoa(JsonObject.count));
    writeln('prob:
            '+values[cnode].asObject.values['neutral'].asstring);
    writeln('result: '+(values['label'].asstring));
    free;
  end;  

2
prob: 0.854074272795421
result: neutral

As you may see many of the most commonly used words pr phrases are insignificant when it comes to discerning the meaning of a phrase. For example, in the phrase the movie was terrible, the most significant words are movie and terrible, while the and was are almost useless. You could get the same meaning if you took them out, that is, movie terrible or terrible movie. Either way, the sentiment is the same.
Another approach is to measure the sentiment of face feelings with 3 flavors: Joy, Sadness and Anger or Disbelief, but that’s kind of research.

Our quote from above results in:
Sentiment of: “Yesterday I was clever, so I wanted to change the world. Today I am wise, so I am changing myself”.
{“probability”: {“neg”: 0.375, “neutral”: 0.091, “pos”: 0.624}, “label”: “pos”}
statuscode: 200

Sentiment Tester

The NLTK (Natural Language Toolkit) is a leading platform for building Python or API programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet and many others.

Conclusion:
This is a demonstration of sentiment analysis using a NLTK 2.0.4 powered text classification process with msxml2.xmlhttp and TJson objects. It can tell you whether it thinks the text you enter below expresses positive sentiment, negative sentiment, or if it is neutral.
The feedback results will be more accurate on text that is similar to original training data. If you get an odd result, it could be the words you have used are unrecognized. Try entering more words or blocks to improve accuracy. Note that the public API is for non-commercial purposes, and each method is throttled to 1000 calls per day per IP.


You may also test the same context with different languages, the default language is english, but this API also supports dutch and french, but dont forget to change the language in the API call:

XMLhttp.Send('text='+'"'+textin+'"'+CRLF+'language=dutch');

Trump’s false election fraud claims face a dead end
{“probability”: {“neg”: 0.52, “neutral”: 0.64, “pos”: 0.47}, “label”: “neutral”}
Trumps falsche Wahlbetrugsansprüche stehen vor einer Sackgasse
Trump’s valse verkiezingsfraudeclaims lopen dood
Les fausses allégations de fraude électorale de Trump font face à une impasse
{“probability”: {“neg”: 0.33, “neutral”: 0.46, “pos”: 0.66}, “label”: “pos”}
Trump’s valse verkiezingsfraudeclaims lopen dood
{“probability”: {“neg”: 0.48, “neutral”: 0.72, “pos”: 0.51}, “label”: “neutral”}

Ref:
http://www.softwareschule.ch/examples/newssentiment2.txt
http://text-processing.com/docs/sentiment.html
https://www.nltk.org/
script: 1017_RSSDatacampSSLStreamSentiment2.pas
Doc:
https://maxbox4.wordpress.com

Appendix: Alternate HTTPPost-Routine:

function GetBlogStream8Sentiment(const S_API, pData: string; 
                                        astrm: TStringStream): TStringStream;
begin
  sr:='text='+HTTPEncode(pData)+CRLF;
  sr:= sr+'language=english';
  if HttpPostURL(S_API, sr, astrm) then
     result:= astrm;
end;  
Code Case

50 Years of Pascal

Niklaus Wirth published the paper “The programming language Pascal” in March 1971, which means it is exactly 50 years this month since the Pascal programming language was officially launched.

The renowned computer scientists celebrated the anniversary by writing a very interesting viewpoint article for Communications of the ACM (March 2021, Vol. 64 No. 3, Pages 39-41) and titled 50 Years of Pascal.

ML Algos

More of that Jazz shine on

Made in Borland
Made in Borland Field Test

JSON Automation

Reading json data in maXbox could be easy. Json data can be read from a file or it could be a json web link. Let us first try to read the json from a web link.

Const 
JsonUrl = 'https://pomber.github.io/covid19/timeseries.json';

Let us first define the necessary packages “msxml2.xmlhttp and the JSON class”.

var  XMLhttp : OleVariant; // As Object
     ajt: TJson; JObj: TJsonObject2;

XMLhttp:= CreateOleObject('msxml2.xmlhttp')      
XMLhttp.Open ('GET', JsonUrl, False)

ajt:= TJson.create(); 

Let us import the covid19 timeseries data from json link pomber.github.io/covid19/timeseries.json using XMLhttp:

Ref:  <class 'pandas.core.frame.DataFrame'>
RangeIndex: 76608 entries, 0 to 76607
Data columns (total 5 columns):
 #   Column     Non-Null Count  Dtype
---  ------     --------------  -----
 0   country    76608 non-null  object
 1   date       76608 non-null  object
 2   confirmed  76608 non-null  int64
 3   deaths     76608 non-null  int64
 4   recovered  76608 non-null  int64
dtypes: int64(3), object(2)
memory usage: 2.9+ MB
XMLhttp.setrequestHeader('Content-Type','application/x-www-form-urlencoded');
  XMLhttp.Send();
  response:=  XMLhttp.responseText; //)
  statuscode:=  XMLhttp.status; 

To get the json type of class, struct or array, we need to use ajt.parse() method first.

try
    ajt.parse(resrange);
  except
    writeln( 'Exception: <TJson>"" parse error: {'+
                  exceptiontostring(exceptiontype, exceptionparam)) 
  end;                                             
  //Split(ajt.Stringify,'{',slist)         
  writeln('Statuscode: '+(statuscode)+': '+'listlen '+itoa(ajt.count));
  writeln('Slice jsons country: '+itoa(ajt.count))

  JObj:= ajt.JsonObject;
  writeln('Get all Countries: ')
  for cnt:= 0 to jobj.count-1 do 
     //writeln(Jobj.items[cnt].name+' '+Jobj.items[cnt].value.stringify);  
     writeln(Jobj.items[cnt].name);  

Ok, it is a JsonObject dictionary with 192 countries. Lets check the keys of our dict.

//*)  //accumulated   
   Clabel:='Vietnam'; 
   Chart1.Title.Text.clear;  
   Chart1.Title.Text.add('Sciplot TimeSerie for: '+Clabel); 
     JArray:= ajt.values[Clabel].asarray; 
     writeln('jitems country '+itoa(jarray.count));              
     for cnt:= 1 to jarray.count-1 do begin      
        itmp:= jarray.items[cnt].asObject.values['confirmed'].asinteger;
        chart1.Series[0].Addxy(cnt,itmp,'',clGreen);
        itmp:= jarray.items[cnt].asObject.values['deaths'].asinteger;
        chart1.Series[1].Addxy(cnt,itmp,'',clRed);
        itmp:= jarray.items[cnt].asObject.values['recovered'].asinteger;   
        chart1.Series[2].Addxy(cnt,itmp,'',clBlue);       
     end; 

The script you can find at: http://www.softwareschule.ch/examples/covid2.txt

Conclusion: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

Random Number Generator

A random number generator is a routine that produces a sequence of numbers that would pass statistical or probabilistic tests for randomness. To be really strict, routines that generate random numbers are said to be pseudorandom number generators (often abbreviated to PRNG) to differentiate them from true random number generators that rely on some kind of random events happening at a quantum level.

type
  TStRandomBase = class
    private
    protected
      function rbMarsagliaGamma(aShape   : double) : double;
      function rbMontyPythonNormal : double;
    public
      {uniform distributions}
      function AsFloat : double; virtual; abstract;
      function AsInt(aUpperLimit : integer) : integer;
      function AsIntInRange(aLowerLimit : integer;
                            aUpperLimit : integer) : integer;

      {continuous non-uniform distributions}
      function AsBeta(aShape1, aShape2 : double) : double;
      function AsCauchy : double;
      function AsChiSquared(aFreedom : integer) : double;
      function AsErlang(aMean  : double;
                        aOrder : integer) : double;
      function AsExponential(aMean : double) : double;
      function AsF(aFreedom1 : integer;
                   aFreedom2 : integer) : double;
      function AsGamma(aShape : double; aScale : double) : double;
      function AsLogNormal(aMean   : double;
                           aStdDev : double) : double;
      function AsNormal(aMean   : double;
                        aStdDev : double) : double;
      function AsT(aFreedom : integer) : double;
      function AsWeibull(aShape : double;
                         aScale : double) : double;
  end;

  TStRandomSystem = class(TStRandomBase)
    private
      FSeed : integer;
    protected
      procedure rsSetSeed(aValue : integer);
    public
      constructor Create(aSeed : integer);
      function AsFloat : double; override;
      property Seed : integer read FSeed write rsSetSeed;
  end;

https://github.com/TurboPack/SysTools/blob/master/source/StRandom.pas

Often, in conversation, people use the term random when they really mean arbitrary. When one asks for an arbitrary number, one is saying that one doesn’t really care what number one gets: almost any number will do. By contrast, a random number is a precisely defined mathematical concept: every number should be equally likely to occur. A random number will satisfy someone who needs an arbitrary number, but not the other way around.

The first test is the simplest: the uniformity test. This is the one we were discussing earlier. Basically, the random numbers we generate are going to be checked to see that they uniformly cover the range 0.0 to 1.0. We create 100 buckets, generate 1,000,000 random numbers, and slot them into each bucket. Bucket 0 gets all the random numbers from 0.0 to 0.01, bucket 1 gets them from 0.01 to 0.02, and so on. The probability of a random number falling into a particular bucket is obviously 0.01. We calculate the chi-square value for our test and check that against the standard table, using the 99 degrees of freedom line.

{===Helper routines==============================================}
function GetRandomSeedX : integer;           
var
  Hash : integer;
  SystemTime: TSystemTime;
  G : integer;
begin
  {start with the tick count}
  Hash := integer(GetTickCount);

  {get the current time}
  GetLocalTime(SystemTime);

  {hash in the milliseconds}
  Hash := (Hash shl 4) + SystemTime.wMilliseconds;
  G := Hash and Integer($F0000000);
  if (G <> 0) then
    Hash := (Hash xor (G shr 24)) xor G;

  {hash in the second}
  Hash := (Hash shl 4) + SystemTime.wSecond;
  G := Hash and Integer($F0000000);
  if (G <> 0) then
    Hash := (Hash xor (G shr 24)) xor G;

  {hash in the minute}
  Hash := (Hash shl 4) + SystemTime.wMinute;
  G := Hash and Integer($F0000000);
  if (G <> 0) then
    Hash := (Hash xor (G shr 24)) xor G;

  {hash in the hour}
  Hash := (Hash shl 3) + SystemTime.wHour;
  G := Hash and Integer($F0000000);
  if (G <> 0) then
    Hash := (Hash xor (G shr 24)) xor G;

  {return the hash}
  Result := Hash;
end;
{===============================================================}

https://www.delphipower.xyz/data_structures/the_uniformity_test.html

  SelfTestCRandom;
  
  writeln('GetRandomSeedX: '+inttostr64(GetRandomSeedX));
  
  strand:= TStRandomSystem.create(42); //if 0 then randomseedx    
  writeln(floattostr(strand.asFloat))
  writeln(floattostr(strand.asFloat))
  writeln(floattostr({System.}Random(10)));
  writeln(floattostr({System.}RandomE));
  writeln(itoa(strand.asInt(10000)))
  writeln(itoa(strand.asInt(10000)))
  writeln(itoa(strand.asInt($E15)))
  
  UniformityTest2(strand, ChiSquare, DegsFreedom)
  writeln('ChiSquare: '+floattostr(ChiSquare)+' ,degsfreedom:'+itoa(degsfreedom));
  
  UniformityTest3(strand, ChiSquare, DegsFreedom)
  writeln('ChiSquare: '+floattostr(ChiSquare)+' ,degsfreedom:'+itoa(degsfreedom));
 
  strand.Free;

(Current theories state that quantum events are truly random. The time of the decay of a radioactive atom into its byproducts cannot be predicted; all we can say is that there is a certain probability that it will decay within a certain period of time, and we can estimate that probability by observing the decay of many, many atoms.)

File Size Proof

The FileSize test monitors the file size of each of the files specified as parameters to the test. The current size of the file in Kilobytes and alerts can be generated when a file exceeds a predefined maximum size.

function FileGetSizeX(const FileName: string): Int64;
{$ifndef fpc}
var FileInfo: TSearchRec;
{$endif}
begin
{$ifdef fpc}
  Result:= FileUtil.FileSize(FileName);
{$else}
  // from LCL FileUtil code
  FileInfo.Name:= Filename;
  FileInfo.FindHandle:= {Windows.}FindFirstFile({Windows.}{LPTSTR}
                              (FileInfo.Name),FileInfo.FindData);
  if FileInfo.FindHandle={Windows.}Invalid_Handle_value then begin
    Result:=-1;
    Exit;
  end;
  Result:= (int64(FileInfo.FindData.nFileSizeHigh) 
                Shl 32)+ FileInfo.FindData.nFileSizeLow;
  {Windows.}FindCloseW(FileInfo.FindHandle);
{$endif}
end;

writeln(inttostr64(FileGetSize(exepath+’maXbox4.exe’)));
writeln(inttostr64(FileGetSizeX(exepath+’maXbox4.exe’)));
println(int64tostr(CFileGetSize(exepath+’maXbox4.exe’)));

FileStream Handling

procedure Testbinaryload(afilepath: string);
var fs, fsc: TStream; 
    LoadString: AnsiString;
begin  
  fs:= TFileStream.Create(afilepath, 
                              fmOpenReadWrite or fmShareDenyNone);
  try
    SetLength(LoadString, FS.Size);
    writeln('filesize1 '+itoa(fs.size));
    FS.ReadBuffer((LoadString), FS.Size);
    //fs.Seek(0, sofromBeginning);
    fs.Position:= 0;
    fs.WriteBuffer(loadstring, fs.size);
  finally
    writeln('filesize2 '+itoa(fs.size));
    fs.free;
  end;  
end; 

Procedure TBackupFormFileCopy(Const sourcefilename,
                                         targetfilename: String );
Var S, T: TFileStream;
Begin
 S:= TFileStream.Create(sourcefilename, fmOpenRead );
 try
   T:= TFileStream.Create(targetfilename,
                            fmOpenWrite or fmCreate );
   try
     T.CopyFrom(S, S.Size );
   finally
     T.Free;
   end;
 finally
   S.Free;
 end;
End;  

Time Stamp Compare Forensic

Whether you need to hide your recent activity on a computer or if you need to synchronize file dates, using this routine is the best way to adjust the creation, access, or modification dates and times of files or folders.

//The structure is as follows : (taken from Win32 Reference Guide)

(*typedef struct _WIN32_FIND_DATA { // wfd
    DWORD dwFileAttributes;
    FILETIME ftCreationTime;
    FILETIME ftLastAccessTime;
    FILETIME ftLastWriteTime;
    DWORD    nFileSizeHigh;
    DWORD    nFileSizeLow;
    DWORD    dwReserved0;
    DWORD    dwReserved1;
    TCHAR    cFileName[ MAX_PATH ];
    TCHAR    cAlternateFileName[ 14 ];   *)
    
//http://docwiki.embarcadero.com/Libraries/Sydney/en/System.SysUtils.TSearchRec    

function FileGetSizeX(const DirBase, extension: string): Int64;
{$ifndef fpc}
var FileInfo: TSearchRec; srlist: TStringlist;
    timestamp, createdate: Tdatetime; tcompare: integer;
{$endif}
begin
{$ifdef fpc}
  Result:= FileUtil.FileSize(FileName);
{$else}
  //from maXbox4FileUtil code
   srlist:= FindAllFiles(DirBase,extension,true) //true:recursive
   for it:= 0 to srlist.count-1 do begin
     FileInfo.Name:= srlist.strings[it]; //filename;
     FileInfo.FindHandle:= {Win.}FindFirstFile({Win.}
                    {LPTSTR}(FileInfo.Name),FileInfo.FindData);
     if FileInfo.FindHandle={Win.}Invalid_Handle_value then
     begin
       Result:=-1;
       Exit;
     end;
     Result:=(int64(FileInfo.FindData.nFileSizeHigh) 
                Shl 32)+ FileInfo.FindData.nFileSizeLow;
     timestamp:=
          FileTimeToDateTime(fileinfo.finddata.ftLastWriteTime); 
     createdate:=
          FileTimeToDateTime(fileinfo.finddata.ftCreationTime);
     tcompare:= CompareDateTime(timestamp, createdate)
               
     {Win.}FindCloseW(FileInfo.FindHandle);
    // FileDateToDateTime(fileinfo.time);  
    writeln(itoa(it+1)+ ': '+srlist.strings[it]+
       ' sz:'+inttostr64(result)+ ' dt:'+
          datetostr(timestamp)+'
                cr:'+datetostr(createdate)+':'+itoa(tcompare));    
   end;
   srlist.Free;    
{$endif}
end;

While programming file handling, especially changing file date and time, I
used the function FindFirst() to get the filehandle, in which one of the arguments is of type TSearchRec.

This component has the property FindData., of type TWin32FindData. Unfortunately, on-line help would not provide the properties of TWin32FindData, while using a watch on this component shows that there must be quite some properties as listed above.

Word Count Routine

Not so trivial but almost blameable. Knowing the word count of a text can be important. For example, if an author has to write a minimum or maximum amount of words for an article, essay, report, story, book, paper, you name it. A Routine will help to make sure its word count reaches a specific requirement or stays within a certain limit.

function WordCount3(const S:String; const WordDelims:TCharSet):
                                                          Integer;
var sLen, i: integer;
begin
  Result:= 0; i:= 1;
  sLen:= Length(S); 
  writeln('debug '+itoa(slen))                                
  while i <= sLen-1 do begin
    while (i <= sLen) and CharInSet(S[i],WordDelims) do Inc(i);
    if i <= sLen then Inc(Result);
    while not(i >=sLen) and Not isCharInSet(S[i],WordDelims) do 
          Inc(i);
  end;
end;

In writing a story, recommended word counts only really come into play when you’re weighing up your publishing options. For example, literary magazines typically have strict limits to the length of short stories they will print. After all, they have a limited number of pages for each issue (and their editors only have so many hours in the week to edit manuscripts).

Cologne

Model Appendix

model = ARIMA(differenced, order=(7,0,1))
model_fit = model.fit()
model_fit.summary()

“””

SARIMAX Results

Dep. Variable: y No. Observations: 3285
Model: ARIMA(7, 0, 1) Log Likelihood -8689.286
Date: Mon, 29 Mar 2021 AIC 17398.571
Time: 15:18:25 BIC 17459.542
Sample: 0 HQIC 17420.401
– 3285

Covariance Type: opg

coef std err z P>|z| [0.025 0.975]

const 0.0152 0.132 0.115 0.909 -0.244 0.275
ar.L1 1.1442 0.314 3.642 0.000 0.528 1.760
ar.L2 -0.4358 0.168 -2.594 0.009 -0.765 -0.106
ar.L3 0.0962 0.044 2.179 0.029 0.010 0.183
ar.L4 0.0126 0.029 0.427 0.669 -0.045 0.070
ar.L5 -0.0103 0.029 -0.362 0.717 -0.066 0.046
ar.L6 0.0124 0.026 0.485 0.628 -0.038 0.063
ar.L7 0.0086 0.025 0.345 0.730 -0.040 0.057
ma.L1 -0.6172 0.314 -1.967 0.049 -1.232 -0.002

sigma2 11.6150 0.281 41.386 0.000 11.065 12.165

===
Ljung-Box (Q): 50.56 Jarque-Bera (JB): 1.55
Prob(Q): 0.12 Prob(JB): 0.46
Heteroskedasticity (H): 0.84 Skew: -0.02

Prob(H) (two-sided): 0.00 Kurtosis: 3.10

===
model = ARIMA(series.Temp, order=(7,1,1))
model_fit = model.fit()
model_fit.summary()

“””

SARIMAX Results

Dep. Variable: Temp No. Observations: 3650
Model: ARIMA(7, 1, 1) Log Likelihood -8386.229
Date: Mon, 29 Mar 2021 AIC 16790.457
Time: 15:18:50 BIC 16846.277
Sample: 0 HQIC 16810.336
– 3650

Covariance Type: opg

coef std err z P>|z| [0.025 0.975]

ar.L1 0.4973 0.023 21.748 0.000 0.453 0.542
ar.L2 -0.1303 0.019 -6.752 0.000 -0.168 -0.092
ar.L3 0.0035 0.020 0.175 0.861 -0.036 0.043
ar.L4 -0.0037 0.020 -0.189 0.850 -0.042 0.035
ar.L5 0.0022 0.019 0.114 0.909 -0.035 0.040
ar.L6 -0.0056 0.018 -0.306 0.759 -0.042 0.030
ar.L7 0.0087 0.018 0.483 0.629 -0.027 0.044
ma.L1 -0.9016 0.017 -53.703 0.000 -0.935 -0.869

sigma2 5.8024 0.129 44.830 0.000 5.549 6.056

===
Ljung-Box (Q): 45.96 Jarque-Bera (JB): 14.26
Prob(Q): 0.24 Prob(JB): 0.00
Heteroskedasticity (H): 0.86 Skew: 0.08

Prob(H) (two-sided): 0.01 Kurtosis: 3.26

===

Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-s
tep).

differenced = difference(X[:,1],180)
model = ARIMA(differenced, order=(7,0,1))
model_fit = model.fit()
model_fit.summary()

“””

SARIMAX Results

Dep. Variable: y No. Observations: 3470
Model: ARIMA(7, 0, 1) Log Likelihood -9136.165
Date: Mon, 29 Mar 2021 AIC 18292.331
Time: 15:37:28 BIC 18353.850
Sample: 0 HQIC 18314.296
– 3470

Covariance Type: opg

coef std err z P>|z| [0.025 0.975]

const -0.1465 1.761 -0.083 0.934 -3.598 3.305
ar.L1 1.4341 0.030 48.385 0.000 1.376 1.492
ar.L2 -0.5879 0.033 -17.669 0.000 -0.653 -0.523
ar.L3 0.1246 0.032 3.922 0.000 0.062 0.187
ar.L4 0.0078 0.031 0.253 0.801 -0.053 0.069
ar.L5 -0.0204 0.031 -0.662 0.508 -0.081 0.040
ar.L6 0.0311 0.029 1.063 0.288 -0.026 0.089
ar.L7 0.0057 0.020 0.285 0.775 -0.034 0.045
ma.L1 -0.8373 0.025 -33.309 0.000 -0.887 -0.788

sigma2 11.3278 0.265 42.797 0.000 10.809 11.847

===
Ljung-Box (Q): 76.34 Jarque-Bera (JB): 2.42
Prob(Q): 0.00 Prob(JB): 0.30
Heteroskedasticity (H): 0.90 Skew: -0.00

Prob(H) (two-sided): 0.08 Kurtosis: 3.13

===

differenced = difference(X[:,1],90)
model_fit = model.fit()
model = ARIMA(differenced, order=(7,0,1))
model_fit = model.fit()
model_fit.summary()

“””

SARIMAX Results

Dep. Variable: y No. Observations: 3560
Model: ARIMA(7, 0, 1) Log Likelihood -9402.551
Date: Mon, 29 Mar 2021 AIC 18825.102
Time: 15:41:35 BIC 18886.877
Sample: 0 HQIC 18847.130
– 3560

Covariance Type: opg

coef std err z P>|z| [0.025 0.975]

const -0.0568 1.112 -0.051 0.959 -2.235 2.122
ar.L1 1.4803 0.026 57.227 0.000 1.430 1.531
ar.L2 -0.6267 0.031 -19.976 0.000 -0.688 -0.565
ar.L3 0.1385 0.031 4.439 0.000 0.077 0.200
ar.L4 -0.0073 0.031 -0.233 0.816 -0.069 0.054
ar.L5 0.0131 0.031 0.419 0.676 -0.048 0.074
ar.L6 -0.0111 0.029 -0.386 0.699 -0.067 0.045
ar.L7 0.0074 0.018 0.403 0.687 -0.029 0.044
ma.L1 -0.8843 0.020 -43.684 0.000 -0.924 -0.845

sigma2 11.5186 0.271 42.474 0.000 10.987 12.050

===
Ljung-Box (Q): 56.31 Jarque-Bera (JB): 1.34
Prob(Q): 0.05 Prob(JB): 0.51
Heteroskedasticity (H): 0.84 Skew: -0.04

Prob(H) (two-sided): 0.00 Kurtosis: 3.06

===

new slides and libraries for it-sec:

   <Words> ActnColorMaps, ActnCtrls, ActnList, ActnMan, ActnMenus, ActnPopup, ActnRes, ADOConst, ADODB, ADOInt, AppEvnts, AxCtrls, BandActn, bdeconst, bdemts, Buttons, CheckLst, Classes, Clipbrd.pas, CmAdmCtl, ComCtrls, ComStrs, Consts, Controls, CtlConsts, CtlPanel, CustomizeDlg, DataBkr, DB, DBActns, dbcgrids, DBClient, DBClientActnRes, DBClientActns, DBCommon, DBConnAdmin, DBConsts, DBCtrls, DbExcept, DBGrids, DBLocal, DBLocalI, DBLogDlg, dblookup, DBOleCtl, DBPWDlg, DBTables, DBXpress, DdeMan, Dialogs, DrTable, DSIntf, ExtActns, ExtCtrls, ExtDlgs, FileCtrl, FMTBcd, Forms, Graphics, GraphUtil, Grids, HTTPIntr, IB, IBBlob, IBCustomDataSet, IBDatabase, IBDatabaseInfo, IBDCLConst, IBErrorCodes, IBEvents, IBExternals, IBExtract, IBGeneratorEditor, IBHeader, IBIntf, IBQuery, IBRestoreEditor, IBSecurityEditor, IBServiceEditor, IBSQL, IBSQLMonitor, IBStoredProc, IBTable, IBUpdateSQL, IBUtils, IBXConst, ImgList, Jcl8087, JclAbstractContainers, JclAlgorithms, JclAnsiStrings, JclAppInst, JclArrayLists, JclArraySets, JclBase, JclBinaryTrees, JclBorlandTools, JclCIL, JclCLR, JclCOM, JclComplex, JclCompression, JclConsole, JclContainerIntf, JclCounter, JclDateTime, JclDebug, JclDotNet, JclEDI, JclEDI_ANSIX12, JclEDI_ANSIX12_Ext, JclEDI_UNEDIFACT, JclEDI_UNEDIFACT_Ext, JclEDISEF, JclEDITranslators, JclEDIXML, JclExprEval, JclFileUtils, JclFont, JclGraphics, JclGraphUtils, JclHashMaps, JclHashSets, JclHookExcept, JclIniFiles, JclLANMan, JclLinkedLists, JclLocales, JclLogic, JclMapi, JclMath, JclMetadata, JclMIDI, JclMime, JclMiscel, JclMsdosSys, JclMultimedia, JclNTFS, JclPCRE, JclPeImage, JclPrint, JclQGraphics, JclQGraphUtils, JclQueues, JclRegistry, JclResources, JclRTTI, JclSchedule, JclSecurity, JclShell, JclSimpleXml, JclStacks, JclStatistics, JclStreams, JclStrHashMap, JclStringLists, JclStrings, JclStructStorage, JclSvcCtrl, JclSynch, JclSysInfo, JclSysUtils, JclTask, JclTD32, JclUnicode, JclUnitConv, JclUnitVersioning, JclUnitVersioningProviders, JclValidation, JclVectors, JclWideFormat, JclWideStrings, JclWin32, JclWin32Ex, JclWinMIDI, ListActns, Mask, MConnect, Menus, Midas, MidasCon, MidConst, MPlayer, MtsRdm, Mxconsts, ObjBrkr, OleAuto, OleConst, OleCtnrs, OleCtrls, OleDB, OleServer, Outline, Printers, Provider, recerror, ScktCnst, ScktComp, ScktMain, SConnect, ShadowWnd, SimpleDS, SMINTF, SqlConst, SqlExpr, SqlTimSt, StdActnMenus, StdActns, StdCtrls, StdStyleActnCtrls, SvcMgr, SysUtils, TabNotBk, Tabs, TConnect, Themes, ToolWin, ValEdit, VDBConsts, WinHelpViewer, XPActnCtrls, XPMan, XPStyleActnCtrls </Words>

https://matplotlib.org/stable/tutorials/introductory/pyplot.html

Let’s bring out the seasonality a little bit by creating lag-plots of the the current average monthly temperature against time-lagged values of itself, for various months. Here are the lag-plots:

Scatter plots of average monthly temperature against lagged versions of itself

https://timeseriesreasoning.com/2019/11/16/how-to-select-a-regression-model-using-aic/

Regression goal

Our goal is to predict the average temperature in Boston for the current month.

Regression strategy

The strategy we will follow is as follows:

  1. We will build several Ordinary Least Square Regression (OLSR) models for the temperature data set.
  2. In each model, the response variable will be the current month’s average temperature. This is the TAVG column in the data set.
  3. In each model, the regression variables i.e. the explanatory variables will be different combinations of time lagged temperature variables.
  4. We will train each model on the temperature data set and we’ll select the model with the lowest AIC score.
Secure Center 2010

The last IV

A double edition

MNIST Single Predict

MNIST Single Prediction

We have set up a very simple SVC to classify the MNIST digits to make one single shoot predict. First we load the libraries and the dataset:

A notebook you find at:

https://github.com/maxkleiner/maXbox4/blob/master/MNISTSinglePredict.ipynb

#sign:max: MAXBOX8: 13/03/2021 07:46:37 
import numpy as np
import matplotlib.pyplot as plt
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn import datasets
from sklearn.metrics import accuracy_score

# [height, weight, 8*8 pixels of digits 0..9]
dimages = datasets.load_digits()
print(type(dimages), len(dimages.data), 'samples')
<class 'sklearn.utils.Bunch'> 1797 samples

Then we setup the Support Vector Classifier with the training data X and the target y:

sclf = SVC(gamma=0.001, C=100, kernel='linear')

X= dimages.data[:-10]
y= dimages.target[:-10]
print('train set samples:',len(X))
train set samples: 1787

Gamma is the learning rate and the higher the value of gamma the more precise the decision boundary would be. C (regularization) is the penalty of the fault tolerance. Having a larger C will lead to smaller values for the slack variables. This means that the number of support vectors will decrease. When you run the prediction, it will need to calculate the indicator function for each support vector. Now we train (fit) the samples:

sclf.fit(X,y)
SVC(C=100, break_ties=False, cache_size=200, class_weight=None, coef0=0.0,
    decision_function_shape='ovr', degree=3, gamma=0.001, kernel='linear',
    max_iter=-1, probability=False, random_state=None, shrinking=True,
    tol=0.001, verbose=False)

In the last step we predict a specific digit from the test set (only the last 10 samples are unseen), means we pass an actual image and SVC makes the prediction of which digit belongs to the image:

you can choose the testimage by yourself -6 means the 6.th last of the dataset.

testimage = -6

s_prediction = sclf.predict([dimages.data[testimage]])
print ('the image maybe belongs to ',s_prediction)
plt.imshow(dimages.images[testimage], cmap=plt.cm.gray_r, interpolation="nearest")
plt.show()
the image maybe belongs to  [4]
image 4 jupyter

The same fit we try with a Random Forest Classifier to finish this lesson:

#RandomForestClassifier
rfc_clf = RandomForestClassifier()
rfc_clf.fit(X,y)
rfc_prediction = rfc_clf.predict([dimages.data[testimage]])
print ('predict with RFC ',rfc_prediction)
predict with RFC  [4]
BPM 72
#92
metrics of a binary classifier
Classifier Overview

did a direct import from wiki with the press freedom index

>>> df.head(9).iloc[:,[0,1,2,9,10]]
>>> df.sort_values(by=[‘Rank2020’],inplace=True,ascending=True)

RangeIndex: 180 entries, 0 to 179
Data columns (total 14 columns):
# Column Non-Null Count Dtype
— —— ————– —–
0 ISO 180 non-null object
1 Rank2020 180 non-null int64
2 FR_Country 180 non-null object
3 EN_country 180 non-null object
4 ES_country 180 non-null object
5 Score A 180 non-null object
6 Sco Exa 180 non-null object
7 Score 2020 180 non-null object
8 Progression RANK 180 non-null int64
9 Rank 2019 180 non-null int64
10 Score 2019 180 non-null object
11 Zone 180 non-null object
12 AR_country 180 non-null object
13 FA_country 180 non-null object
dtypes: int64(3), object(11)
memory usage: 19.8+ KB

df.sort_values(by=[‘Rank2020’], inplace=True, ascending=True)

df.head(9).iloc[:,[0,1,2,9,10]]

     ISO  Rank2020        FR_Country  Rank 2019 Score 2019
     ISO  Rank2020        FR_Country  Rank 2019 Score 2019
120  NOR         1           Norvège          1       7,82
53   FIN         2          Finlande          2        7,9
44   DNK         3          Danemark          5       9,87
150  SWE         4             Suede          3       8,31
119  NLD         5          Pays-Bas          4       8,63
80   JAM         6          Jamaïque          8      11,13
37   CRI         7        Costa Rica         10      12,24
27   CHE         8            Suisse          6      10,52
122  NZL         9  Nouvelle-Zélande          7      10,75

The story of a parcel tracing (from 9.2- 25.2) analysis:

If you want to ask post.ch the response from the remote server was:

550 #5.1.0 Address rejected.

  • 25. Feb 2021 12:11 Erfolgreiche Zustellung
  • Voraussichtliche Zustellung
  • am 25.02.2021 zwischen 11.00 und 15.00 Uhr
    • 23. Feb 2021 11:35 Beladung
    • 23. Feb 2021 11:30 Zollfreigabe
    • 16. Feb 2021 14:55 Weiterleitung zur Exportbearbeitung
    • 16. Feb 2021 14:55 Entladung
    • 16. Feb 2021 14:55
    • 11. Feb 2021 7:34 Beladung
    • 10. Feb 2021 23:39 Weiterleitung zur Exportbearbeitung
    • 9. Feb 2021 18:41 Weiterleitung zur Exportbearbeitung
    • 9. Feb 2021 16:06 Filiale / Agentur
    • 9. Feb 2021 16:45 Sendungsnummer angegeben

Dienstag, 23. Februar 2021 12:00 Datenübermittlung durch Versender 11:35
Sendung wurde sortiert und weitergeleitet 897000 CH-8970 Urdorf EO

Dienstag, 16. Februar 2021 14:55 Verzollungsprozess 897000 CH-8970 Urdorf EO
14:55 Ankunft Bestimmungsland 897000 CH-8970 Urdorf EO
Donnerstag, 11. Februar 2021 07:34 Abgang Grenzstelle Aufgabeland IFS Speyer

16. Feb 2021 14:55 Weiterleitung zur Exportbearbeitung

16. Feb 2021 14:55 Entladung

11. Feb 2021 7:34 Beladung

10. Feb 2021 23:39 Weiterleitung zur Exportbearbeitung

9. Feb 2021 18:41 Weiterleitung zur Exportbearbeitung

9. Feb 2021 16:06 Filiale / Agentur

9. Feb 2021  16:45  Sendungsnummer angegeben

Transportation to destination country/destination area.

Destination country/region: Switzerland

International shipment number: CY542939469DE
Th, 11.02.2021, 07:34 hours
NOTE: As soon as the shipment arrives in the destination country/destination area, you will receive updated information in the detailed tracking history.

Tu, 16.02.2021, 14:55
Shipment is prepared for customs clearance in the destination country/destination area

Tu, 16.02.2021, 14:55
The shipment has arrived in the destination country/destination area
Th, 11.02.2021, 07:34, Speyer, Germany
The shipment will be transported to the destination country/destination area and, from there, handed over to the delivery organization. (Homepage / online shipment tracking: http://www.post.ch)
We, 10.02.2021, 23:39, Speyer, Germany
The international shipment is being prepared for onward transport.
Tu, 09.02.2021, 18:41, Rüdersdorf, Germany
The international shipment has been processed in the parcel center of origin
Tu, 09.02.2021, 16:06 The shipment has been posted by the sender at the retail outlet

Fundamentals Library

////////////////////////////////////////////////////////////////////////////
Fundamentals 5 Code Library Introduction


by Max Kleiner

“Love comes unseen; we only see it go.”
– Henry Austin Dobson

The Fundamentals 5 Code Library is a big toolbox for Delphi and FreePascal.

What I appreciate the most in this library are the main utilities for network and internet. This utilities (Utils) it provides involve math, statistic, unicode routines and data structures for classes similarly to how users would find them in a big framework. In this way, testing-routines helps ensure your tests and give you confidence in your code.

Our Test Directory includes detailed information, guides and references for many of our tests. This includes test and result codes, specimen collection requirements, specimen transport considerations, and methodology.
Concerning a documentation of the Fundamentals library, the most is detailed direct in code with a revision history and supported compilers. There are also tools like DiPasDoc which we can use to generate API documentation from comments in sources. Those are free and generates HTML as well as CHM. A very useful online docu has been built and hosted gratefully in the meantime but not finished yet:

http://fundamentals5.kouraklis.com/

David J. Butler is also the author of the Zlib version of PASZLIB which is based on the zlib 1.1.2, a general purpose data compression library.
The ‘zlib’ compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method
(deflation) but other algorithms will be added later and will have the same stream interface.

Similarly to for example the Indy or Jedi library, we can specify the class name, test name number of samples (measurements) to take and number of operations (iterations) the code will be executed. Most of the operations are not overload but has a strong name like that:

function GetEnvironmentVariableA(const Name: AnsiString): AnsiString;
function GetEnvironmentVariableU(const Name: UnicodeString): UnicodeString;
function GetEnvironmentVariable(const Name: String): String; {$IFDEF UseInline}inline;{$ENDIF}

Whats nice is that when you pass an empty name or something invalid as the actual parameter of samples, most of the names or buffers will be initialized and checked or fill out with a proper default name on its own.
So the Fundamentals Library includes:

String, DateTime and dynamic array routines
Unicode routines
Hash (e.g. SHA256, SHA512, SHA1, SHA256, MD5)
Integer (e.g. Word128, Word256, Int128, Int256)
Huge Word, Huge Integer
Decimal (Decimal32, Decimal64, Decimal128, HugeDecimal and signed decimals)
Random number generators
Ciphers (symmetric: AES, DES, RC2, RC4; asymmetric: RSA, Diffie-Hellman)
Data structures (array and dictionary classes)
Mathematics (Rational number, complex number, vector, matrix, statistics)
JSON parser
Google protocol buffer parser, utilities and Pascal code generator
Socket library (cross platform - Windows and Linux) TLS Client, TLS Server
TCP Client, TCP Server, HTTP Client, HTTP Server, HTML Parser and XML Parser.

https://github.com/fundamentalslib/fundamentals5/
https://github.com/maxkleiner/fundamentals5

I did open another fork on github to document my adapted scripting units. Another advantage is the use of test-procedure with assertions. It implements the Assert procedure to document and enforce the assumptions you must make when writing code. Assert is not a real procedure. The compiler handles Assert specially and compiles the filename and line number of the assertion to help you locate the problem should the assertion fail.

On Github

Assert is not a real procedure. The compiler handles Assert specially and compiles the filename and line number of the assertion to help you locate the problem should the assertion fail.
The syntax is like:

procedure Assert(Test: Boolean);
procedure Assert(Test: Boolean; const Message: string);

If you write a simple script program and distribute it to each computer, you can have the users start the tests on their own by running the script with a list of asserts.

Assert(CopyFrom(‘a’, 0) = ‘a’, ‘CopyFrom’);
Assert(CopyFrom(‘a’, -1) = ‘a’, ‘CopyFrom’);
Assert(CopyFrom(”, 1) = ”, ‘CopyFrom’);
Assert(CopyFrom(”, -2) = ”, ‘CopyFrom’);
Assert(CopyFrom(‘1234567890’, 8) = ‘890’, ‘CopyFrom’);
Assert(CopyFrom(‘1234567890’, 11) = ”, ‘CopyFrom’);
Assert(CopyFrom(‘1234567890’, 0) = ‘1234567890’, ‘CopyFrom’);
Assert(CopyFrom(‘1234567890’, -2) = ‘1234567890’, ‘CopyFrom’);

Assert(not StrMatch(”, ”, 1), ‘StrMatch’);
Assert(not StrMatch(”, ‘a’, 1), ‘StrMatch’);
Assert(not StrMatch(‘a’, ”, 1), ‘StrMatch’);
Assert(not StrMatch(‘a’, ‘A’, 1), ‘StrMatch’);
Assert(StrMatch(‘A’, ‘A’, 1), ‘StrMatch’);
Assert(not StrMatch(‘abcdef’, ‘xx’, 1), ‘StrMatch’);
Assert(StrMatch(‘xbcdef’, ‘x’, 1), ‘StrMatch’);
Assert(StrMatch(‘abcdxxxxx’, ‘xxxxx’, 5), ‘StrMatch’);
Assert(StrMatch(‘abcdef’, ‘abcdef’, 1), ‘StrMatch’);
Assert(StrMatch(‘abcde’, ‘abcd’, 1), ‘StrMatch’);
Assert(StrMatch(‘abcde’, ‘abc’, 1), ‘StrMatch’);
Assert(StrMatch(‘abcde’, ‘ab’, 1), ‘StrMatch’);
Assert(StrMatch(‘abcde’, ‘a’, 1), ‘StrMatch’);
Assert(StrMatches(‘abcd’, ‘abcd’, 1)=true, ‘StrMatches’);

Lets take the above single assert with

Function StrMatches(const Substr, S: AnsiString; const Index: Int): Boolean;

As you can see the strings matches if equal otherwise we get an Exception:

Assert(StrMatches(‘abcd’, ‘abcde’, 1)=true, ‘StrMatches’);

Exception: StrMatches

If the test condition fails the SysUtils unit sets this variable to a procedure that raises the EAssertionFailed exception.
By the way dont comment an assert like that

//Assert(StrMatchLeft(‘ABC1D’, ‘aBc1’, False), ‘StrMatchLeft’);
//Assert(StrMatchLeft(‘aBc1D’, ‘aBc1’, True), ‘StrMatchLeft’);

You can also negate an assert as long as they deliver a boolean (logic) condition:

Assert(not StrMatchLeft(‘AB1D’, ‘ABc1’, False), ‘StrMatchLeft’);
Assert(not StrMatchLeft(‘aBC1D’, ‘aBc1’, True), ‘StrMatchLeft’);

Then you want to write more assert system information to a log file for analyzing problems during installation, debugging, tests and de-installation or app distribution like that:

10/01/2018 19:31:54 V:4.6.2.10 [max] problem occurred in initializing MCI. [at: 3275216pgf; mem:1247492]
14/01/2018 17:15:18 V:4.7.2.30 [max] MAXBOX8 Out Of Range. [at: 2607048pgf; mem:1082444]
14/01/2018 17:15:21 V:4.7.2.40 [max] MAXBOX8 Out Of Range. [at: 2605716pgf; mem:1080012]
16/01/2018 09:18:00 V:4.7.5.20 [max] MAXBOX8 List index out of bounds (456). [at: 2913700pgf; mem:1157700]

{ }
{ Test cases }
{ }
{$IFDEF DEBUG}
{$IFDEF LOG}
{$IFDEF TEST}
//{$ASSERTIONS ON}

Next step is to bundle asserts in a Test Procedure with sections like that:

procedure TestBitsflc;
begin
Assert(SetBit32($100F, 5) = $102F, ‘SetBit’);
Assert(ClearBit32($102F, 5) = $100F, ‘ClearBit’);
Assert(ToggleBit32($102F, 5) = $100F, ‘ToggleBit’);
Assert(ToggleBit32($100F, 5) = $102F, ‘ToggleBit’);
Assert(IsBitSet32($102F, 5), ‘IsBitSet’);
Assert(not IsBitSet32($100F, 5), ‘IsBitSet’);
Assert(IsHighBitSet32($80000000), ‘IsHighBitSet’);
Assert(not IsHighBitSet32($00000001), ‘IsHighBitSet’);
Assert(not IsHighBitSet32($7FFFFFFF), ‘IsHighBitSet’);

Assert(SetBitScanForward32(0) = -1, ‘SetBitScanForward’);
Assert(SetBitScanForward32($1020) = 5, ‘SetBitScanForward’);
Assert(SetBitScanReverse32($1020) = 12, ‘SetBitScanForward’);
Assert(SetBitScanForward321($1020, 6) = 12, ‘SetBitScanForward’);
Assert(SetBitScanReverse321($1020, 11) = 5, ‘SetBitScanForward’);
Assert(ClearBitScanForward32($FFFFFFFF) = -1, ‘ClearBitScanForward’);
Assert(ClearBitScanForward32($1020) = 0, ‘ClearBitScanForward’);
Assert(ClearBitScanReverse32($1020) = 31, ‘ClearBitScanForward’);
Assert(ClearBitScanForward321($1020, 5) = 6, ‘ClearBitScanForward’);
Assert(ClearBitScanReverse321($1020, 12) = 11, ‘ClearBitScanForward’);

Assert(ReverseBits32($12345678) = $1E6A2C48, ‘ReverseBits’);
Assert(ReverseBits32($1) = $80000000, ‘ReverseBits’);
Assert(ReverseBits32($80000000) = $1, ‘ReverseBits’);
Assert(SwapEndian32($12345678) = $78563412, ‘SwapEndian’);

Assert(RotateLeftBits32(0, 1) = 0, ‘RotateLeftBits32’);
Assert(RotateLeftBits32(1, 0) = 1, ‘RotateLeftBits32’);
Assert(RotateLeftBits32(1, 1) = 2, ‘RotateLeftBits32’);
Assert(RotateLeftBits32($80000000, 1) = 1, ‘RotateLeftBits32’);
Assert(RotateLeftBits32($80000001, 1) = 3, ‘RotateLeftBits32’);
Assert(RotateLeftBits32(1, 2) = 4, ‘RotateLeftBits32’);
Assert(RotateLeftBits32(1, 31) = $80000000, ‘RotateLeftBits32’);
Assert(RotateLeftBits32(5, 2) = 20, ‘RotateLeftBits32’);
Assert(RotateRightBits32(0, 1) = 0, ‘RotateRightBits32’);
Assert(RotateRightBits32(1, 0) = 1, ‘RotateRightBits32’);
Assert(RotateRightBits32(1, 1) = $80000000, ‘RotateRightBits32’);
Assert(RotateRightBits32(2, 1) = 1, ‘RotateRightBits32’);
Assert(RotateRightBits32(4, 2) = 1, ‘RotateRightBits32’);

Assert(LowBitMask32(10) = $3FF, ‘LowBitMask’);
Assert(HighBitMask32(28) = $F0000000, ‘HighBitMask’);
Assert(RangeBitMask32(2, 6) = $7C, ‘RangeBitMask’);

Assert(SetBitRange32($101, 2, 6) = $17D, ‘SetBitRange’);
Assert(ClearBitRange32($17D, 2, 6) = $101, ‘ClearBitRange’);
Assert(ToggleBitRange32($17D, 2, 6) = $101, ‘ToggleBitRange’);
Assert(IsBitRangeSet32($17D, 2, 6), ‘IsBitRangeSet’);
Assert(not IsBitRangeSet32($101, 2, 6), ‘IsBitRangeSet’);
Assert(not IsBitRangeClear32($17D, 2, 6), ‘IsBitRangeClear’);
Assert(IsBitRangeClear32($101, 2, 6), ‘IsBitRangeClear’);
Assert(IsBitRangeClear32($101, 2, 7), ‘IsBitRangeClear’);
end;
{$ENDIF}
{$ENDIF}

A tester is then able to run a bunch of tests in Fundamentals, e.g:

setBitmaskTable;
TestBitsflc;

In the Fundamentals Lib we do have a 15 CLF_Fundamentals Testroutines Package:

01 TestMathClass;
02 TestStatisticClass;
03 TestBitClass;
04 TestCharset;
05 TestTimerClass
06 TestRationalClass
07 TestComplexClass
08 TestMatrixClass;
09 TestStringBuilderClass
10 TestASCII;
11 TestASCIIRoutines;
12 TestPatternmatcher;
13 TestUnicodeChar;
14 flcTest_HashGeneral;
15 flcTest_StdTypes;

procedure TestStdTypes;
begin
{$IFDEF LongWordIs32Bits} Assert(SizeOf(LongWord) = 4); {$ENDIF}
{$IFDEF LongIntIs32Bits} Assert(SizeOf(LongInt) = 4); {$ENDIF}
{$IFDEF LongWordIs64Bits} Assert(SizeOf(LongWord) = 8); {$ENDIF}
{$IFDEF LongIntIs64Bits} Assert(SizeOf(LongInt) = 8); {$ENDIF}
{$IFDEF NativeIntIs32Bits} Assert(SizeOf(NativeInt) = 4); {$ENDIF}
{$IFDEF NativeIntIs64Bits} Assert(SizeOf(NativeInt) = 8); {$ENDIF}
{$IFDEF NativeUIntIs32Bits} Assert(SizeOf(NativeUInt) = 4); {$ENDIF}
{$IFDEF NativeUIntIs64Bits} Assert(SizeOf(NativeUInt) = 8); {$ENDIF}
end;

Another way is to prevent call errors as a mistaken precondition of false assumption in
a procedure you designed. This pre- and post-condition can handle a lot of errors.
An example should make this clear.
A TStack object has a method called Pop to remove the topmost data object from the stack.

If the stack is empty, I count calling Pop as a programming mistake: you really should check for the stack being empty in your program prior to calling Pop. Of course Pop could have an if statement within it that did this check for you, but in the majority of cases the stack wont be empty when Pop is called and in the majority of cases when you use Pop, you will have some kind of loop in your program which is continually checking whether the stack is empty or not anyway. In my mind having a check for an empty stack within Pop is safe but slow.

So, instead, Pop has a call to an Assert procedure at the start (activated by the DEBUG compiler define) that checks to see whether the stack is empty. Here is the code for Pop:

  function TStack.Pop : pointer;
    var
      Node : PNode;
    begin
      {$IFDEF DEBUG}
        Assert(not IsEmpty, ascEmptyPop);
      {$ENDIF}
      Node := Head^.Link;
      Head^.Link := Node^.Link;
      Pop := Node^.Data;
      acDisposeNode(Node);
    end;

As you see, if DEBUG is set the Assert procedure checks whether the stack is empty first, if not it executes the code that pops the data object off the stack. If the stack is empty an EEZAssertionError exception is raised (the constant ascEmptyPop is a string code for a string-table resource). If DEBUG is not set the code runs at full speed.

So log the steps and compare test procedures before installation: The location of the update can be a local, UNC or network path to compare it.
When you need Admin Rights you can try this:

ExecuteShell(‘cmd’,’/c runas “/user:Administrator” ‘+
ExePath+’maXbox4.exe’)
or C:> net user Administrator /active:yes

After you have finishing and writing the script, the next and final step is select “Go Compile” in maXbox. What this does is create a complete, ready-to-run Setup program based on your script. By default, this is created in a directory named Exepath under the directory or UNC path containing the script or what destination you need.

function GetInstallScript(const S_API, pData: string): string;
var ts: TStrings;
begin
 with TIdHTTP.create(self) do begin
  try
   ts:= TStringList.Create
   ts.Add('install='+HTTPEncode(pData));
   result:= Post(S_API,ts);
  finally
   ts.Free;
   Free;
  end;
 end
end;

The big step comes with unit tests with setup and tear down. Generic “Assert This” Assertion Procedure means that most generic assertion program simply says “assert this” and passes a Boolean expression. It is used by all the other assertion routines, which construct a Boolean expression from their specific values and logic.
Unit testing is a way of testing the smallest piece of code referred to as a unit that can be logically isolated in a system. It is mainly focused on the functional correctness of standalone modules.

A unit can be almost anything you want it to be – a specific piece of functionality, a program, or a particular method within the application:

type
THugeCardinal_TestCase = TTestCase;
var
Fbig1234: THugeCardinal;
Fbig2313: THugeCardinal;
Fbig3547: THugeCardinal;
//TVerifyResult
Temp1, Temp2, Temp3, Temp4: THugeCardinal;
Temp2000_1: THugeCardinal;
Temp2000_2: THugeCardinal;
T3, F100: THugeCardinal;
TmpStream: TMemoryStream;

procedure THugeCardinal_TestCaseSetUp; //override;
procedure THugeCardinal_TestCaseTearDown; //override;
//published
//procedure Test_CreateZero;
procedure Test_CreateRandom;
procedure Test_CreateSmall;
procedure Test_Clone;
procedure Test_Assign;
procedure Test_Zeroise;
procedure Test_CompareSmall;
procedure Test_Compare;
procedure Test_AssignSmall;
procedure Test_BitLength;
procedure Test_MaxBits;
procedure Test_Add;
procedure Test_Increment;
procedure Test_Subtract;
procedure Test_MulPower2;
procedure Test_MulSmall;
procedure Test_Multiply;
procedure Test_Modulo;
procedure Test_AddMod;
procedure Test_MultiplyMod;
procedure Test_isOdd;
procedure Test_CreateFromStreamIn;
procedure Test_CloneSized;
procedure Test_Resize;
procedure Test_AssignFromStreamIn;
procedure Test_Swap;
procedure Test_ExtactSmall;
procedure Test_StreamOut;
procedure Test_PowerMod;
procedure Test_SmallExponent_PowerMod;

procedure InitUnit_HugeCardinalTestCases;
begin
//TestFramework.RegisterTest( THugeCardinal_TestCase.Suite)
THugeCardinal_TestCaseSetUp;
end;

procedure DoneUnit_HugeCardinalTestCases;
begin
THugeCardinal_TestCaseTearDown
end;

Conclusion:
The proper way to use Assert in the Fundamentals Lib is to specify conditions that must be true in order for your code to work correctly.
Assert(StrMatches(‘abcd’, ‘abcde’, 1)=true, ‘StrMatches’);
All programmers make assumptions about internal state of an object or function, the value or validity of a subroutine’s arguments, or the value returned from a function. A good way to think about assertions is that they check for programmer errors, not user errors!

My 7 Steps for maintainable code:
• Maintain separation of concerns (avoid unnecessary dependencies)
• Fully qualified unit names to be used: Winapi.Windows not Windows
• Code format to be consistent with LIB source
• Do not put application-specific implementations in general code libraries
• Carefully consider modification to common code – the way to proceed
• No hints (instant code review fail) and No warnings
• Keep code small – avoid long methods and should be broken down

Ref:
http://www.softwareschule.ch/download/maxbox_starter36.pdf
https://github.com/fundamentalslib/fundamentals5/
http://www.softwareschule.ch/examples/unittests.txt
script: 919_uLockBox_HugeCardinalTestCases.pas

Doc:
http://fundamentals5.kouraklis.com/
https://maxbox4.wordpress.com

Machine Learning algorithms can be divided into 12 branches, based on underlying mathematical model:

  1. Bayesian — Bayesian machine learning models are based on Bayes theorem which is nothing but calculation of probability of something happening knowing something else has happened, e.g. probability that Yuvraj (Cricketer) will hit six sixes knowing that he ate curry-rice today. We use machine learning to apply Bayesian statistics on our data and we are assuming in these algorithms that there is some independence in our independent variables. These models start with some belief about data and then the models update that belief based on data. There are various applications of Bayesian statistics in classification as I did in my Twitter Project using Naive Bayes Classifier. Also, in business calculating probability of success of certain marketing plan based on data points and historical parameters of other marketing strategies.
  2. Decision Tree — Decision tree as the name suggests is used to come to a decision using a tree. It uses estimates and probabilities based on which we calculate the likely outcomes. Tree’s structure has root node which gets divided into Internal nodes and then leafs. What is there on these nodes is data classification variables. Our models learns from our labelled data and finds the best variables to split our data on so as to minimize the classification error. It can either give us classified data or even predict value for our data points based on the learning it got from our training data. Decision Tree’s are used in finance in option pricing, in Marketing and Business planning to find the best plan or the overall impact on business of various possibilities.
  3. Dimensional Reduction — Imagine you got data which has 1000 features or you conducted a survey with 25 questions and are having a hard time now making sense of which question is answering what. That is where the family of dimensional reduction algorithms come into picture. As the name suggests they help us in reducing the dimensions of our data which in turn reduces the over-fitting in our model and reduces high variance on our training set so that we can make better predictions on our test set. In market research survey often it is used to categorize questions into topics which can then easily be made sense of.
  4. Instance Based — This supervised machine learning algorithm performs operations after comparing current instances with previously trained instances that are stored in memory. This algorithm is called instance based because it is using instances created using training data. k-nearest neighbors is one such example where new location for neighbor is updated all the time based on the number of neighbors we want for our data points and it is done using the previous instance of neighbor and its position which was stored in memory. Websites recommend us new products or movies working on these instance based algorithms and mix of more crazy algorithms.
  5. Clustering — Making bunch of similar type of things is called clustering. The difference here is that we are clustering points based on the data we have. This is an unsupervised machine learning algorithm where algorithm itself makes sense of whatever gibberish we give it. Algorithm clusters the data based on those inputs and then we can make sense of data and find out what all things or points fit together better. Some of the business applications include bundling of products based on customer data of purchase of products. Clustering consumers on basis of their reviews about a service or product into difference categories. These insights help in business decisions.
  6. Regression — In statistics often we come across problems which require us to find a relationship between two variables in our data. We explore how change in one variable can affect the other variable. That is where we use regression. In these algorithms our machine tries to find the best line that can be fit into our data something similar to slope of a line. Our algorithm tries to find the line with best slope to minimize error in our data. This line can be used then by us to make predictions be it in form of values or in the form of probability
  7. Rule System — Rule based machine learning algorithms work on set of rules that are either predefined by us or they develop those rules themselves. These algorithms are less agile when creating a model or making predictions based on that model. But due to their less agility they are faster in doing what they are set to do. These are used to analyze huge chunks of data or even data which is constantly growing. They are also used for classification and can work faster than other classification algorithms. Accuracy might take a hit here but in machine learning its always a trade-off between accuracy and speed.
  8. Regularization — These techniques or algorithms are used in conjunction with regression or classification algorithms to reduce the effect of over-fitting in data. Tweaking of these algorithm allows to find the right balance between training the model well and the way it predicts. Many times we have too many variables or their effect on modelling is huge in those cases regularization works to reduce that high variance in our model.
  9. Ensemble — This method of machine learning combines various models to produce one optimal predictive model. They are usually better than single models as they are combining different models to achieve higher accuracy. More like a perfect life partner. Only drawback being that they might be slow in running. Sometimes when speed is required over accuracy we can switch over to rule-based algorithms or regression.
  10. Neural Networks — Based on the principle of working of neurons in brain, Neural networks are complex algorithms that work in layers. These layers take input from previous layer and do processing. More layers increase the accuracy but make algorithm slow. They work better than other algorithms but due to their computationally expensive characteristics did not gain popularity in past. But now they are back in business as the processors have improved. They are being used for sales forecasting, financial predictions, anomaly detection in data and language processing.
  11. Deep Learning — Deep learning algorithms use neural networks and constantly evolve the model they work on using new data. They learn and better themselves just like a human being would. Self-driving cars are based on these algorithms. I know what you are thinking here, it is what AI is based on. The real terminator will be based on this algorithm but we are way far away from it. There are full businesses running on deep learning algorithms. New delivery systems are under development which use these algorithms, Google’s AlphaGo is another example. Deep learning structures algorithms in layers and uses them to make decisions.

12. Classifier – Naive Bayes classifier is a classification algorithm which works on Bayes theorem. It assumes that all the features exist independent of each other. It is supervised machine learning algorithm and we need to provide both data and labels to train it.

TEE Backspace
Design a site like this with WordPress.com
Get started