Friday, September 10, 2021

Private Communications

 

It's the 21st century and a man and wife cannot have a truly private conversation. A meeting of the “The Young College Republicans" is almost certainly bugged, Libertarians ... Yep. In fact any politically incorrect group is going to probably be bugged. Jewish organizations, Christian organizations are all politically incorrect today. There is no guarantee that your home isn't bugged. Your chat on the internet is probably being logged. If Trump can be bugged, anyone can be bugged!!! The truth of the matter is there is a high probability the NSA or your government's version of the NSA is logged into your home router trying to see what their citizens are up to. In the past they would have had to get a warrant, this is not true today. In the past, any intelligence or policing institution would have to go to a judge and present credible evidence a crime is or has been committed to get a warrant. But in today's world the NSA goes wherever it damned well pleases and the Constitution be damned. Even worse, it is reasonable to assume that Corporate America is also spying on us.


Is it possible to have a private conversation in today's world? Well, you can rule out any conversation over the Internet. TOR Chat is supposed to be pretty good, but I heavily suspect the NSA has a back door into that, but one could setup a private network off the Internet and then turn off all wireless and then have a chat. The problem is that most chat servers and clients keep logs. Note in the table that privacy is not cheap. Also, this does sort of require everyone to be in the same room.


Here is my solution, and it isn't pretty, but it should work.  I realize what I am talking about here can be used to plan and help commit crimes, but that is the price of living in a free society, and I am not willing to give up those freedoms.


One, select your hardware. I have tried using a Raspberry Pi. It was just a model 3B+ and it proved adequate for small groups, I'm not sure how many connections it can handle. I suspect it could handle ten to 15 connections without getting hammered too badly. I have played around with an Orange Pi Zero and it also works, but by the time you pay shipping it is almost as expensive as a Raspberry Pi 3B+ and the Raspberry Pi performs better. You will also need a Raspberry Pi power supply and a Micro SD card. You will also need a CAT cable for each laptop and one for the Raspberry Pi which can be purchased at your local office store or one can get about five for as little as $20 USA on Amazon. You will need a basic network switch, one can be purchased on Amazon for as little as $10 USA.


The cheapest switches have between 4-8 ports, the two-port models are useless for this, since the Raspberry Pi uses a port. One needs at least three ports to do this. If a larger group wants to chat, I have seen used switch models in the range of 18, 24 and 48 port models on Amazon. They run around $50, but some are considerably more expensive.

Hardware Cost


Raspberry Pi 3B+ 35.00
Raspberry Pi PS 6.00
Network Switch 10.00
Micros SD Card 7.00
CAT Cables 20.00


Total 78.00            

 

 

Software: 

We need to install some software. First, I used the following website to install Linux on a Raspberry Pi headless:

https://hackernoon.com/raspberry-pi-headless-install-462ccabd75d0


Next I ssh'd in (From Windows use Putty to sign in) and ran the following commands:

sudo apt-get update

sudo apt-get upgrade (This takes a while) 

sudo apt-get install fpc fpc-source  

sudo apt-get install dnsmasq 

Instead of doing an install of Free Pascal from the repository (2nd line), it is probably better to grab the install files from FreePascal.org. When I tried to install from the repository I did not get all of my source files. 

Add following command to /etc/dnsmasq.conf:  

dhcp-range=192.168.0.0,192.168.0.255,12h

 

In the /etc/network/interfaces file, you need to add the following. This will 
make sure you Raspberry Pi always has an ip address of 192.168.0.200:

iface eth0 inet static
address 192.168.0.200
netmask 255.255.255.0
gateway 192.168.0.1


We need a chat client and server that does not keep a log. Most apps do keep a log even though they may not tell you about it. If a log is kept, your computer could be searched and any log could be discovered. I think a primitive app is the safest solution, even though it is not encrypted. As long as it runs on a private network and not hooked up to the Internet, one should be safe. Warning: wireless should be turned off on all laptops.


