Author: Nako

How To Add Customize Menu for Original WordPress Theme

This is one of the articles about project “Create Original Theme in WordPress”.

GOAL

Today’s goal is to add original menu to the “Theme Customizer” as below.

The Theme Customizer can be opened from “Appearance” > “Customize” in WordPress admin page.

If the “Excerpt” is selected the excerpts of the post are displayed as page list and if the “Post” is selected the posts themselves are displayed as page list.

The difference between “Excerpt” page list and “Post” page list

Environment

WordPress 5.5.1
XAMPP 7.4.10

Method

Reference: Theme Customization API in wordpress.org

1. Define customizer-register function

Add function to register new customizer to the hook “customize_register” in functions.php of your theme.

(more…)

Implementation Of Ajax (Search Suggestion)

GOAL

Today’s goal is to implement a search suggestion as below. The suggestion should be displayed without page transition while inputting the search word.

Environment

Windows10
XAMPP 7.4.10

What is Ajax

AJAX, Asynchronous JavaScript And XML, is a term that refers to a group of Web development techniques for asynchronous communication on the client side using JavaScript. Please check “What Is AJAX (and Asynchronous Communication)?” for details about ajax.

The following is a brief explanation about the ajax mechanism.

How Ajax works

In Ajax, the 2 system “sending the request and getting the response from the server” and “get the data from the browser and reflect the received data to the browser” are separated. So users can operate on the browser while waiting the response.

This image has an empty alt attribute; its file name is image-2.png
(more…)

What Is AJAX (and Asynchronous Communication)?

AJAX, Asynchronous JavaScript And XML, is a combination of web development techniques to establish asynchronous communication on the client side.

GOAL

Today’s goal is to summarize what is Asynchronous communication and AJAX, Asynchronous JavaScript and XML. This is for beginners in web development.

What are synchronous communication and asynchronous communication?

Synchronous communication is a communication method which matches the timing of data transmission by sender and the one of data reception by recipient. On the other hands, asynchronous communication is a communication method which doesn’t match these timings of data exchange.

The meaning of the word “Synchronous” changes according to the context. For example, at the physical level, it means to synchronize clock frequencies in communication. In web application, it means to synchronize the timing to send request to the server and the timing to get response from the server. The following is a description in the context of a web application.

<!--more-->

Synchronous communication

Synchronous communication on the web matches the timing when the client send the request and the timing when the client get the response from the server. In other words, client does no process once it sends the request until it receives the response.

Examples of synchronous communication

Waiting for loading when accessing a web page
Waiting for page move after pressing the button to send the answer


Advantages and disadvantages of synchronous communication

  • Advantages
    • Client can surely get a response to the request
    • The order of processing does not change
  • Disadvantages
    • Cannot operate until response is obtained
    • It sometimes takes a long waiting time

Asynchronous communication

Asynchronous communication on web allows user to do another process while waiting response. Users can continue to operate after request sending because the reception processing will be done without freezing after receiving the response.。

Examples of asynchronous communication

  • On the search page a suggestion is displayed when you enter a search term
  • Users can search and move while loading the map (Reference: Google Maps)

Advantages and disadvantages of asynchronous communication

  • Advantages
    • No perceived waiting time
    • It is possible to refresh only a part of the page (other parts can be operated during that time)
  • Disadvantages
    • Implementation is complicated
    • A large amount of asynchronous communication increases the load on the server

What is AJAX?

AJAX, Asynchronous JavaScript And XML, is a term that refers to a group of Web development techniques for asynchronous communication on the client side using JavaScript. (Not a single programming language or tool).

For example the following are techniques of Ajax. (reference: AJAX Documentation)

How Ajax works

In Ajax, the 2 system “sending the request and getting the response from the server” and “get the data from the browser and reflect the received data to the browser” are separated. So users can operate on the browser while waiting the response.

This image has an empty alt attribute; its file name is image-2.png

The system which manage exchange of the data between server and client is called “Ajax engine”.

Advantages of Ajax

Ajax has the same advantages as the asynchronous communication’s advantages above such as “No perceived waiting time”.

Additionally, ajax enables the display change without page transition. Generally, the HTTP response body contains html itself. So, a new html page will be received and page transition will occur after waiting. (Related article: What is http request/response?). Ajax can change the contents without causing this page transition.

Implementation of Ajax

XMLHttpRequest (XHR) can be used for Ajax implementation.

Please check “Implementation Of Ajax (Search Suggestion)” for a concrete example.

How To Create JSON Data In PHP

JSON is used for data exchange in PHP. But how can I create json data in php and pass it to JavaScript?

GOAL

Today’s goal is to generate Json data from PHP array and get the data in JavaScript. This can be used when getting data from the server in PHP and processing the data in JavaScript.

Method

1. Create a nested array data

<?php
$teachers = []
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

You can create the nested array with for loop, too.

