Monday, December 30, 2019

PHP Use of Openssl Encryption

There are a number of encryption methods available in PHP. While they are used in various applications, the main objective here is to talk about a two way encryption/decryption using Openssl.

Openssl is a general cryptography library. PHP has a number of functions that handles openssl. To use openssl you have to create or buy a SSL certificate. Buying from a cert authority means that your certificate are certified authentic. Creating your own private cert has its own use. For the purpose of encryption and decryption, there is no advantage in not using a authentic cert sine your purpose is only between two parties. You can generate ssl private cert using command line Openssl library. I will skip this part as it does not involve using PHP.

A certificate has two keys (a set of strings that can be used for encryption/decryption). One is Private key the other is Public key. By its name, you can see that the former is only used by one party. The Public key can be distributed to many others. Its uses is discussed below.

The user that has a private key uses it to encrypt a string. Any one with the corresponding Public key can decrypt it. Any one with Public key can use it to encrypt a string but only the one with the corresponding Private key can decrypt it. The former is for sending common data to many people that has the Public key. Its actual use is for a specific purpose detailed later. The latter is for many people to send data to a central person. This means people can sent personal data to a site but only the site can read it.

Lets talk about using Public Key to encrypt and decrypt data. First we do public key encryption.

$aok = openssl_public_encrypt($data. $encrypted, $pubvlicpemkey);

$aok is just for checking whether the encryption is successful. $data is the raw data to be encrypted. $encrypted is simply the variable to store the encrypted data. $publicpemkey is the Public Key in PEM form.

To prevent data transmission error, we need to convert the encrypted data into a special text format using "base64_enconde($encrypted)".

On the receiving end, we need to use bse64_decrypt($encrypted) to return back the encrypted string before using

$aok = openssl_private_decrypt($encrypted, $data, $privatepemkey);

As usual $data is the decrypted data.This method is basically used by sites to let customer send personal data or banking transaction. Since only the site is able to decrypt, the transaction is secure.

Next we use private key to encrypt. Its use is to ensure that the sender is authentic (if it uses recognized cert authority certs or has a understanding between sender and receiver.) Its main use is just to sign the data that was send in plain or encrypted text. It usually involve two certs each exchange their public cert with the other.

The method use is

openssl_private_encrypt($data, $encrypted, $privatepemkey);

The other party then uses the following to decrypt the data.

openssl_pubhlic_decrypt($encrypted, $data, $publicpemkey);

Since only the sender that has the private key can encrypt the data to be decrypted by the receiver with the public key, the receiver basically can be sure that the data is from the sender with the private key.

Another use of the Openssl is to send a signature. A signature generally follows a text and is used to prove that the text is authentic from a specific person. It is similar to sending a private key encrypted message but with a layer of security added called hashing (a method of mapping a data to a specific size).

$hashed = hash($method, $data, false);

There are many methods of hashing. Usually we uses 'sha256'. The last parameter specify using raw output to ensure that nothing is changed.

The next method encrypts the data using a different functtion

openssl_sign($hashed, $signature, $privatepemkey);

Obviously, by sending the above does not quite let the receiver know how to identify the signature. The signature is basically used to accompany a plain text or an encrypted text. If it is encrypted then the receiver has to decrypt it first using methods previously discussed above.

On the receiving end, the following decrypts the signature. Before doing anything, the receiver has to hash the text (plain or encrypted) that comes with the signature. If the text is encrypted then the receiver has to decrypt it first. The following function then is used to verify that the hash matches the signature.

$hashed = hash($method, $data, false);
openssl_verify($hashed, $signature, $publicpemkey, OPENSSL_ALGO_SHA256);

The last parameter specify 'sha256' hash method.

Note that if the text is encrypted, it usually use a public key from the receiver otherwise the encrypted text is already proving that the sender is authentic.





Monday, October 28, 2019

National Step Challenge Can it be Completed?

