RSS Feed

PHP programming


PHP was a great programming language in web development. It surpasses the VBscript for ASP and Perl for CGI. It is favoured because of the syntax based C and C++. It supports procedural programming paradigm and object-oriented paradigm. A lot of functions resemble C functions such as printf, fprintf, sprintf, fopen, etc. Similarly, it can work directly to the C library such as expat, zlib, libxml2, etc. A lot of great content management systems (CMS) are written in PHP, such as Drupal, WordPress, Joomla, etc.

However, a lot of new programming language emerges and surpassing it.

Taken from http://skillprogramming.com/top-rated/php-best-practices-1234

Array is passed by value

Because PHP syntax is very similar to C and C++, it can use “&” reference operator and pass the parameter by reference in a function. But this will be very different from other languages such Python and JavaScript. Python and JavaScript function parameters are passed by value for all primitive data types, such as integer, float, string, and boolean; complex data type like object and array are passed by reference, meaning they are mutable, including Date object in JavaScript.

function change_array($arr) {
    $arr[0] = 100;
}

function change_object($obj) {
    $obj->value = 100;
}

function change_many_objects($arr) {
    $arr[0]->value = 100;
}

function change_object_array($obj) {
    $obj->array[0] = 100;
}

class MyObj {
    var $value;
    var $array;
}

function main() {
    $arr = [1, 2, 3];
    $obj = new MyObj();
    $obj->value = 10;

    change_array($arr);
    change_object($obj);

    echo $arr[0], "\n"; // still 1, not changing
    echo $obj->value, "\n"; // changed to 100

    $arr_obj = [ new MyObj(), new MyObj(), new MyObj() ];
    $arr_obj[0]->value = 10;
    change_many_objects($arr_obj);
    echo $arr_obj[0]->value, "\n"; // changed to 100

    $obj_arr = new MyObj();
    $obj_arr->array = [1, 2, 3];
    change_object_array($obj_arr);
    echo $obj_arr->array[0], "\n"; // changed to 100

    $obj_a = new MyObj();
    $obj_a->value = 10;
    $obj_b = $obj_a;
    $obj_b->value = 20;
    echo $obj_a->value, "\n"; // 20
    echo $obj_b->value, "\n"; // 20

    $obj_c = &$obj_a;
    $obj_c->value = 30;
    echo $obj_a->value, "\n"; // 30
    echo $obj_b->value, "\n"; // 30
    echo $obj_c->value, "\n"; // 30
}

main();

In the example above, the function change_array() will not modify the array that being passed, this is because it is passed by value. Unless we use the “&” reference operator.

The function change_object() will change the object that being passed.

One of the key-points of PHP 5 OOP that is often mentioned is that “objects are passed by references by default”. This is not completely true. […]

(from PHP manual)

So, basically, the function parameters are passed by value, even though it is an array. But the object will be dealt differently. We can treat it as a pointer, if you are familiar with C++ “new” operator. In C++, “new” operator will create an instance and return a pointer to the instance. If we understand this concept, then this is how it works in PHP (according to what I know).

Consequently, the function change_many_objects() though the argument is for an array, and an array is passed into it, but the function changes the value of the object within the array. This is because the array stores the pointer to the object instances. The function does change the instance is pointed by the “pointers” stored in the array.

In summary, PHP deals array as value, which is different from Python, JavaScript, and even C and C++. However, PHP deals object as pointer, that is why object is mutable when it is passed to a function.

Other limitations

PHP was created before the technology of RESTful API. PHP focuses on the GET and POST, but not like PUT and DELETE. The HTTP methods are server dependent. As a result, the HTTP server such as Apache requires some extra configurations for PHP to work. Unlike Node and Ruby on Rails, Node itself has a HTTP module; Ruby on Rails has WEBrick HTTP server.

Comparing to the language like Python, Node with JavaScript, Ruby, Lua, it lacks of REPL (read-eval-print loop). Interactive shell is different from REPL. With REPL, the function to print the result in the console is omitted. REPL will print the result whenever the function returns value.

Closure


In JavaScript, we can create closure like this,

var foo = (() => {
  let x = 0;
  return () => {
    return x++;
  }
})();

for (var i = 0; i < 10; i++) {
  var x = foo();
  console.log(x);
}

But translating above code into C++, it cannot work as expected for the variable, unless the variable is outside the lambda function.

// In a function
int x; // variable here
auto foo = [&x]() {
  x = 0;
  return [&x]() {
    return x++;
  };
}();
for (int i = 0; i < 10; i++) {
  int x = foo();
  cout << x << endl;
}

This is because C++ variable can be only accessed in the function scope. After the function return the value, the variable is not accessible anymore.

Similarly, Python can also return the function, but it cannot work as closure like JavaScript. However, Python can create non-primitive variable such as object or list so that the variable will be accessed by reference.