<?php
$teachers = [];
$data_set = [["101", "Poppins", "music"],["102", "Dolittle", "natural history"],["103", "Snape", "pharmacy"]];
for($i=0; $i < count($data_set); $i++){
    $teacher = $teachers_list[$i];
    $teachers += array($teacher[0] => array("name" => $teacher[1], "class" => $teacher[2]));
}
?>

2. Generate Json with json_encode() function

<?php
echo json_encode($teachers);
?>
//output => {"101":{"name":"Poppins","class":"music"},"102":{"name":"Dolittle","class":"natural history"},"103":{"name":"Snape","class":"pharmacy"}}

3. Get the data in JavaScript

Get the json string from the variable $teachers and convert the string to the Object with JSON.parse().

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(k in json_obj){ // get keys
        var teacher = json_obj[k];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
/*
--console output--
name: Poppins
class: music
name: Dolittle
class: natural history
name: Snape
class: pharmacy
*/
</script>

Source Code

The Completed Code is as below.

<?php
$teachers = [];
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(i in json_obj){
        var teacher = json_obj[i];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
</script>

Create Search Form with PHP

GOAL

Today’s goal is to create search form to find the name from the database.

Environment

Windows10
XAMPP 7.4.10

Method

This is an adjusted version of the code in “Access MySQL with PHP in XAMPP“. So please check the article first.

Search form

Use post method and the form is named “word” as below.

<form action="" method="POST">
    <label>Name:</label>
    <input type="text" name="word" /> <input type="submit" value="Search" />
</form>
(more…)

How Get Value With Format in Python

GOAL

Today’s goal is to check if the string follows the format and to get the value according to the format. The following is an example.

# the format is "My name is <NAME>, the phone number is <NUMBER>" (<NUMBER> is separated by 2 '-')

str1 = "My name is Nako, the phone number is 123-456-7890"
#str1 follows the format, <NAME> is "Nako" and <NUMBER> is "1234567890" in this case

str2 = "I am Nako, the phone number is 1234567890"
# str2 doesn't follow the format

Environment

Python 3.8.7

Method

Use regular expression

Create regular expression object with re.compile(pattern, flags=0). It can be used to check if the string matches the pattern or not by using Pattern.match(string) function.

# coding: utf-8
import re

str1 = "My name is Nako, the phone number is 123-456-7890"
str2 = "I am Nako, the phone number is 1234567890"

prog = re.compile("My name is [A-Za-z]+, the phone number is [0-9]+-[0-9]+-[0-9]+$")

print(prog.match(str1))
# output => <re.Match object; span=(0, 49), match='My name is Nako, the phone number is 123-456-7890>
print(prog.match(str2))
# output => None

You can get the value by grouping the regular expression using (). The value of each group can be get with Match.group([group1, …])

gourp(0) is the entire match and group(n) is the match for n-th group.

# coding: utf-8
import re

str1 = "My name is Nako, the phone number is 123-456-7890"

prog = re.compile("My name is ([A-Za-z]+), the phone number is ([0-9]+-[0-9]+-[0-9]+)$")

match = prog.match(str1)
if match:
    print(match.group(0)) # output => My name is Nako, the phone number is 123-456-7890
    print(match.group(1)) # output => Nako
    print(match.group(2)) # output => 123-456-7890
    print(match.group(2).replace('-', '')) # output => 1234567890

Postscript

$ as the end of the string

You should use $ that matches the end of the string because Pattern.match(string) finds zero or more characters at the beginning of string match.

fullmatch method

If you don’t use $, you should use Pattern.fullmatch(string) instead of Pattern.match(string).

str1 = "My name is Nako, the phone number is 123-456-7890ABCDE"
prog = re.compile("My name is ([A-Za-z]+), the phone number is ([0-9]+-[0-9]+-[0-9]+)")

print(prog.match(str1))
# output => <re.Match object; span=(0, 49), match='My name is Nako, the phone number is 123-456-7890>

print(prog.fullmatch(str1))
# output => None

pattern with length limitation

The length of the input can be limited by {} in regular expression.

str1 = "My name is Nako, the phone number is 123-456-78900000"
prog = re.compile("My name is ([A-Za-z]+), the phone number is ([0-9]{3}-[0-9]{3}-[0-9]{4})$")

print(prog.match(str1))
# output => None

[AttributeError] module ‘tensorflow’ has no attribute ‘Session’

When I was trying the exercise of TensorFlow Programming Concepts, an error “AttributeError module ‘tensorflow’ has no attribute ‘Session'” occurred.

Error Detail

The code run in Google Colaboratory is the following.Generic HighlightingEnlighterJS Syntax Highlighter

This image has an empty alt attribute; its file name is 38dbab30e4232a9115cd0f972a88d428.png
An attribute error

Cause

tf.Session can be used in tensorflow 1.x version, while it cannot be used in 2.x version.

(more…)

What is Github Gist?

GOAL

Today’s goal is to understand what is Gist and how to use it.

What is Gist?

Gist is a source code sharing service provided by GitHub. Gist manages all or parts of the source of projects or documentations such as a manual.

Gist is used for sharing or versioning source codes or documentations.

The difference between Git, GitHub and Gist.

Git: Git is a distributed revision control system. Refer git page for details.
GitHub: GitHub is a source code hosting service for version control and collaboration using Git. It is a service for sharing the entire project as a repository.
Gist: Gist is a one of the services provided by GitHub. It is a service for sharing the source codes and documentations. You can create a Gist of a single source or a part of the source, too.

(more…)

[Tips] How To Get Attribute By String In Python

GOAL

Today’s goal is to access attributes of objects by the string of its name.
What I’d like to do is the following.

class MyClass:
  class_attr = 1
  def __init__(self, num):
    self.attr1 = 100 + num
    self.attr2 = 200 + num
  def func1(self):
    print("this is func1")
    
item = MyClass(5)
attr = "attr2"
print(item.get_attr(attr)) # output should be 205

Environment

Python 3.8.7

Method

Use getattr(objectname) to get attributes. And setattr(objectname) to set attributes.

item = MyClass(5)
attr = "attr2"
print(getattr(item, attr))
# output => 205

You can get methods and class variable too.

getattr(item, "func1")()
# output => this is func1

print(getattr(MyClass, "class_attr"))
# output => 1

Bidirectional Dict In Python

GOAL

Today’s goal is discuss the method of implementing bidirectional dictionary in Python.

Environment

Windows 10
Python 3.8.7

What is bidirectional dictionary?

Dictionary or hash table is a data structure composed of a collection of (key, map) pair where keys are unique, which is known as an associative array, map, symbol table, or dictionary. The advantage of dictionary is its small time complexity O(1).

job_dict = {"John":"director", "Mike":"designer", "Anna":"designer", "Lisa":"engineer"}
# job_dict["Mike"] returns "designer"
Outline image of hash table or dictionary

Bidirectional dictionary I’d like is the dictionary that return the value when the key is given and return keys when the value is given.

# what I'd like to do
job_bidict = {"John":"director", "Mike":"designer", "Anna":"designer", "Lisa":"engineer"}
# job_bidict["Mike"] returns "designer"
# job_bidict["designer"] returns "Mike", "Anna" or ["Mike", "Anna"]

Method

I introduces 3 methods and pros and cons of them.

<!--more-->

Method 1. Use bidict library

Install and import bidict library according to bidict documentation.

pip install bidict
from bidict import bidict
job_bidict = bidict({"John":"director", "Mike":"designer", "Lisa":"engineer"}) # The values should be unique

print(job_bidict["Mike"])
# output => designer
print(job_bidict.inverse["designer"])
# output => Mike
  • Advantage
    • It’s easy to implement.
    • The library has many useful functions
  • Disadvantage
    • The values of bidict should be unique.
    • The file size grows when the program is distributed.

Advantage: It’s easy to implement.
Disadvantage: The file size grows when you distribute the program.

Method 2. Use 2 dicts in a class

class MyBidict:
  def __init__(self, init_dict):
    self.dict_normal = {} # normal dict to store (key, values)
    self.dict_inverse = {} # normal dict to store (value. keys)
    for key in init_dict.keys():
      self.add_item(key, init_dict[key])
  def add_item(self, key, value):
    if key in self.dict_normal:
      self.dict_normal[key].append(value)
    else:
      self.dict_normal[key] = [value]
    if value in self.dict_inverse:
      self.dict_inverse[value].append(key)
    else:
      self.dict_inverse[value] = [key]
  def get_item(self, key):
    return self.dict_normal[key]
  def get_item_inverse(self, value):
    return self.dict_inverse[value] 

job_bidict = MyBidict({"John":"director", "Mike":"designer", "Anna":"designer", "Lisa":"engineer"})

print(job_bidict.get_item("Mike"))
# output => ['designer']
print(job_bidict.get_item_inverse("designer"))
# output => ['Mike', 'Anna']
  • Advantage
    • You can customize the specification of the dict such as whether it allows duplicate values or not.
    • You can add functions you need.
  • Disadvantage
    • It takes time and effort to implement.
    • The specification is sometimes different from the built-in dict.

Method 3. Implement Bidict class as a subclass of dict

class MyBidict(dict):
  def __init__(self, init_dict):
    self.inverse = {}
    dict.__init__(self, init_dict)
    for key, value in init_dict.items():
      self.inverse[value] = key
  def __setitem__(self, key, value):
    dict.__setitem__(self, key, value)
    self.inverse.__setitem__(value, key)

job_bidict = MyBidict({"John":"director", "Mike":"designer", "Anna":"designer", "Lisa":"engineer"})

print(job_bidict["Mike"])
# output => designer 
print(job_bidict.inverse["designer"])
# output => Anna
  • Advantage
    • It’s relatively easy to implement.
    • You can customize the specification of the dict such as whether it allows duplicate values or not.
    • The functions of built-in dict can be still used.
  • Disadvantage
    • It takes a little time and effort to implement.
    • The original function can destroy the specifications of built-in dict.