Tuan Anh

container nerd. k8s || GTFO

Things you may not know about JavaScript array

Let’s begin with creating an array.

arr = [1,2,3];
typeof a;
> "object"

you get object. Wow, so how would I check whether it is an array? Here’s how people usually do it.

if ('[object Array]' === Object.prototype.toString.call(arr)) {
  // your code
}

Next, what if I’m trying to access index that is greater than current length?

arr[10] = 10;

Seems ok!? No index out of range error whatsoever !? Let’s take a look at it again.

> [1, 2, 3, undefined × 7, 100]

Looks like JavaScript automatically expands the array and filled the blank with undefined.

What about if I’m trying to shrink the array

arr.length = 1;
> [1]

JavaScript reduces the size and keeps only elements from 0 to new length.

What if I try something like this

arr['hello'] = 100;
> [1]

Hmm, where is hello? Let’s try to access it again

arr['hello'];
> 100

Phew, it’s still there.

Ok, let’s stop making fun about JavaScript here for now. No matter how you see it, JS is a pretty good language. I kinda the language in general but some stuff, it’s just weird!! Though I have to admit, it’s fun to debug.


Returning query result as json array with Oracle 10G

I love Postgres SQL and one of my favorite feature is ability to return the query result as a JSON array string.

select array_to_json(array_agg(row_to_json(t)))
from (
  select * from my_table
) t

I wonder if I could do the same with Oracle.

Too bad the Oracle version at work is a bit rusty so it’s a bit more troublesome to get it work. We have to first, generate XML using DBMS_XMLGEN and then transform it to JSON using a XLTS stylesheet.

function ref_cursor_to_json (p_ref_cursor in sys_refcursor,
p_max_rows in number := null,
p_skip_rows in number := null) return clob
as
l_ctx         dbms_xmlgen.ctxhandle;
l_num_rows    pls_integer;
l_xml         xmltype;
l_json        xmltype;
l_returnvalue clob;
begin

-- generate JSON from REF Cursor

l_ctx := dbms_xmlgen.newcontext (p_ref_cursor);

dbms_xmlgen.setnullhandling (l_ctx, dbms_xmlgen.empty_tag);

-- for pagination
if p_max_rows is not null then
dbms_xmlgen.setmaxrows (l_ctx, p_max_rows);
end if;

if p_skip_rows is not null then
dbms_xmlgen.setskiprows (l_ctx, p_skip_rows);
end if;

-- get the XML content
l_xml := dbms_xmlgen.getxmltype (l_ctx, dbms_xmlgen.none);

l_num_rows := dbms_xmlgen.getnumrowsprocessed (l_ctx);

dbms_xmlgen.closecontext (l_ctx);

close p_ref_cursor;

if l_num_rows > 0 then
-- perform the XSL transformation
l_json := l_xml.transform (xmltype(get_xml_to_json_stylesheet));
l_returnvalue := l_json.getclobval();
else
l_returnvalue := g_json_null_object;
end if;

l_returnvalue := dbms_xmlgen.convert (l_returnvalue, dbms_xmlgen.entity_decode);

return l_returnvalue;

end ref_cursor_to_json;

If you want to read more about this, head over to this blog post on ORA-00001 blogspot.

This utility is available as part of plsql-utils on Google Code along with many other cool PL/SQL utilities. You should check it out if you have time.

link bài gốc

How to connect to remote Postgres DB through ssh tunnel

Open a SSH tunnel on your local machine. Here I’m openning a tunnel on my local port 5555, mapping it to the remote 5432 default port of Postgres.

If you have already changed the default port of Postgres, change it accordingly here as well

ssh -fNg -L 5555:localhost:5432 [email protected]

I’m going to use pgAdmin 3 app to connect to Postgres db. Just follow the new connection instruction as you’re connecting a local database.

If you’re using IDENT authentication, your local username has to be matched with the username you’re trying to log on to. Either switch to PASSWORD authentication or create a new username on remote db that match your local username as below and you’re good to go.

CREATE USER myuser;
ALTER USER myuser WITH PASSWORD 'password';
ALTER USER myuser WITH CREATEUSER CREATEDB;

Speed up jekyll site generation with rsync