def _foo():
    x = [0]
    def increment():
        x[0] += 1
        return x[0]
    return increment

foo = _foo()
for i in range(10):
    x = foo()
    print(x)

Prayer Clock GTK3

Posted on

My first open source project, Prayer Clock, I moved from SourceForge to GitHub recently. Yeah! Everyone should git!!!

And today I just made some changes, and updated to GTK3.

With GTK 3, I removed the title bar. But not yet successfully moving the menu bar to the icon like Evince or Nautilus.

I plan to convert the right hand panel to WebKitGtk. But this will not be the priority yet.

CSV to something


Just revived my old script into a project in GitHub, csv_to_something. An old simple script that was created to manage some student data. Because the students data were collected through Google Forms, so I convert it to CSV, then from CSV to SQLite. So that I can use the SQL to query whatever data I need.

Using SQLite software such as sqliteman and sqlitebrowser, I can create any new table, grouping, sorting etc.

Then recently, I need some JSON data for the table. So, I revive the script to convert CSV to JSON format. With the functional programming characteristic in JavaScript, manipulating the data becomes more interesting. Using Node or any JavaScript interpreter, we can perform map and reduce. Other useful functions like find and filter can get what I want. Example,

// Read the JSON data as object
let students;
fs.readFile('./table.json', (err, content) => {
  if (err) throw err;
  students = JSON.parse(content);
});
let average = students.reduce((reduced, item) => item.score, 0) / data.length;
let grades = students.map(student => {
  if (student.score >= 90) return 'A';
  else if (student.score < 90 && student.score >= 70) return 'B';
  else return 'Something else';
});

Why SQLite and JSON? Because they are extremely lightweight.

Monty Hall problem and frog riddle

Posted on

Monty Hall paradox

Probability topic is the fundamental concept of the statistics. And machine learning is closely related to statistics. That is why, understand the probability very important if you are doing research, statistics, and machine learning.

Monty Hall is a very interesting problem. It says, if you are given 3 doors to choose. One of them contains a car (which you want), the other two are goats (which you don’t want). After you made your choice, before opening the door, the host will open the door that you didn’t choose yet contains the goat (he knows which door has the goat). Now, if you are given an opportunity to change your choice to another door (which you didn’t choose earlier), are you going to change?

In the first glance, you will feel that whatever you choose, the probability is always 1/3. However, the conditional probability tells you that, if you always make the switch after the host opened the door that has a goat, your probability to win the car will increase to 2/3. What??

In order to prove this, I wrote a Python script.

#!/usr/bin/env python
# This is simulating Monty Hall Paradox

import random


def monty(switch):
    # random shuffle
    doors = [0, 0, 1]  # one of the door contains the car
    random.shuffle(doors)

    openDoor = None

    # choose the first door (not open)
    # if the first door is 1, randomly open the other
    if doors[0] == 1:
        # open the door
        openDoor = random.randint(1, 2)
    else:  # open the door that contains goat
        if doors[1] == 1:
            openDoor = 2
        else:
            openDoor = 1

    # now open the last door
    if not switch:
        return doors[0]
    else:
        if openDoor == 2:
            return doors[1]
        else:
            return doors[2]


def main():
    total = 10000
    car = 0
    for i in range(total):
        car += monty(True)

    print("Always switch the door. Total: {}, car: {}. P = {}".format(total, car, car / total))

    car = 0
    for i in range(total):
        car += monty(False)

    print("No switch the door. Total: {}, car: {}. P = {}".format(total, car, car / total))


main()

Run the code, you will always get the probabilty close to 0.6667 if you always switch the door.

Always switch the door. Total: 10000, car: 6625. P = 0.6625
No switch the door. Total: 10000, car: 3309. P = 0.3309

Frog riddle

Recently I just watched a Youtube about frog riddle.

It also mentions about the conditional probability. Interestingly, quite a lot of comments mentioned that the author is wrong.

In order to prove that the author is correct, I wrote another Python script.

#!/usr/bin/env python

import random

# Frog 0 for female, 1 for male


def create_frog():
    return random.randint(0, 1)


def has_croak(pairs):  # also male
    return 1 in pairs


def has_female(frogs):
    return 0 in frogs


def choose_without_croak(choose_two):
    frogs = [create_frog() for i in range(3)]
    # first frog at the right side
    # second and third at the left side

    if choose_two:
        return has_female(frogs[1:])  # choose two frogs

    return has_female(frogs[0:1])


def main():
    total = 10000
    correct = 0
    for i in range(total):
        correct += choose_without_croak(True)
    print('Just choose two frogs. Total: {}, correct: {}. P = {}'.format(total, correct, correct / total))

    correct = 0
    for i in range(total):
        correct += choose_without_croak(False)
    print('Just choose one frog. Total: {}, correct: {}. P = {}'.format(total, correct, correct / total))


