Adding Query Params to a URL in Ruby with HTTP

The clearest example was in a StackOverflow post

require 'uri'

def add_param(url, param_name, param_value)
 uri = URI(url)
 params = URI.decode_www_form(uri.query || "") << [param_name, param_value]
 uri.query = URI.encode_www_form(params)
 uri.to_s
end

You can pass a map of params key & values and get expected URL.

Another example

 # prepare params.
 params = { 'id' => '12' }

 path = 'http://localhost/'
 uri = URI(path)

 uri.query = URI.encode_www_form(params)

Output

http://localhost?id=12

Reference

Advertisements

How to Change View of Coding Block in WordPress?

Problem

Many times a good WordPress theme does not render code properly. There are problems like too big font making it harder to read the text. I use StackEdit to prepare posts and publish to my blog.

Solution

There is a way to solve this problem with custom CSS.

Description

The posting source is in Markdown. StackEdit translates MarkDown to HTML and posts to the destination. There is not much I could do with the Markdown. However, the theme on the WordPress blog allows me to set a CSS for particular content.
The code blocks are translated to pre blocks in the HTML. So adding a custom rendering for pre block should fix the problem.
I found a CSS snippet from https://wp-mix.com/css-style-pre-tags/.

pre {
	box-sizing: border-box;
	width: 100%;
	padding: 0;
	margin: 0;
	overflow: auto;
	overflow-y: hidden;
	font-size: 12px;
	line-height: 20px;
	background: #efefef;
	border: 1px solid #777;
	background: url('lines.png') repeat 0 0;
	padding: 10px;
	color: #333;
}

Another good reference is https://perishablepress.com/perfect-pre-tags/

This made the code look much much better.

Update

One More Reason to Avoid Ruby Language

Ruby is type unsafe language but it goes a step further and avoids checking dynamically too.

Consider this code

x = :abc
if x == 'abc'
  puts "Symbol and String are two different classes"
else
  puts x.class, 'abc'.class
end

# puts can print a symbol and string alike.
puts x

My Complaints

  • I’m new to Ruby. How could Ruby let a Symbol and String compare, in spite of being aware of their types? Like Python, it can throw an error.
  • How can puts print a Symbol as good as a String

References

Golang: HTTP Client & Server with Query Params

Client

func TestDelete(id string, registered bool) {
      path := "http://localhost:8085/v1/shops"

      // Create client
      client := &http.Client{}

      // Create request
      req, err := http.NewRequest("DELETE", path, nil)
      if err != nil {
          fmt.Println(err)
          return
      }

      q := req.URL.Query()
      q.Add("id", r.UID)
      q.Add("registered", strconv.FormatBool(registered))
      req.URL.RawQuery = q.Encode()

      fmt.Println(req.URL.String())

      // Fetch Request
      resp, err := client.Do(req)
      if err != nil {
          fmt.Println(err)
          return
      }
      defer resp.Body.Close()

      // Read Response Body
      respBody, err := ioutil.ReadAll(resp.Body)
      if err != nil {
          fmt.Println(err)
          return
      }
      
      fmt.Printf("response=%v body=%v", resp, respBody)
      
      // the server returns a slice in response body
      var out []string
      json.Unmarshal(respBody, &out)
      fmt.Printf("response=%s", out)
  }

Server

var ( 
    errQP = errors.New("query param error")
)

func handleDelete(r *http.Request) (*response, error) {
	uid := r.URL.Query().Get("id")
	registration := r.URL.Query().Get("registration")
	if uid == "" || legacy == "" {
		glog.Errorf("handleDeletes: Url Param missing uid=%s registration=%s", uid, registration)
		return nil, errQP
	}

	isRegistered, err := strconv.ParseBool(registered)
	if err != nil {
		glog.Errorf("handleDelete: failed to parse id=%s registration=%s", uid, registration)
		return nil, err
	}
	// deletedShops is a slice
	deletedShops, err := deleteShops(id, isRegistered)
	if err != nil {
		glog.Errorf("handleDelete: failed id=%s registration=%v err=%s", id, isRegistered, err)
		return nil, err
	}

	return &response{
		status: 200,
		body:   deletedShops,
	}, nil
}

Points to Note

  • The above code allows a client to encode query params in a request.
  • The Client gets a slice in response.

C++: Max Product in a Matrix witout Backtrack

Problem

Given a matrix, find the path from top left to bottom right with the greatest product by moving only down and right.

The code is in C++.
The only moves allowed are down and right. The solution works for positive numbers.

Reference

Written with StackEdit.