Jekyll doesn’t support incremental generation so if your site contains loads of static assets like image, audios,.. jekyll is gonna stroke everytime you re-generate your site by deleting and re-generate/re-coppying everything. This little trick below will help you speeding up jekyll generation process by skipping all the static assets that you specified, until jekyll comes up with a better solution.

  • Rename your static asset folder with underscore in front. jekyll is going to ignore this when generating site. Assume this folder is named images. You will rename it to be _images.

  • In your _config.yml, add the line below. This line basically means that when re-generating, the folder called images in generated folder is not getting touched.

keep_files: ["images"]
  • Keeping in the source and generated folder in sync with a little plugin and rsync. Created a file name rsync_image_generator.rb in _plugins folder with the content below.
module Jekyll    
  class RsyncImageGenerator < Generator
    def generate(site)
      system('mkdir -p _site');
      system('rsync --archive --delete _img/ _site/img/');
    end
  end
end  

From now on, jekyll will ignore the _images folder in your source and images in _sites folder when generating your site. We keep it in sync by using rsync, which is much better/faster than delete/copy process jekyll is using.

Github Pages does support jekyll gems now but it’s kinda limited.


Setup custom error page for jekyll on nginx

First of all, create your custom error page. You can either use static html or jekyll template for this. If you decide to use one of your custom layout, the path will be a bit different when jekyll generates static pages.

I created a 404.html file that looks like this.

---
layout: default
title: "404: Page not found"
---

Olps.

Now if you create one like mine above at root, it will be generated as 404/index.html so use this path instead of just 404.html when configure nginx.

Edit your nginx config file to add these lines inside server block.

error_page 404 /404/index.html;
error_page 500 502 503 504 /50x/index.html;

Test config your new nginx conf, reload (or restart) and you’re good to go.


Hydra - an open-source window manager for OS X written in Lua

Open-source, written in Lua

Gotta try this.

Update: Hydra was renamed to mjolnir due to trademark issues

link bài gốc

Clean code/dirty code

I like to think of myself as a perfectionist. I like going back and forth re- evaluate all the possible options and come up with the cleanest, best, perfect alternative (I can think of) out there. If you are like me and you got to maintain someone else’s bad code, this is gonna be a real nightmare. You just want to scratch everything and start over again. Unfortunately, management people doesn’t think so and you don’t get the luxury of times you need. All they want is you get it fixed and ship the product as soon as possible.

I thought it is what makes me a better developer but in the end, getting a shippable product is what matters.

Sometimes, it’s just better to use a bit of dirty, tricky code to make it works. Sometimes, you just need a bit use of dirty code if it is what it takes to get the product out of the door.


How to use SSH tunnel to access blocked websites

Requirements

  • An UNIX server/VPS (since it’s cheaper than Windows server/VPS). Lowest package would probably do. Location: not in the the same area/country as you.
  • A little copy/paste skill. No Unix commands knowledge required.

Howto

  • If you’re on Unix/OS X, open Terminal app and issue the command
ssh -D 1080 [email protected]_or_domain

This command will connect to your server/VPS using ssh and open a ssh tunnel on port 1080 of your computer. Setup your browser/OS to use localhost:1080 as socks5.

All the traffic will be sent over ssh tunnel hence your ISP will only see it as you’re accessing your server/VPS.

If you’re on Windows, you can grab Tunnelier (free). The setup is pretty straight forward.


How to code like a dick in JS

The goal of this post is to make simple things look complicated.

1. Invert logic

Let’s start with something easy.

Instead of

if (x && y) { ... } // easy

Write this instead

if (!(!x || !y)) { ... } // good enough

2. Extended unicode chars for variable names

Use of extended unicode chars, especially those that are not visible in console like \r, \t, etc…

3. Use = instead of ==

if (x=true) { ... } // always executed

Do this when you want to always excute that code block. Someone may see this and will attempt to “fix” it on their own, changing the original logic. Goodluck debugging it later : )

4. Use 8-base or n-base instead of decimal base

Because why not?

var x = 19;   // 19
var y = 019;  // 17

Programming is like writing a book

Programming is like writing a book… except if you miss out a single comma, the whole thing makes no damn sense.

On why programming is hard.