# The exact question is,
# "What is the probability of the frogs in the pair has female,
# given that one of them is male?"
def exact_calculation():
    total = 10000
    croak = 0
    correct = 0
    for i in range(total):
        frogs = [create_frog() for i in range(3)]
        if has_croak(frogs[1:]):
            croak += 1
            if has_female(frogs[1:]):
                correct += 1
    print('Total croak: {}, correct: {}. P = {}'.format(croak, correct, correct / croak))


main()
exact_calculation()

Running the script, you will get

Just choose two frogs. Total: 10000, correct: 7498. P = 0.7498
Just choose one frog. Total: 10000, correct: 4974. P = 0.4974
Total croak: 7474, correct: 4998. P = 0.6687182231736687

Based on the result, if you choose two frogs, the probability of survive is close to 0.75. If you choose one frog, the probability is 0.5.

Now, the tricky part is the probability 0.67 mentioned in the video. The question should be “What is the probability of the frogs in the pair has female, given that one of them is male?”

So, based on the question, my similuation needs to get the total count of the male (that has croak), and within these pairs, count the female frogs.

To convert this into mathematical expression,

P(\text{female frog}) = 0.5

P(\text{at least one male frog}) = 0.75

P(\text{female frog} | \text{at least one male frog}) = \frac{0.5}{0.75} = 0.6667

Then, based on the simulation and calculation, you will get the 0.6667.

Switching display/monitor/screen in Linux

Posted on

Because I am using the Openbox (window manager), and I believe that the laptop Fn+F8 (or whatever combination with Fn) doesn’t work properly on Linux. Because the combination is detected as Super+p (aka Win+p). As a result, I wrote a Perl script to solve the switching display/monitor/screen issue on my laptop.

#!/usr/bin/perl

# This script requires xrandr, and several bash script created by arandr

use strict;
use warnings;

# Edit these global variables based on your setting
my $primary = 'eDP1';
my $secondary = 'HDMI1';

my %scripts = (default => 'default.sh',
               external_only => 'large_only.sh',
               clone => 'clone.sh',
               dual => 'dual.sh');
my $script_path = '~/.screenlayout';
# End edit

sub get_xrandr {
    return `xrandr`;
}

sub is_active {
    my ($monitor) = @_;
    for my $i (0 .. (scalar @$monitor - 1)) {
        my $line = $monitor->[$i];
        if ($line =~ /\*/) {
            return 1;
        }
    }
    return 0;
}

sub is_left {
    my ($monitor) = @_;
    my $line = $monitor->[0];
    if ($line =~ /\d+x\d+\+(\d+)\+\d+/) {
        if ($1 > 0) {
            return 0;
        }
    }
    return 1;
}

sub is_default {
    my ($primary, $secondary) = @_;
    return &is_active($primary) && !&is_active($secondary);
}

sub is_external_only {
    my ($primary, $secondary) = @_;
    return !&is_active($primary) && &is_active($secondary);
}

sub is_clone {
    my ($primary, $secondary) = @_;
    return &is_active($primary) && &is_active($secondary) &&
        &is_left($primary) && &is_left($secondary);;
}

sub is_dual {
    my ($primary, $secondary) = @_;
    return &is_active($primary) && &is_active($secondary) &&
        &is_left($primary) && !&is_left($secondary);;
}

sub get_monitor_style {
    my ($primary, $secondary) = &get_monitor_details;
    if (&is_default($primary, $secondary)) {
        return 'default';
    }
    elsif (&is_clone($primary, $secondary)) {
        return 'clone';
    }
    elsif (&is_dual($primary, $secondary)) {
        return 'dual';
    }
    elsif (&is_external_only($primary, $secondary)) {
        return 'external_only';
    }
    return 'unknown';
}

sub set_monitor_style {
    my ($style) = @_;
    my $script =  join('/', $script_path, $scripts{$style});
    my $cmd = "sh $script";
    `$cmd`;
}

sub switch_next_monitor_style {
    my $current_style = &get_monitor_style;
    if ($current_style eq 'default') {
        &set_monitor_style('external_only');
    }
    elsif ($current_style eq 'external_only') {
        &set_monitor_style('dual');
    }
    elsif ($current_style eq 'dual') {
        &set_monitor_style('clone');
    }
    elsif ($current_style eq 'clone') {
        &set_monitor_style('default');
    }
    else {
        print STDERR "Unknown monitor style";
    }
}

