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
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.
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)
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.
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.
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.
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
# 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.
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
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.
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).
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"]
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.