I came across such an app written in Free Pascal years ago. It think it was an example program and somewhere in the example programs included with Lazarus. I have a copy of the original source code and it is compile-able with a little effort. There could be similar apps written in c or python. I know it will compile for Linux and Windows. The source code is only about 150 lines in the main app, but it does use some libraries. I have watched “lsof” output for files that are connected with it and have not found anything suspicious. The program just runs in a command prompt with no GUI, so it not going to be too pretty. For highest level of security, once the the Raspberry Pi is set up and the laptops used should not touch the Internet.


I have zipped up the source code into a zip file named chatsrc. You will need to compile lclient.pp and lserver.pp by typing in a command prompt


fpc lclient.pp

fpc lserver.pp


The program lclient.pp will need to be compiled on your Linux or Windows laptops: lserver.pp will need to be compiled on your Raspberry Pi. This may be a little touchy as each version of FreePascal has different numbers and you may have to make some slight adjustments in the source code. Look for something like “{$i /usr/share/fpcsrc/n.n.n” where n.n.n is something like “3.0.4”: this will be be your Free Pascal version number, and it needs to be consistent with your version number on your system. This will be in the files lcommon.pp, levents.pp and lnet.pp multiple times. This will need to be done on the laptop where you are compiling the client and on the Raspberry Pi where you will compile the server.


I will confess I have made a slight modification to lclient.pp, I have altered it so the person sending a message's name is in color (yellow) to make the chat session more readable. I have a 2nd version of lclient out there. That one allows you to send private messages to the different users on the chat. I only have that working for Linux laptops currently. Windows uses the command “ipconfig” to display the computer's IP address while Linux uses “ifconfig”. To get that to work, “ifconfig” in the source code would need to be changed to “ipconfig” and then the search in the for loop would need to be changed to what ever Windows prints to grab the right address.


To start a chat, first ssh into the Raspberry Pi and start the server. You will need to be in the directory where you compiled it.


sudo ./lserver 1000


This will start the server on port 1000


Then on your laptops go to the directory where the lcient program exists, type the following in a command prompt


./lclient 192.168.0.200 1000 MyName


MyName is going to be your chat id. You can have multiple chats going on different ports, by starting lserver with differnt port numbers:

sudo ./lserver 1000 &

sudo ./lserver 1001 &

sudo ./lserver 1002 &

You could use ports 1001 and 1002 as subcommitee chats. If you are using ports 1001 and 1002 for subcommitee chats, the chat clients that need to connecct to said chats would need to adjust the 2nd parm to that port number. Yes it is possible to have more then one lclient running on a single laptop.  To send a private message using v2 of the client, note the ip address of the recipent and type “PM192.168.0.nnn Send me your secret message”

nnn would be their last octet.

Performance:  I had three laptops hooked up and I saw ZERO cpu utilization in Linux's Top commandd for the lserver process and only about .04% memory use.  I tried sending a bunch of fake messages across and still saw zero cpu utilization, so it may be possible to run quite a few chat clients at once.

 



Friday, August 28, 2020

Bufflhooligans at Neal Smith

Only saw three of them. The first guy walking along the fence near western end of the Bison area, and then two more north eastern corner. They were a couple hundred yards away from me and I was shooting at high zoom. I ccaught one of them rolling around.

Sunday, August 16, 2020

The Great Derecho of 2020 and my Internet Provider

 

As you may have heard, the Great Derecho of 2020 knocked out our power, this was on Monday 8/10/2020. I was at work and didn't see the storm, but felt it effects as I saw many Midwestern Financial Institutions loose power. By the time I got home, the power was back on in my direct neighborhood. What we didn't have was Internet.


Our source of internet became my phone where I would use it as a hotspot and then connect my laptop to it. By Thursday, the internet came back on, but it was spotty and slow. It would still drop for hours at a time and the bandwidth we were getting was terrible. Linux has a tool to estimate your band width, so I did put some statistics together:



Upload (Megabits)

Download (Megabits)




Min

1.46

0.08

Max

3.76

1.71

Average

2.56

0.58

Std. Dev.

0.99

0.65



Just for the record, the Download speed is supposed to be much higher then upload speed. We knew Mediacom was having trouble and I figured it was them. I didn't see any point in calling them because they have lied to me before. They will always tell me it is my modem, that way they don't have to refund any money.


Cheryl's employer lost their modem with the storm or right before. I thought we should wait a few days and see returns to normal. By Saturday it had not. Cheryl wanted to know if we should buy a new modem, but I wasn't convinced it was our modem yet. So after dinner Saturday night, I googled “How to check your cable modem” or something like that. I found the following page:

https://www.wikihow.com/Diagnose-Cable-Modem-Issues


It turns out all I had to do was point my web browser to 192.168.100.1 and enter a user and password found on the modem and I could see the condition of the router. The above web page had what the good values were and what the power ranges needed to be. I went over the stats for a good twenty minutes and realized there was nothing wrong with our modem.


After going over all the stats, I decided to run the Linux Command to test the speed. The upload speed was over 3 megabits, but the download speed was now over 78 megabits. Hmm, I wonder if my big brother Mediacom was watching me. That improvement happened awfully close to me checking the modem state and now it was normal. I know they are talking to my modem all of the time. It is possible they can watch to see when the internal web page is accessed.

Monday, May 18, 2020

MariaDB Database Engines

I wrote some simple programs to hit MariaDB and compare the performance of the different database engines.  The programs were written in Free Pascal.  These numbers are just for comparing the approximate performance of each engine.


Database Engine
Insert Key Update Non Key Update Key Delete Non Key Delete







Desktop i7-8700 with relative fast HD











Memory
15151.52 13513.51 10869.57 12195.12 12195.12
MyISAM
12195.12 8771.93 1340.48 10416.67 8196.72
Aria
359.97 319.49 320.51 364.96 375.38
InnoDB
114.31 98.60 94.75 97.81 96.28







Laptop i7-3470QM with a slow laptop HD











Memory
9090.91 5494.51 6410.26 6410.26 6944.44
MyISAM
7575.76 5747.13 963.39 7142.86 4716.98
Aria
81.10 84.70 83.88 83.22 83.84
InnoDB
18.68 17.03 16.90 15.65 15.00



The numbers listed for Insert, are inserts per second. Updates and deletes are Updates/Deletes per second. I guess I was dumbfounded at the speed MyISAM performs at. Ok, it has the low feature set.  But it's feature set is similar to Aria and it is giving performance almost as good as the Memory Engine!!!  For home use or playing around with data on a laptop, MyISAM seems like a good choice.  I know InnoDB has a lot of features and is the best choice for a production database.

Sunday, April 26, 2020

Star Neighborhoods


I was talking to a friend about the distance of stars. He stated that he knew or could look up the distance from Earth to some star, but he had never seen published the distance from Starx to its neighboring stars. I said I have a list of stars in a MySQL table and I think one of them has the x, y, z coordinates.

Well, I was wrong, I do not have them recorded in the x, y, z coordinate system. But I do have Right Ascension, Declination and distance. The best table I have has 46,000 nearby stars and their RA, Dec and distance in Parsecs. Guess what, if One has RA, Dec. and distance, One can convert to the x, y and z coordinate system.

x = Sin(Dec) * Sin(RA) * Dist
y = Sin(Dec) * Cos(RA) * Dist
z = Cos(Dec) * Dist

With any two stars in an x, y, z coordinate, the distance between them can be calculated by:

Distance = ((x1-x2)2 + (y1-y2)2 + (z1-z2)2).5

The computer Language I like is Lazarus, which is an Object Pascal based “Rapid Application Development” or RAD System. It involves placing forms on the screen and then objects on those forms, One can then attach source code to each object. Lazarus itself and the Free Pascal it is based on generates relatively fast programs.

Lazarus can pull data out of MySQL tables using using ZeosDBO, all one has to do is put in the Database Name, your user and password and the table you want to access. So I wrote a little program to grab one star, like Vega, calculate it's x, y, z coordinates. select all the data out of the database table and load it into an array while calculating their x, y, z coordinates and distance from the primary star. Sort the output and display the nearest 50 or so stars.

This takes about 20 seconds to calculate, most of that is the sort. I used the ShellSort algorithm, I know the Quick Sort is the fastest, but with this amount of data the Shell Sort does as well, the Quick Sort algorithm doesn't start to out perform the Shell Sort until it reaches about 75,000 items to be sorted.

This all became a fun diversion during the Pandemic.

Here is an image of my program after calculating the star distances from Vega.  Well it turns out that one can have even more fun with this data.  It is possible to graph it.  Unfortunatly, I don't know how to graph it to a 3rd plane conventionally.  But it is possible to use color to represent distance on the x plane.  The following list maps color to distance with red being closest and purple being the furthest:

  1. Red
  2. Fuschia
  3. Maroon
  4. Yellow
  5. Olive
  6. Green
  7. Lime
  8. Mint
  9. Teal
  10. Aqua
  11. Sky Blue
  12. Blue
  13. Purple
The star catalog I am using only has 46,000 stars in it when we know there are over 1.0e+8 stars in our galaxy, so many stars aren't there.  The data I have is also less then perfect, so please be forgiving. The larger the dataset, the harder this will be to do. You may note that most stars name's begin with GL, well the Gliese names are the most populated of star names in my catalog.  The Poper and Bayer names are mostly blank. The distances very based on the neighborhood selected, I am seeing ranges on the low side of +/- 1LY and on the high side of +/-4LY. Here are a few of my graphs:

The Vega Neighborhood


The Sirius Neighborhood

Arcturus







Saturday, February 18, 2017

Amusements

I ran across the following article in a math geek book I found at Barnes and Noble:




So basically, you sum up the values of ever element that is in an even position and then you take every element in an odd position and multiply it by two.  Then if it is a single digit add it to the sum.  If it is two digits, add each digit to the sum separately.  Then if the answer is evenly divisible by 10, it is a possible valid Card number.

So I came up with the following Pascal source:

For i := 1 to 16 Do
  Begin
    If (i Mod 2) <> 0 Then
      If CardArray[i] < 5 Then
        OddSum := OddSum + (CardArray[i] * 2)
      Else
      Begin
        OddSum := OddSum + 1;
        OddSum := OddSum + ((CardArray[i] * 2) - 10);
      End
    Else
      EvenSum := EvenSum + CardArray[i];
    ValidEdit.Text := IntToStr(EvenSum+OddSum);
  End;

CardArray is a table with the first sixteen elements loaded with each digit of a credit card and after running it through the above source it gave me a number evenly divisible by 10.  Except one time when I got one of the digits wrong, then it was not evenly divisible by 10.  So I have to say the algorithm works.

Cool, Huh???

Wednesday, September 23, 2015

Followup to Fun with SQL

I increased the size of my test:



In the first graph it showed that the improvement had stopped at about 80 processes.  I'm going with that, since on one of the runs with 80 processes, Mariadb started kicking out "No connections available" error.  It only happened on one run.  The 2nd chart shows that it is still improving, I will admit that I was having trouble getting accurate numbers with that many processes running. 

75 processes seems ok, anything more and I think I was not making much additional progress.

Saturday, September 19, 2015

Fun with SQL

MySQL/MariaDB is supposed to be one of the fastest SQL servers on the market.  But is that accurate? They do very fast selects (extracting data), but inserts and updates are considerably slower. 

As a standard benchmark, I ran a program that inserted about 50,000 records into a table.  This was done on an i5 desktop running MariaDB under Linux Mint.  I broke it down into approximate 5000 record segments.  The input file of random data was created in Free Pascal and written to a Pascal flat file.





The chart is pretty much flat over this group of data. My experience suggests, though, that if I put more data through, the inserts would slow down as the file got bigger.

[Notes on Pascal: The CLI Pascal program could not read from the Pascal Flat File Format and then write to the database.  I suspect that there is a memory leak in the standard Pascal File Calls that was damaging the MySQL data structures.  I ended up just reading the data and writing it out to Standard Output.  I then piped this to MariaDB's command prompt.  Neither process used very much CPU: 

0.7   2 19670 myuser    /usr/bin/mysql
0.0   3 19692 myuser    ./LoadData

Why would I even write data in the Pascal Format?  It's an obsolete file format that has been around since at least 1980.  But, it is very fast.  On my i5 laptop, it can write data out as fast as 11 million records per minute.  So, if I was in a situation where I had to capture a lot of data, I would consider it.]

In truth, writing to MariaDB is not very fast. If you had a lot of data to import, it would be like watching molasses in January.  I have worked with MySQL and it's performance isn't any better.

Both of these database servers are supposed to be multi-threaded.  In theory it should be possible to increase throughput by running multiple inserts at the same time. But is that the case?

This show the average of how many records per second were being added when the table had 50,000 records in it.  The X axis is the number of processes and the Y axis is the records being added per second.




This graph shows how long it takes in seconds to reach 20,000 records.  Again the X axis is number of processes and the Y axis is the number of seconds required.  These two graphs are basically mirror images of each other. 

The conclusion:  Running multiple processes to increase throughput does work.  I have increased throughput by more than a factor of 10.  I have not hit the point of diminishing returns. Even on a home computer, MariaDB could handle 25 proccesses hitting the same table.  What's more, it's not taking that big of a hit on the CPU.

0.0   3 20744 myuser    ./LoadData2 PersonFile01      0
0.0   1 20748 myuser    ./LoadData2 PersonFile02      0
0.0   2 20754 myuser    ./LoadData2 PersonFile03      0
0.0   0 20759 myuser    ./LoadData2 PersonFile04      0
0.0   2 20765 myuser    ./LoadData2 PersonFile05      0

0.1   1 20745 myuser    /usr/bin/mysql --binary-mod   0
0.1   0 20749 myuser    /usr/bin/mysql --binary-mod   0
0.1   0 20755 myuser    /usr/bin/mysql --binary-mod   0
0.1   1 20761 myuser    /usr/bin/mysql --binary-mod   0
0.2   0 20766 myuser    /usr/bin/mysql --binary-mod   0







The above shows the load these were adding to my system while running five processes.  The first column shows the cpu load for that specific process, and the second column shows what cpu the process is running on.  Total for all 10 processes isn't much more than 0.6% spread across four CPU's.  Even running 25  processes, I was only pulling 2.3% load spread across four processors. That is only about 0.6% per CPU.







Sunday, April 05, 2015

MySQL Access Comparison

Just for fun, I compared MySQL access times from several different languages.  Python which is REAL popular these days, Free Pascal (An Open Source Object Pascal Compiler) and c (gcc).

Here are the results:



And from the point of view of Transactions per second

I was really kind of surprised how much better c did then Free Pascal.  I did a comparison several months ago that showed c and Free Pascal performing much closer to each other, so I assume the Free Pascal Library needs some work.  Also, I was surprised that by changing MariaDB from a my-small to my-medium I saw no improvement.  Below is a chart from the sort comparison: 


Friday, January 09, 2015

How to Write your own Monitoring App


First the problem:

Some Linux users like to run servers and or services. You could be running Samba, MySQL, Web Servers and maybe even a Chat Server. You could be running these all on your desktop, but that wastes electricity and uses up your desktop when you may want to use it for other purposes. A primary desktop would need to be up all the time, and many desktops have a high end video card which uses as much electricity as the rest of the computer combined. Why not run them all on one or more headless servers? This could be one big processor running multiple virtual machines or on single less powerful computers (maybe even “Raspberry Pi”s) each supporting a specific service. A headless i3 could come in between 60 -70 watts, while a gaming rig can use 400 watts or more.

But how do you monitor them? You can download and install Nagios or something like that, but it could be more fun to write your own. You can design the GUI app to fit your needs, not what someone says you need. Maybe you want the app to sit in a little corner and not use up much space, or maybe you want it large on one computer all by itself.

Second, what language (Compiler or Interpreter) are you going to use.

There are many choices and in reality you can make almost any of them work, so it is going to come down to your personal choice. Okay, I like Lazarus, which is a GUI front end to the Free Pascal Compiler. It is a true compiler and generates relatively fast code. Lazarus will run circles around Python performance-wise, but in truth c++ will outperform Lazarus. Pascal is easier to write then c++ and you can have a working app in much less time. In performance tests I have seen, Free Pascal generated programs that run on average 2.5 times longer then an equal program written in c++, but Python will run about 6 times longer then an equivalent Free Pascal program. Your results may vary, in the below charts, Python took 50 times longer to run then Free Pascal, and the differences between Free Pascal and c was marginal. On the learning curve, Python is the easiest to learn (but not by much), followed by Pascal, and the hardest to learn is c++.



If you think that this charts is irrelevant to computing today. Sorting is a fairly good way to compare performance of compilers or interpreters and the source code is freely available on the internet. And lastly, I have an application that had a Procedure that updated a MySQL Table with a sort value that would change on a daily basis, and then sort the output. It had a performance issue due to the fact that MySQL updates data slowly, but can select it very quickly. I rewrote the application to load the table into RAM, update it there and then run an internal sort. This Procedure went from running minutes to milliseconds. There may come a point where it will become necessary to run a sort on data inside your program.

The Algorithm.

I knew that I wanted to start ssh processes into each server and then process the returned data. When you put the command right after the address to connect to, the session will terminate after the command is run. I have written previous programs that have started background processes that just returned the output, which could then be processed by the main application. This is relatively easy to do; you need to add Process to the uses clause and declare a TProcess and a TStringList Variable.

uses
Classes, SysUtils, Process;

Var
MyProcess: TProcesss;
MyStrList: TStringList;

And then the following needs added at the point where you want to start the process:

MyStrList := TStringList.Create;
MyProcess := TProcess.Create(nil);
MyProcess.CommandLine := 'ValidLinuxCommand';
MyProcess.Options := MyProcess.Options + [poWaitOnExit, poUsePipes];
MyProcess.Execute;
MyStrList.LoadFromStream(MyProcess.Output);
{ Do something with the String List Here }
MyStrList.Free;
MyProcess.Free;

That isn't really all that hard, and it will work as long as the output is smaller then about 2k. If it is going to be larger, we need to add more complexity. This is explained in detail at:

http://wiki.lazarus.freepascal.org/Executing_External_Programs

Initially I was thinking it would need to be a multi-threaded app, and I started researching that option. I was afraid one stuck process could freeze the whole application. The more I looked at that option, however, the more complex it sounded. Each thread could not update graphical components within the main app (that can crash the Window Manager), so they would have to update basic objects (Integers, Strings, floats and such) within the main thread and then have the main thread update the component objects and then there is added complexity of needing to use Critical Sections (this would prevent more than one thread from accessing shared object at the same time).

I then thought, well maybe I can start each subprocess and not have to wait on it finishing, and then just create a loop that tests each subprocess's state. If the subprocess has finished, process its output and then just start a replacement subprocess. No messing around with all of the multi-thread stuff.

So first of all I declared a simple record:

TProcessRec = Record
      Process: TProcess;
      Addr,
      User,
      Password: String;
      Pct: Double;
      StrList: TStringList;
End;

And then declared an Array of that Record:

ProcessTable: Array[1..KKArraySize] of TProcessRec;

Now we want to set up the main loop, but first we want to prime the pump and start all the ssh processes needed:

For i := 1 to KKArraySize Do
Begin
      If Length(ProcessTable[i].Addr) > 1 Then
      Begin
            ProcessTable[i].Process := TProcess.Create(nil);
            ProcessTable[i].StrList:=TStringList.Create;
            ProcessTable[i].Process.CommandLine := CmdLine(i);
            ProcessTable[i].Process.Options :=                           ProcessTable[1].Process.Options +
                   [poUsePipes];
            ProcessTable[i].Process.Execute;
      end;
end;

I am just looping through my Array and checking to see if there is an address defined, if so start a ssh. Note, I removed the poWaitOnExit from ProcessOptions because we don't want to stop and wait for each process to finish. Instead, we will test the subprocess in the next step. Also note that I am calling a function CmdLine to build the Linux command I want to run. Below is that function:

Function CmdLine(i: Integer): String;
Begin
         CmdLine := 'sshpass -p "' + ProcessTable[i].Password +
         '"   ssh ' + ProcessTable[i].User + '@' +
                  ProcessTable[i].Addr + ' sar -u 1 1;free';
end;

This is pretty simple, it just uses the Array to fill in user, Password and Address. As you can also note, I am using sshpass to pass the password to ssh and am also using the sar utility. sshpass can be found in most repositories and sar is part of the sysstat monitoring utilities which also can be found in most repositories. I found sar gave cpu utilization numbers very close to what top gives, so that is why I ended up using it. sar or whatever utility you end up using will have to be installed on all of the servers you are monitoring.

Now finally the main loop:

EndTime := Now + EncodeTime(0, 0, 5, 0); // 5 Seconds
While Now < EndTime do
Begin
      Application.ProcessMessages;
      Sleep(10);
End;
For i:=1 to KKArraySize Do
Begin
       If Length(ProcessTable[i].Addr) > 1 Then
       Begin
              If ProcessTable[i].Process.Running = False then
              Begin
                     ProcessTable[i].StrList.LoadFromStream
                           (ProcessTable[i].Process.Output);
                     For j:=0 to ProcessTable[i].StrList.Count-1 Do
                     Begin
                             If copy(ProcessTable[i].StrList[j],1,7)
                  = 'Average' then
                             Begin
                                   Sum :=
                   SumProcessorStats 
                   (ProcessTable[i].StrList[j]);
                                   PctStr := Format('%5.2f', [Sum]);
                                   ProcessTable[i].Pct := Sum;
                              End;
                      End;
                      BladeSG.Cells[i,2] := Format('%5.2f',
              [ProcessTable[i].Pct]);
                      ProcessTable[i].StrList.Clear;
                      ProcessTable[i].Process.CommandLine := CmdLine(i);
                      ProcessTable[i].Process.Options := 
              ProcessTable[1].Process.Options +
              [poUsePipes];
                      ProcessTable[i].Process.Execute;
               End;
        End;
End;

Well, that is a mouthful! This is all in a Repeat ... Forever Loop, well, almost a forever loop because I do have a way to break it. The first While Loop, is just a means to get the App to wait 5 seconds before checking on the status of all of our background processes. The first two If statements seem silly and seem like they should be combined, but ... Since I only initialized a Process in the array where the Addr field had actual data in it, if we ran the “Process.Running” statement for an uninitialized Process variable, the app would have had a memory error and would have crashed.

ProcessTable[i].StrList.LoadFromStream
(ProcessTable[i].Process.Output);

―— just loads the output from our ssh into our TStringList, which was declared in our Array. A TStringList is actually just an array of Strings and the output of the sar utility has the word Average in it. So the following block of code just sums up the output from the sar utility. I summed up user, nice, and system values listed from the sar utility. You may decide on a different strategy.

For j:=0 to ProcessTable[i].StrList.Count-1 Do
Begin
       If copy(ProcessTable[i].StrList[j],1,7) = 'Average' then
       Begin
              Sum := SumProcessorStats (ProcessTable[i].StrList[j]);
              PctStr := Format('%5.2f', [Sum]);
              ProcessTable[i].Pct := Sum;
        End;
End;

SumProcessorStats is a function and it does the adding of the sar outputed fields together.

Function SumProcessorStats(s: String): Double;
Var
     UsrStr, NiceStr, SysStr: String;
     Sum, Dbl: Double;
begin
       UsrStr := copy(s,24,6);
       NiceStr := copy(s,34,6);
       SysStr := copy(s,44,6);
       Sum := 0.0;
       Dbl := StrToFloat(UsrStr);
       Sum := Sum + Dbl;
       Dbl := StrToFloat(NiceStr);
       Sum := Sum + Dbl;
       Dbl := StrToFloat(SysStr);
       Sum := Sum + Dbl;
       SumProcessorStats := Sum;
end;

Finally, since the previous subprocess had finished, this last piece starts a new subprocess:

ProcessTable[i].StrList.Clear;
ProcessTable[i].Process.CommandLine := CmdLine(i);
ProcessTable[i].Process.Options := ProcessTable[1].Process.Options +
[poUsePipes];
ProcessTable[i].Process.Execute;

Security is an issue here. The addresses, users and passwords could be hard-coded into your App. If somebody broke into your system though, they could get all of your passwords by looking at your source code. An improvement would be to have all that info in MySQL Table and have the Operator prompted for the password to access that table. Even better would be to have the data all encrypted and have the Operator prompted for a decryption key.

At some point, we may want to start sending e-mails out when certain conditions occur. Like if one of the servers is maxed out for several minutes, or if a server becomes unresponsive. Sending out e-mails isn't that hard to add. There is a library that can be downloaded for free called Synapse (http://wiki.freepascal.org/Synapse). You would need to download the library and add the following libraries to uses clause:

synautil, synacode, blcksock, pop3send, smtpsend

I copied the whole Synapse Library into the directory containing my app, and then whatever Lazarus needed, it would compile. The content of the e-mail would need to be added to a tstringlist and then to send the e-mail, use something similar to the following:

If Not SendTo('ToEmailAddress', 'FromEmailAddress', 'Subject',
'EmailServer', MsgStringList) Then
ShowMessage('E-Mail Didn''t Work');


ToEmailAddress could be your gmail address on your phone, FromEmailAddress would be your regular e-mail address, EmailServer will be your e-mail (Probably something like mail.myservername.com). There is more information on the Wiki Site listed above.


Performance

On an Intel i5, the main thread uses about 6% of the CPU on one core. Very acceptable.

Thursday, November 06, 2014

2014 Midterms

Ok, I am a Republican. A liberal one, but still a Republican.  First of all I  didn't trust the Media and I didn't trust the Media's Polling.  Some of the Polling Firms I was throwing out like Survey/USA and sometimes Rasmussen.  I can show that certain Polling Firms lean further to the left then mean average.  Ok, Rasmussen's poll data on Presidential Approval Rating was way off from companies like Gallup, but their State Senate Polls weren't as bad.

So I flew by my own assumptions:

1. The Media Organisations were for the Democrats and their polling was trying to  manipulate the Electorate instead of inform them.  They were party activists instead of being reporters.

2. They were not estimating turnout correctly. I took the conservative assumption that were off by 5%.  So I adjusted the Democrat numbers down by 2.5% and upped the Republican numbers equally.

3. The Media was using too long of a range of polls.  A Poll taken a month ago was no longer valid, in my opinion.

4. I also thought the Electorate was very angry and election would have a very close correlation to 1978!

So I wrote a little app that used my assumtions and did some calculations.  It's crude but gave me some very good estimates.

This run was ran Tuesday morning, just before the election:


So my program estimated a pickup  for the Republicans of 10 Senators, not bad. I think I did better then the Pundits.  But I kept my mouth shut living in a multi-party family.  Also, my assumptions were incorrect in 2012.

As far as the economy goes, it will not improve until ACA is removed.  My proof is not perfect, it is statistical.  If you take all of the recesions in American history and take an average and standard deviation of their length, you get something like:

Average:  21.5 months
StdDev:    15.75

So, virtually all recessions should be over in (21.5) + (3 * 15.75) = 68.75 months.
That is just under 6 years.  If you don't understand why this is valid, it is because when you have a normal Distribution curve about 68% of all data will occur Plus or minus 1 Standard Deviation of the Mean (Average), 95% of all data will occur plus or minus two Standard Deviations of mean.  And 99.97% of all data will occur within three Standard Deviations of Mean!

Professional Economists do use this and their published results are actually a little more conservative, with a slightly smaller mean and slightly smaller standard deviation.  Which makes my argument just that much stronger.

So why are we still in a recession???  I know we technically we are not in one, but we arn't in a recovery either.  Unemployment is still too high and the only ones doing well, are the top couple of percent.  This is not normal.  The answer is the cost of the ACA is adding about $15,000 dollars to the employers cost for a full time employee per year.  When small business persons run their numbers through their spreadsheets they can't make it work and therefore, they don't risk their money and there is no business expansion.

I would also argue that if the Democratic Party wants to be viable again, they need to drop the ACA.  If they have to over ride a Presidential veto, do it and do it quickly.  If you let the clock run out and the Republicans end up doing it after the 2016 elections they will get all of the credit for an improving economy.

Tuesday, September 03, 2013

 While at the Iowa Star Party we witnessed a Rapture Release cosponsored by Whiterock Conservency and SOAR.  I am posting them here for those who follow this blog instead of my Facebook.