I joined and faithfully completed National Step Challenge season 4.  I continue to join Season 5. Season 5 added 2 more tiers to MVPA in Season 5 when I started the season, I was thrown back to Season 4 MVPA tier 5. So my Season 5 cannot start huh? Am I a completer then?

On calculating the time needed to complete 6 tiers of MVPA, I was surprised that it requires 187 days (40 points a day maximum). The challenge period is 189 days. To start MVPA challenge  I am supposed to complete the steps challenge tier 2. Minus the bonus, It takes at least 37.5 days to complete tier 2 of the step challenge. Adding it to 187 days, it is impossible to complete.

Now that I am thrown back to Season 4, I need another 75 days. It is equivalent to I cannot be a completer in season 5. I decided to quit completely. It is a challenge with a set period so it should start and stop within the period. HPB make it so difficult to complete. I wonder why.

By the way, in Season 4, HPB actually recommends 150 minutes per week for MVPA. That is 5 days of 30 minutes MVPA. Which translate to 200 points. Therefore, to complete the 6 tiers (7500 points), you need 37.5 weeks which is 262.5 days. Another puzzling figure. Absolutely mission impossible.



Saturday, September 28, 2019

One Plus One

Most kids will know that 1 + 1 = 2. But to adults. It has quite a variety of answers. The following is a list of answers.


  1. 1 + 1 =2 (simple arithmetic)
  2. 1 + 1 =11 (simply put two 1 together)
  3. 1 + 1 = II (roman number)
  4. 1 + 1 = ∥ (parallel symbol
  5. 1 + 1 = 1 (logical OR function)
  6. 1 + 1 = 1 (overlap two 1)
  7. 1+1 = 王 (if you turn your head side ways)
  8. 1+1 = 土 (if you overlap two 1 with + and look side ways)
  9. 1 + 1= 士 (same way except using a smaller 1)
  10. 1 + 1 = 干 (same way but turn your head the other side)
The above is based on the principle that the ones stays in its natural vertical form. If you can place any one or both side ways,  It has another dimension.

  1. 1 + 1 = T (one vertical one horizontal)
  2. 1 + 1 = + (same as above but move the horizontal one to the middle.
  3. 1 + 1 = L (move the horizontal one all the way down and to the right.
  4. 1 + 1 = Γ ( Greek Gamma character)
  5. 1 + 1 = 二 (both placed horizontally)
  6. 1 + 1 = 一 (overlap both horizontally)
  7. 1 + 1 = V (bottom end touch each other)
  8. 1 + 1 = X (both touch center)
  9. 1 + 1 = Λ (Greek Lamda character)
  10. 1 + 1 = = (equal symbol)
  11. 1 + 1 = > (greater than symbol)
  12. 1 + 1 = < (less than symbol)
The above is not an exhaustive list. There are probably more that can be made out of it.

So, don't just take things as is, think out of the box and you find a lot of simple things can be viewed in different ways.



Sunday, September 08, 2019

Defending our faith

As a Christian, we are to defend our faith. However, does it means that we have to do it every time some one says something against our faith?

Singapore have a law on Maintenance of Religious Harmony Act. Which explicitly prohibits "causing feelings of enmity, hatred, ill-will or hostility between different religious groups" (Wikipedia). Some company thus have rules against religious activities and discussions while conducting business.

While in this working environment, if some one starts to provoke you by saying something against Christianity, do we have to defend our faith regardless?

Jesus have a solution. Matthew 22:17-21 says "Give to Caesar what is Caesar's and to God what is God's". Jesus is saying that taxes are taxes and religion is religion. While you are doing your duty, you should do your duty and not mix religion in it.  Why break the rule just because some one did not observe religious harmony and badmouth Christianity?

On a Facebook page, some friend of mine posted two religious quotes side by side. One is based on Old Testament (Joshua 6:21) total destruction of a city another portray his religion as a peaceful religion ( i will not disclose the religion nor the quote). Obviously, he is trying to portray Christianity as violent and destructive compared to the peaceful nature of his religion.

Now I can defend Old Testament by saying that it is the act that is commanded by God for a specific purpose and reason at that specific time. It cannot be applied to Christianity in general. The quote is simply out of context. I will not venture into the person's religious quote and draw a different picture. By doing so I am in breach of causing hostility on other religion. The person is probably trying to provoke a hostile response.

By Just defending our Bible, I already achieved the purpose of defending our faith. There is no need to bring down the other part of the statement by the person. It served the purpose and still maintains religious harmony.



Tuesday, July 02, 2019

中国五千年跳不出去的九大定律

拜读了题目文章后 (刊在《历史开讲了》),觉得那是人类的问题不是中国独特问题。这问题是在于权力与控制。如果中国是真正民主制度就可大大减少定律问题。下面是我的见解。

1.象牙筷定律

这是人类贪婪的特性。没有限制的话就会造成恶性循环。如果不是民主制度话就无法限制这恶性循环。

2.兔死狗烹定律

这是人类独裁问题。当没有敌人的时候就会内斗。没有法律的话就会造成此现象。没有民主的话就权力至上无法无天。

3. 包围定律

这也是人类独裁问题。因为没有民主就成绝对包围。

4.敌戒定律

生存法律。有了民主才会有”敌人“。敌对政党时常会盯着你。那你会时时提防被攻击。

5.朋党定律

朋党不是问题。那个社会没有朋党? 不受控制的朋党才是大问题。民主制度才能有些控制。

6. 黄宗义定律

独裁主义以上制下。最下层的老百姓跟本无能力反抗。如果是民主制的话就不是大问题。

7.五世而斩定律

这也是独裁主义才会有的。庸才会被推为首领。民主制是民选。无能的话跟本上不了台。

8. 权大欺主定律

人类通病。权大就不受控制特别是掌握握军权的。民主制度也无法。这就看其他军人会不会反抗。人民也可以反抗不过只手对不了枪杆。

9. 皮毛定律

也是独裁问题。 语言自由是民主制才有的。只有霸权社会才控制语言自由。

总而言之,有真正的民主制度才会防止这九大定律的重复。当然民主制度也有其弊病。




Sunday, June 23, 2019

Navigation system for Blind using Passive RFID

It is always troublesome to find our way in a big shopping center. This applies to Visual Handicapped as well as sighted. Currently, the best way is to use beacons system to provide navigation and information around the beacon.

To maintain the beacon system is not that cheap. Beacons are life beacons that needs power source. In a big building, the number of beacons used is staggering. There are ways and means of using other technologies to provide navigational needs for the Visual Handicapped. Below is one which I think is viable.

RFID has been in the market for decades already. Passive RFID is just a piece of paper attached with a tiny chip and an antenna. It is very cheap and can be bough in bulk. Each RFID is unique. Therefore, if you are near enough with a reader, you could know which RFID is near you.

Firstly, you need to lay breadcrumb (RFID) trails on every path in the building. A mapping of each RFID and nearby POI (point of interest) is necessary for navigation. The breadcrumbs should be spaced at a fixed distance apart. Ideally, at every junction, a breadcrumb should be right in the center of it.

User using RFID reader could then able to read the breadcrumbs as he/she walks along the path. By limiting the range to just able to read at least 2 breadcrumbs, The system will be able to know which direction the user is moving since the last one will drop off and new ones will appear. With the mapping, you can then tell the direction of movement.

At junctions, user should be informed that there are branches and alert user on the possible direction and POI. User can then make a decision to move to the specific direction.

The app can be in a form of a map of the building with blinking dots to show current user position and with voice assistance for Visual Handicapped to use. It will have a list of POI to assist users. It will be good to have a search function that finds the nearest point matching the search string like "exit". A highlighted path to the search string, like map navigation, will be helpful.

Since passive RFID is cheap and need no power, it is just a install and forget type. Any missing RFID can be replaced with the same ID. It is, therefore, simple and cheap to maintain such a system.

Now the expensive part is the RFID reader. It needs to be Wi-Fi enabled so that it can be integrated with hand phone app. The app has to be custom designed to use it as navigation system. All these costs eats into user's budget. However, it reduces the cost of building owners so that they will be more willing to invest in the infrastructure. With many building owners willing to install the system, the cost of the application can then be reduced thus lessens the financial burden of users.

Since this navigation can be used for sighted, it becomes universal navigational system thus further reduces the costs. It is a win-win situation.

This system need not to be indoors only. Outdoor place like parks can install such system using weather proof containers for the RFID. It can even be used for temporary venues like a carnival. The uses are multiple.





GSX Questions

It was something that was started quite sometime ago but wasn't made compulsory. Questions are a set of data that was posted as questions and user is supposed to answer it accordingly. Its as simple as that.

However, the Questions are nested questions and no fixed pattern. Previously, a pointer is used if there are nested questions. It could not work that well. Recently GSX changed the data format to JSON and the Questions were set in nested JSON format. This makes it much easier to follow as we just need to traverse the nesting structure typical of JSON.

Fortunately, Questions uses fixed format in the form of Questions and Answers. The nesting is always at the Answers array or as a array in the Questions level.

This blog talks about how to traverse through the list and nested questions using FileMaker. As it is, GSX returns a JSON. Since FileMaker has JSON functions that can read nodes from JSON stored in fields or variables and the format (path) of reading the nodes is like "XX.YY.ZZ". If it is an array, just add the array number after the node name like "XX[0]".

The method of traversing the nodes is simple. The path is stored in a variable.  We start off with $trees="questionDetails[0].trees[0].questions[0].answers[0]". Using JSONListKeys($json;$trees) we can get a list of keys. If there is no answers, we remove the last node and add 1 to the previous level array then repeats to find the answer keys.

Upon finding the answer, we post the question and gets an answer from user. Depends on answer type, user have to respond accordingly. Once finished answering then we look for nested questions in the answer. If there are nested questions, we add one new level after answers and go to the first question in the nested questions.

In the nesting, if there are more items in the array, we go into the next item in the array and look for questions or answers. If there is no more or no questions/answers. we back up one level and see if there are more items in that level.

In this way, we could go into the nesting systematically and back up to the higher level if there are no more array item.

GSX requires you provide the question ID when you answers. So you must create an answer JSON that corresponds to the Questions. Every time you add a question/answer level you need to add the array first so that when you answer, you can write the answers using the same $trees array.

I won't be diving into showing examples of traversing. Do figure out how to do it yourself.




Thursday, June 20, 2019

Communicating with Apple Web Services (GSX) via Filemaker 2

My previous blog on the same subject is 3 years ago. Since then Apple has changed from using XML to JSON as a means of transferring data. Therefore there is a need to show how to do it with JSON.

JSON (Javascript Object Notion) by its name, is a Javascript feature but it has extended its use to many other applications. It is a format of storing data just like XML except it is more human readable when you format it nicely.

Fortunately, FileMaker has caught up with the latest trend by including a few JSON related functions. It is not that easy to use those functions to compose JSON but it is very much easy to get data from JSON.

To create simple JSON you just need to use $example =JSONSetElement("";"elementkey";"elementvalue";1) and it will create a nice JSON '{"elementkey":"elementvalue"}'. However, if you want to insert nested JSON then it is a bit tedious.

For example, you want to create a key that contains an array with one key and  value. First you must create the key and value as a JSON like last paragraph. Then you have to create an array to contain that JSON like $array= JSONSetElement("[]";0;$example;3).

Finally you then create the root element like $root=JSONSetElement("";"root";$array;4). You have created a JSON '{"root":[{"elementkey":"elementvalue"}]}'. This format is generally used by Apple in GSX in both request and response.

If it is a simple JSON that need to store a small set of data with fixed keys, it is better to create the JSON with unique values for each element that needs to be changed like "~!1", "~!2" etc. After that use substitute function to replace the "~!x" sequence. Two lines instead of 3. In actual fact, one line encompassing both action can be done by just using the JSON as source of substitute directly. In this way you could reuse the same code repeatedly or even store it as custom function.

The parameters used in JSONSetElement can be found at. JSONSetElement.

Getting values from "elementkey" in the above JSON is easy. $value=JSONGetElement($root;"root[0].elementkey")

If you looking at this blog first then I suggest you go to the previous blog on the same subject first to get an understanding.


Saturday, June 15, 2019

Exercising by Heart Beat

Normally one would want to exercise with some repeatable routine. Some go for fixed time. Others go for distance. More health conscious people will want to stick to an exercise/training routine depends on the type of exercise done.

I usually go for speed based exercise as I do walking and cycling. Recently, I am obsessed with heart beat based exercise. It is not scientifically proven but based on the ample talks about lowering heart beat, a controlled heart beat during exercise moves one towards lowering it. It will be good for controlling hyper tension, high blood pressure.

Before launching on the methods used to keep heart beat within a range during exercise, it will be good to about the basis of heart beat measure. According to scientific figures, the maximum heart beat a human can have is 220 beats per minute (BPM). Individual person's maximum heart beat is 220 - number of years of your age. People who exercise constantly will have their maximum heart beat considerably higher than normal people's heart beat.

Minimum heart beat depends on individual. Some athletes have resting heart beat around 40 BPM. Most people's heart beat is between 60 - 100 BPM. Children aged 6 -15 is around 70 - 100 BPM.

My range of heart beat I want to control while walking is 99 - 108. It is at the lower end of medium exercise range. The reason is to avoid excessive sweating. It is not easy to control the heart beat at this range as any lower than 98 BPM means I am out of medium exercise range. This is especially true if I don't do warm up before walking. It tends to fluctuate very much till the body is warm up.

Monitoring heart beat while cycling is a bit dangerous. However, all vehicle drivers including motor-cyclist have to keep monitoring their speed while driving. Their speed is very much higher. Just ensure that the coast is clear before you take a peek at the heart beat monitor. I only do it while cycling on long stretch of PCN or cycling path.

Depending on the type of cycling done, the heart beat range can be different. Usually, if I want to go for speed, I abandoned heart beat monitoring. Just go fast till your limit. On the other hand, for standard exercising, I go for 155 plus minus 10. It is at a comfortable heart rate without stress. Coincidentally, 155 is my maximum heart beat (theoretically).  Individuals must try and error to find a comfortable cycling speed for themselves.

At 155 BPM the speed of travel is basically below the 25 KPH limit of PCN. It is therefore safe and within the regulation.

GARMIN Connect has a stress measurement statistic page. It is to show how often you get stressed. My stress region is generally non existing except at the beginning  and end of exercise. It could be a result of my method used but there is no proof and I don't bother to prove it.

Below is a typical walking speed and heart beat chart.






Friday, May 24, 2019

Windows 10 grinds to a halt

First it was an extra application called Chromium get installed. Unable to install thus use IObit uninstaller to remove the program.

After that the computer suddenly goes unresponsive. It takes over a minute to respond to clicks.  Task manager indicated that CPU usage is low and Disk activity is low. It just puzzles me.

Nothing I do could solve the problem. Manage to get Win 10 to boot to safe mode by forcing it to close then start again 3 times.

Even at safe mode, it also responses not that well. On searching from internet, it was suggested to check page faults. Starts Performance Monitor and adds page fault. The percentage is 100. Netizens suggest using Sysinternals, Process Explorer. Downloaded it and run. There is an item that has more than one million page fault. It is Mcafee.

Uninstalled it and the system works as normal. One problem still persists. Windows Defender antivirus shows that "the virus protection is managed by other manager". No facility to set it back. Well, that is not part of this issue.



Tuesday, April 30, 2019

Profiling Tan Kin Lian

A person is gauged by his/her acts and speech. There seems to be quite a lot of news from Tan Kin Lian. The following is extracted from internet. I don't draw conclusion. It is up to you.

He portrayed NUS voyeur Nicholas Lim and mother as victims of the case just because the actual victim post his picture and name on Instagram.  The voyeuristic act is ignored. A "controversial statement" according to Tan Kin Lian himself.

"Paying Johor 15 million a year saves 15 million on defense". He thinks Singapore is going to make war with Malaysia for water. Also the idea of "paying Johor 15 million" is giving Malaysia what they wanted. There is no other way?

He said he will stand for election of enough like minded people come forward to support him. "I will change my mind if I do not see enough of them coming forward". He expects to be ushered into parliament? First he ask for 300 likes on FaceBook then he ask for 1000 after it is achieved.

He posted "Changi Airport custom officer - Are you Mr Tan? Any Tongkat Ali to declare? A traitor tipped him off". After that he claimed he was joking on Twitter. In his earlier post he described how to make Tongkat Ali tea.

He cancelled Grab booking 3 times in a row. Maybe he don't know how Grab works.

He ran in the 2011 Presidential election and forfeited $48,000 because he cannot get enough votes.

 He said on Facebook "I boarded SMRT 857 and found that I was in Mumbai." A statement unbecoming of a presidential candidate. He apologized and deleted the post.

According to some his departure from insurance cooperative is not entirely voluntary.

Some accused him of being a detractor of the presidential election. He instead accused Tan Jee Say of being "the last candidate" thus should consider withdrawal. It is noted that he only got 4.9% vote whereas Tan Jee Say has 25%.

http://tankinlian.blogspot.com/2011/07/sia-website.html is yet another blog of his showing how much he knows about internet of things.

He posted his personal data online and dares people to hack his SingPass. Well, his SingPass got locked out within hours.

The above are just gathered from internet. There is no checks on whether those are false news. At least I don't see any report that they are false news.




Friday, April 26, 2019

NUS Peeping Tom Case

In olden days when internet was not that popular. Any such offence simply gets unnoticed even if the accused gets persecuted. The victim does not have any further say as to whether the punishment is just.

With the IoT, at least the victim can voice out the feeling of injustice. Although the victim's post on social media could be viewed as 'doxxing', it is still a victim's voice. Where else could the victim voice out the frustration.

Netizens have various views and comments even politicians chipped in. The following are comments on some of it.

1. The police. The police have decided not to prosecute the accused based on their reasoning that the offender is just a first offender with no traits of such offensive behavior. They therefore give the accused a 12 month conditional warning. If they prosecute the offender then there will be a permanent record which will ruing a person's life even before he get started in life.

2. NUS. NUS is like any educational institution, which is supposed to uphold individual's privacy and integrity. The initial punishment is suspense from a semester, banned from entering campus residence and write a letter of apology to victim.  I am not here to judge the punishment but it does looks like a slap on the hand. Of course I can't say how much punishment is enough but it is not even near the police's punishment level. There are already 20 NUS previous cases in last 3 years and there is no review on how to stop it. They finally apologize and get to hold a review on this.

3. The accused. Beside being given punishment by Police, NUS, Great Eastern, he only express "no excuse" in a ST interview. No public apology was given  as far as I can see.

4. The victim. As said before, her post could be viewed as 'doxxing'. There are better ways to express frustration than to identify the person with pictures in social media.

5. 'Trial by social media'. Those against voicing out saying it is TBSM. However, if this wasn't brought up, nobody knows about it and the vicious cycle continues unabated and unknown. At least now we know that Police have their reason and NUS no longer wants to keep it quiet.

6. Great Eastern. As a company, it cannot be seen to be doing nothing. Firing the accused is the only way out.

7. Agrarian. The company cuts ties with NUS on condition that NUS expel the accused. I don't think this is the right way. It becomes issuing a threat to NUS. Others simply says that the company join in to the media rush to be heard and seen, a typical business tactic.

8. A blogger seems to be biased against the victim in her lengthy blog on the issue. She question about the rights of the accused future. One other post that talks about the blog question how she feels if she or her family member is the victim.

9. Tan Kin Lian is giving support to the accused. He portrayed them as victims. If he is referring to 'doxxing' then it may be true. It depends on who is viewing the incident at what instance? I will be grossly unjust if the focus is only on the consequence of the victim's action than the voyeur's action. It reminds me of the "Singapore Kindness movement" which sides with the perpetrator rather than the wronged.

9. Right to be forgotten. Singapore has this Personal Data Protection Act in place. This should give the accused back his life.




Monday, March 25, 2019

Evaluation of Careeach HR

The Careeach HR is a free tracker provided by Health Promotion Board. The following is a comparison with Garmin Forerunner 935. The comparison is one way. That is to say only compare what Careeach HR has to Forerunner similar functionality only. It is unfair to compare with all the available features of Forerunner 935.

1. Steps - Steps are fundamental feature however it is noted that Careeach HR always track about 10% less compared to Garmin even the steps setting are the same. Garmin seems to show slightly more steps than usual.

2. Heart Rate - Careeach heart rate measurements are very unstable. It can go above 150 while Forerunner shows a modest sub 90. The measurement can simply drops well below 80 while exercising and can drop out of continuous measure mode unexpectedly. Its auto mode is most unreliable. I always turn on continuous mode while exercising. Garmin shows a bit less accurate in auto mode but function well in continuous mode. I can use Garmin to control the heart beat rate but not Careeach. The latter heart beat goes up and down too much and too quickly. Careeach calculates max heart rate according to age. It will buzz user to slow down if the heart rate goes beyond heavy range. Garmin does not buzz user and its range is fixed percentage.

3. Display of the Careeach tracker is always off but can be activated by hand or a twist of the hand but often have to make very large angle swing of arm in order to activate it. Garmin does not have this feature as its display is always on. Both tracker will switch over to clock mode if it not in continuous measure mode. Garmin heart rate display will switch to clock mode after a while but it will stay if it is displayed in sports tracking mode.

4. Upload of data is a hassle. At times the HPB App has to be turned off and on a few times to make it update. Sometimes, the whole hand phone has to be rebooted to get it to work. Garmin update to HPB is via its apps. Although two steps are required but the updates are usually reliable.

5. Charging of Careeach is via USB but the display can some times go straight into full by just plugging in the tracker. The full charge display can stay till it run suddenly out of juice thus lost valuable data. Turning off and on the tracker does not help. Garmin charging can be a bit of problem due to contact issues but never have wrong display issue.

6. Careeach states that its tracker is splash proof. However, one tracker died after going though a light drizzle. Had to replace it. Garmin is water proof up to 50 meters.

7. Battery life of Careeach is way too low to be compared to Garmin. But it can last at least 10 hour of continuous heart beat tracking mode. It could last 2 days or more on normal mode.

8. Careeach will buzz user if they stay static for too long. I am not sure Garmin has it.

For a free device, Careeach HR could be used for tracking steps. Heart rate is at best good for indicator only. Just don't exercise in the rain or use quick charger to charge it.




Monday, March 18, 2019

Time and light

I am fascinated about time. There are already two blogs on the subject. This blog is to further elaborate on it against light.

The concept of time has already been discussed in earlier blogs. Light is the visible element that enables us to see things when light reflects on it. The speed of light is 299792458 meters per second or 1080,000,000 KPH. The speed of light according to WikiPedia is "a universal physical constant". However, X ray and laser seems to be travelling faster than light. Thus it is merely a reference value. Lets just take the reference value as the standard.

Now to see the light one second before now, you have to travel faster than the speed of light. It takes twice the speed to reach the light one second ago if you are travelling in the same direction as light. However, you can't travel in the opposite direction as light has not reflected from the object yet otherwise you would have gone past the object and chasing the light that does not exist. At best, you would have chased the past light in the other direction if the light is always on.

Travelling to see one second of the light before now needs you to travel at double the speed for one second. How long to take before you can catch up with the light one hour before at the same speed?

Now, even when you can see the light one second before, there is nothing you can do to alter it since it is already in the past. Therefore, the theory of changing the events that occur in the past is meaningless since you are only chasing the light not the object.

Even if you are chasing the object that travels away from you, you are merely reaching the object in its present state. There is no way you could have change anything before that state even if you travel ahead of it. You will only be able to see the "now" state of the object. Obviously you could change the environment before the object reach you but its not the future of the object, you are merely changing the "now" state of the environment so that the "now" state of the object and the "now" state of the environment where you are now coincides.

An analogy can be shown by a person shooting an arrow towards a target and another person moved the target before the arrow reaches it. It is just the "now" moment with the two object. 

Frankly speaking. The "now" state occurs on everything simultaneously. Nothing you do that could possibly change the "now" state as time is a measurement of a past event that is not changeable.

On the speed of light thing, a person can only withstand a certain G-force before he black out or dies. 1 G is 9.81 meters per sec. Light speed is 299792458 meters per sec. Without calculation, you will know that it is impossible to survive if you travel at the speed of light.

On the joking side. If there is no light then you can see nothing. How would you be able to chase the light at light speed? How is it possible to see anything?

One other thing, if you are travelling at the speed of light, those light you will see is probably a small area of light that is travelling in the parallel direction. How big a lens would be able to use to view an area of a square meter that is 299792458 meters away?



Friday, January 11, 2019

SQL Aggregate Function as Table using PHP

SQL aggregates as defined by netizens is "perform a calculation on a set of values to return a single scalar value". We often use aggregate functions with GROUP BY, HAVING clause of SELECT statements.

While it is very simple showing tables with just one aggregate or a set of aggregate functions using SELECT and GROUP BY then showing the table as retrieved by the SELECT statement, the table is practically vertical listing in nature. For example

SELECT states, people, SUM(revenue) FROM sales GROUP BY states,people order by states DESC

will show when you format it as table from the query result directly.

People   Revenue   State
Sam       100,000    Selangor
Ken        200,000    Selangor
Joe         100,000    Johor

What if you want to show all the people in the state regardless whether there are sales made by individual and the percentage of their Revenue for the state? It is quite impossible to do it in a single select statement.

The following method shows how to use a single statement to get a list of people and their revenue plus percentage of the group.

First we create an associative array from a list of people and populate it in the array.

$keys=array('Sam','Ken','Joe','April');
$values=array('Revenue'=>0,'Percent'=>0);
$total=0; //totals of the group
$revenue=array_fill_keys($keys,$values)

Retrieve the data using the previous SELECT statement like below. The example uses SQLite.

$db=new SQLite3('revenue.db');
$result=$db->query("select people, sum(revenue) from sales group by people");
while ($row=$result->fetchArray(SQLITE3_NUM))){
$ppl=$row[0];
$revenue[$ppl]['Revenue']=$row[1];
$total +=$row[1];
}
$db->close();
//do calculation and populate table
foreach ($revenue as $key=>$row){
$percent=round($row['Revenue']/$total*100,2);
echo " {$key}
{$row['Revenue']}{$percent}";}

Obviously, the above could be done by 2 queries. One to retrieve the overall total and the other one as above. However, what if you want to list the sales by date and show the people in columns? That is not an easy task representing it in one or two SQL.

You could retrieve the query by revenue grouped by date and people. Your array setting will be

$keys=array('Date','Sam','Ken','Joe','April');
$people=array_fill_keys($keys,$values)
$revenue=Array(); //you could fill the array with every date in the period you choose.

In the while loop, do as follows (assuming date is unix datetime),

$rdate=$row[0]; // the date field
if (!isset($revenue['A'.$rdate])){
$revenue['A'.$rdate] =$people;
$revenue['A'.$rdate]['Date']=date('m/d/Y',$$rdate);
) // set up the array and populate the 'Date' of the array for easy retrieval later
$people = $row[1] //the people field
$revenue['A'.$rdate][$people]=$row[2]; // the revenue field

With this you could populate the whole columns of people with date as first column. Displaying the table is then a breeze using the FOREACH example above.