sub switch_prev_monitor_style {
    my $current_style = &get_monitor_style;
    if ($current_style eq 'default') {
        &set_monitor_style('clone');
    }
    elsif ($current_style eq 'external_only') {
        &set_monitor_style('default');
    }
    elsif ($current_style eq 'dual') {
        &set_monitor_style('external_only');
    }
    elsif ($current_style eq 'clone') {
        &set_monitor_style('dual');
    }
    else {
        print STDERR "Unknown monitor style";
    }
}

sub switch_monitor_style {
    my ($prev) = @_;
    if ($prev) {
        &switch_prev_monitor_style;
    }
    else {
        &switch_next_monitor_style;
    }
}

sub get_monitor_details {
    my $xrandr = &get_xrandr;
    my @lines = split(/\n/, $xrandr);

    my @primary_lines;
    my @secondary_lines;
    my $current_block;
    for my $i (0 .. $#lines) {
        my $line = $lines[$i];
        if ($i == 0) {
            next;  # not "continue"
        }
        if ($line =~ /^${primary}/) {
            $current_block = 'primary';
        }
        elsif ($line =~ /^${secondary}/) {
            $current_block = 'secondary';
        }
        if ($current_block eq 'primary') {
            push @primary_lines, $line;
        }
        elsif ($current_block eq 'secondary') {
            push @secondary_lines, $line;
        }
    }
    return (\@primary_lines, \@secondary_lines);
}

sub main {
    my ($prev) = @_;
    &switch_monitor_style($prev);
}

&main(@ARGV);

The script requires “xrandr” command. Furthermore, you need to have some actual switching monitor bash script, which can be created by using ARandR. Example of the script

#!/bin/sh
xrandr --output HDMI1 --primary --mode 1920x1080 --pos 0x0 --rotate normal --output VIRTUAL1 --off --output eDP1 --off

So, my Perl script will detect existing screen setup, whether it is laptop only (“default”), external only (“external_only”), laptop with external monitor at the right side (“dual”), or clone (“clone”) for both monitor sharing same screen. Therefore, we need to create four bash scripts using ARandR for these settings.

To invoke the script,

perl /path/to/monitor_switch.pl

This will switch to the screen to the “next” setting, in this order: default -> external_only -> dual -> clone -> default.

In order to switch between default and external_only, I extended the script with an argument.

perl /path/to/monitor_switch.pl prev

When passing with an argument (any argument), the monitor setup will switch in the reverse order: default -> clone -> dual -> external_only -> default. By this, we can switch between default and external_only easily.

Next, just apply the keybinding (aka hotkey or shortcut) to your preferred combination, then you can switch the screen with your favourite key combination.

Yeay!

P/S: The reason I wrote this script is, when I show my screen on external only, and the power is cut, the screen doesn’t switch to laptop automatically. That means, I cannot see anything to change my screen display. Before the script is written, I blindly use the Terminal, Ctrl+R, and type the keyword and press Enter to switch back. But this is extreemly impractical.

ROC, AUC, WTF?

Posted on

These few days I was spending my whole time to understand this ROC (receiver operating characteristic) curve. In machine learning, ROC is a very common way to evaluate the prediction performance. The AUC (area under curve) of ROC indicates the accuracy of prediction of a classifier.

If you wish to learn more, these two links are the best resources: here and here.

I searched through tutorial and Q and A sites on how to do the plot of ROC and calculating the AUC. The answers were telling me about “cut-off”, “threshold”, or some weird terms. And some answers were telling me to use R package to plot the graph. WTF? I know all of these things. My question was, “How can I plot ROC curve with my classifier?!”

So, there was a real gap between what I had known and the problem I faced. The gap was the classifier that I created cannot be used to plot the ROC curve directly. Because my classifier is a discrete classifier. That is, it just predicts with a label, then checks with actual label whether the prediction is true or false. Though, I can improve this result to true positive, false positive, true negative, and false negative, it can only produce one point in the ROC space.

In order to plot the curve, I need a theshold that can be manipulated to produce a sequence of TPRs (true positive rates) and FPRs (false positive rates). If I have a discrete classifier, I can never produce the sequence of TPRs and FPRs. That is my real problem.

In order to solve this, the only solution is to transform my classifier to ranking or scoring classifier. This is the crucial part that solves my problem. Now, the question is, what is the score here? I believe all classifiers involve some calculations to get some values, then only do the prediction whether the input should be labelled as true or false, even it is a discrete classifier. So, that calculated value is the score! Even if your classifier does a random guess, the random value can be used as the score.

As a result, I need to discard the discrete classification when plotting ROC curve. But the discrete classification is stilled being used during the training. So, by adjusting the theshold, for any input that produces the score greater than the theshold will be labelled as the positive. And from here, I just need to check whether it is true positive or false positive. Continuously adjusting the threshold, I can get a sequence of TPRs and FPRs. Yay. No more discrete classification, and the ROC curve produced.

P/S: Maybe this concept is just as simple as ABC, that is why nobody cares and mention it online.