Jun. 12, 2020
The panic recover is only alive within the current thread, that means each goroutine need it’s own panic recover
The panic in this goroutine, wont be caught by the recover, it will panic.
defer func() { if rec := recover(); rec != nil { fmt.Println("Catched panic", rec) } }() fmt.Println("Hello, playground") wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() panic("You can't catch me!") }() wg.Wait() To catch the panic inside of the goroutine, you need code the recover again
defer func() { if rec := recover(); rec != nil { fmt.Println("Catched panic", rec) } }() fmt.Println("Hello, playground") wg := sync.WaitGroup{} wg.Add(1) go func() { defer func() { if rec := recover(); rec != nil { fmt.Printf("Now catched `%v`\n", rec) } }() defer wg.Done() panic("You can't catch me!") }() wg.Wait() More reading
Website: jma.dev
Weekly tech bookmarks: funcmarks
Aug. 23, 2019
cg_context.set_allows_font_smoothing(false); cg_context.set_should_smooth_fonts(false); cg_context.set_allows_font_subpixel_quantization(false); cg_context.set_should_subpixel_quantize_fonts(false); cg_context.set_allows_font_subpixel_positioning(false); cg_context.set_should_subpixel_position_fonts(false); Change the value from true to false in font/src/darwin/mod.rs, then build Alacritty The font is displaying much better on Mac OSX (at least for me)
If you have not tried Alacritty + Tmux + vim(Neovim), you should do it. Here is a good article to talk about this set ‘Alacritty integration with Tmux’
Jan. 15, 2019
Install gnupg and pinentry-mac brew install gnupg brew install pinentry-mac Generating a GPG key Generating key gpg --full-generate-key
Checking my key gpg --list-secret-keys --keyid-format LONG
Copying key gpg --armor --export 3AA5C34371567BD2 | pbcopy
Setting key for git git config --global user.signingkey 3AA5C34371567BD2
Full help https://help.github.com/articles/generating-a-new-gpg-key/
Setting to load key nvim .gnupg/gpg-agent.conf
pinentry-program /usr/local/bin/pinentry-mac
Backup and restore gpg --export-secret-keys KEY_ID > my-private-key.asc gpg --import my-private-key.asc
Apr. 4, 2018
targetURL := "http://www.example.com/one/two/three.json?output=four" u, err := url.Parse(targetURL) if err != nil { panic(err) } fmt.Println(path.Base(u.Path)) // three.json
Apr. 4, 2018
Example to download a file from url and save on local
io.Copy() read 32kb (maximum) from input and write to output reapeatly, so dont need worry about memory.
func DownloadFile(filepath string, url string) error { // Create the file out, err := os.Create(filepath) if err != nil { return err } defer out.Close() // Get the data resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() // Write the body to file _, err = io.Copy(out, resp.Body) if err != nil { return err } return nil } reference: Code Example
Mar. 28, 2018
var fibTests = []struct { n int // input expected int // expected result }{ {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}, {7, 13}, } source: 5 simple tips and tricks for writing unit tests in #golang
Sep. 2, 2017
First of all, PHP Code Example. (PHP ≥ 7)
function isStriaghtFlush($d) { $b = $f = 0; $m = ['a'=>1,1=>10,'j'=>11,'q'=>12,'k'=>13]; foreach ($d as $a) { $p = substr($a,-1); $b |= 1<<(($m[$a[0]])??$a[0]); $f = ($f===0||$f===$p) ? $p : 1; } $b = ($b << 3) | ($b >> 10); foreach (range(0,13) as $i) { if ((($b >> $i) & 31) == 31){ return [true, $f!=1]; } } return [false, false]; } Explain:
A can be straight of A, 2, 3, 4, 5 and 10, J, Q, K A
There are total 14 ranks, when getting rank n from the $d, we set 1 of the n element in bitwise map.
If we could find any 5 continuously 1 in the bitwise map, then it’s straight. also if all faces are same, then it’s straight flush.
Example, cards: 10, J, Q, K, A
read 10, bitwise map: 0,0,0,1,0,0,0,0,0,0,0,0,0,0
read J, bitwise map: 0,0,1,1,0,0,0,0,0,0,0,0,0,0
read Q, bitwise map: 0,1,1,1,0,0,0,0,0,0,0,0,0,0
read K, bitwise map: 1,1,1,1,0,0,0,0,0,0,0,0,0,0
read A, bitwise map: 1,1,1,1,0,0,0,0,0,0,0,0,1,0
shift left 3 of bitwise map to 1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0
shift right 10 of bitwise map to 1,1,1,1
OR this two bitwise maps and get a new map 1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1
then we have 5 continuously 1, it’s straight.
Dec. 27, 2016
Using Homebrew to install MariaDB, and got this eror when starting the server
$ mysql.server start Starting MySQL .161227 19:05:10 mysqld_safe Logging to '/usr/local/var/mysql/xxx.err'. ERROR! Mostly it is caused by previous installation of MySQL.
Manually remove /usr/local/var/mysql and reinstall MariaDB, it will start normally.
Jul. 25, 2016
You will get this kind of error message when you run brew services in tmux
/usr/local/Cellar/something/homebrew.mxcl.something.plist: Operation not permitted How to fix it, just need install reattach-to-user-namespace
brew install reattach-to-user-namespace
Jul. 5, 2016
Date Range Overlap Only 2 conditions that overlap does not exist
|------ Date Range A ------| |------ Date Range B ------| or
|------ Date Range A ------| |------ Date Range B ------| That means start date A is later than end date B, or end data A is early than start date B.
Overlap exists if neither of them is true.
In rails we can create a scope to find all overlaps
scope :overlaps, -\>(start_date_, end_date_) do where “((start_date \<= ?) and (end_date \>= ?))", end_date_, start_date_ end reference:
http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
http://baodad.blogspot.com.au/2014/06/date-range-overlap.html
Jun. 29, 2016
Ruby on Rails datepicker
Use bootstrap datepicker gem
Gemfile:
gem 'bootstrap-datepicker-rails'
Add this line to app/assets/stylesheets/application.scss
*= require bootstrap-datepicker3
Add this line to app/assets/javascripts/application.js
//= require bootstrap-datepicker
Add this line to template
<%= f.text_field :publish_at, "data-provide" => 'datepicker', "data-date-format" => "yyyy-mm-dd" %>
Mar. 5, 2015
Laravel Homestead commands:
Available commands: destroy Destroy the Homestead machine edit Edit the Homestead.yaml file halt Halt the Homestead machine help Displays help for a command init Create a stub Homestead.yaml file list Lists commands resume Resume the suspended Homestead machine run Run commands through the Homestead machine via SSH ssh Login to the Homestead machine via SSH status Get the status of the Homestead machine suspend Suspend the Homestead machine up Start the Homestead machine update Update the Homestead machine image There is missing provision command
Solution is:
list all vagrant instance
$ vagrant global-status id name provider state directory ------------------------------------------------------------------------------------- 6e1aa44 default virtualbox poweroff /Users/[whoami]/.composer/vendor/laravel/homestead then run provision with id
$ vagrant provision 6e1aa4
Feb. 26, 2015
I was using Vaprobash as basic starting Vagranfile which is working perfectly ‘post is here’. However, there are too many settings I will never use, I think it’s a better idea I make my own Vagranfile.
I vagranted up a new empty box, and run each commands to setup my LAMP environment, and recorded each command to shell scripts, that make sure all commands are just what I need.
Download my Vagrant LAMP: My Vagrant LAMP
TODO:
remote call shell scripts like Vaprobash use puppet might be better
Feb. 6, 2015
I started to move my development works on my local envirnoment setup to Vagrant. Since I like to reinstall my system once major update released like Mac OSX 10.9 to 10.10, this will save lots of time for me.
And also, I watched this video Get Off MAMP on Laracast to push me move to Vagrant.
Recently, I have moved one of my projects to a new directory, and it told me path is not correct once I vagrant up my project. Becuase I am using Vaprobash as basic start Vagrantfile, it is using NFS to sync folder between your local and box, which will modify /etc/exports.
What I need to do after I move existing project to another directory, I just need modify /etc/exports and update the directory path to new one.
Dec. 5, 2013
Go to Google Apps Script and start a new blank project.
{% gist 7799698 %}
After you save script, run it and authorize the script to access your Gmail account, then add triggers to call script.
Oct. 11, 2013
for REPO in `ls`; do (cd "$REPO";git pull); done; update
find . -mindepth 1 -maxdepth 1 -type d -print -exec git -C {} fetch \; https://github.com/imjma/dotfiles/blob/master/zsh/alias.zsh#L54
Jul. 15, 2013
Let’s see what’s differences between JSON and JSONP first;
//JSON {"name":"stackoverflow","id":5} //JSONP func({"name":"stackoverflow","id":5}); JSONP is the result that you can load the json as a script file. And it is usually used to allow for cross-site AJAX with JSON data.
function func(json){ alert(json.name); } var elm = document.createElement("script"); elm.setAttribute("type", "text/javascript"); elm.src = "http://example.com/jsonp"; document.body.appendChild(elm); Convert JSON to JSONP in PHP, JSONP will pass callback to script
$json = json_encode($data); $jsonp_callback = isset($_GET['callback']) ? $_GET['callback'] : null; echo $jsonp_callback ? "$jsonp_callback($json)" : $json; Rerference: Stack Overflow
Jun. 25, 2013
Saw this good example from stackoverflow
class Person { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } public function getTitle() { return $this->getName()." the person"; } public function sayHello() { echo "Hello, I'm ".$this->getTitle()."<br/>"; } public function sayGoodbye() { echo "Goodbye from ".self::getTitle()."<br/>"; } } class Geek extends Person { public function __construct($name) { parent::__construct($name); } public function getTitle() { return $this->getName()." the geek"; } } $geekObj = new Geek("Ludwig"); $geekObj->sayHello(); $geekObj->sayGoodbye(); Output:
Hello, I'm Ludwig the geek Goodbye from Ludwig the person $this will refer to current object(extended class), but self:: only refer to current class. If you want to refer to current object, you can use static:: (>= PHP5.3.0)
Jun. 20, 2013
Sometimes I want to run jekyll on office’s computer which is using windows. I dont want to spend too much time to setup ruby or compile setup on windows, or even install linux on office’s computer. Vagrant is a quick virtual machines to do the work!
Follow the instruction on vagrant website, and vagrant init in your project folder. Then open Vagrantfile to configure Vagrant
Vagrant.configure("2") do |config| config.vm.box = "precise32" config.vm.network :forwarded_port, guest: 4000, host: 4000 config.vm.provision :shell, :inline => "sudo apt-get update && sudo apt-get -y install build-essential ruby-compass && sudo /opt/vagrant_ruby/bin/gem install jekyll rdiscount --no-ri --no-rdoc" end Then you are ready to start VM
$vagrant up $vagrant ssh $cd /vagrant $jekyll server After vagrant up successflly. You should be able to visit via http://localhost:4000 by your web browser.
Apr. 8, 2013
Please register your own api key on 500px via here, and put Consumer Key after $api="" in workflow.
For example, you want to save this photo with id: 27042559 on 500px to your local. Call Alfred, and type: 500px 27042559
It will download size 5 image into your desktop with name 27042559_5.jpg
Download: 500px.workflow
Aug. 22, 2012
A nice Sublime Text 2 Theme And a good font: PragmataPro
Aug. 20, 2012
A good tools to manage Pow
According to this post, if you dont need Pow and MAMP Pro together. You can use Powder to run powder down to disable pow first, then start MAMP Pro.
Aug. 15, 2012
source: Running Pow with Apache
I use both Pow for rails development and MAMP Pro for PHP development. I need them work simultaneously.
Before start, if you have Pow installed, uninstall it with
curl get.pow.cx/uninstall.sh | sh
Then let pow’s firewall run to redirect all traffic from port 88 instead of port 80
echo 'export POW_DST_PORT=88' >> ~/.powconfig
Then you can install Pow as normal
curl get.pow.cx | sh
Now, open MAMP Pro, create a new host. Doesn’t matter what it is named and which directory is selected (though I use ‘rails.dev’ and the folder I keep my Rails apps in).Also, deselect the select box for “local name resolution”, just in case. Then go to the Advanced tab, and fill this in to the textarea labeled “Customized virtual host general settings”:
ServerName pow
ServerAlias *.dev ProxyPass / http://localhost:20559/
ProxyPassReverse / http://localhost:20559/
ProxyPreserveHost On
Aug. 7, 2012
This topic is about some general problems when I depoly rails app.
After I set up server environment, I cloned source code by git. Usually, we need do some steps to make sure it works on production environment.
gem we need install
bundle install
initial mongodb
rake db:seed
compile files we need for production
rake assets:precompile --trace RAILS_ENV=production
install javascript runtime
sudo apt-get install nodejs
or from package src
apt-get install make python g++
mkdir ~/nodejs && cd $_
wget -N http://nodejs.org/dist/node-latest.tar.gz
tar xzvf node-latest.tar.gz && cd \`ls -rd node-v*\`
make install
Jun. 22, 2012
We are using git-flow as git branching model to do development.
However, there are more and more feautre branches were generated, and we need to make a list quickly for all branches to see which branch is still under development and not merged into master branch sometimes.
Then this command will give a huge help.
git branch --no-merged master
And if add -a you can get all include remote branches.