teleren/devto huggingface dataset:
Clean up and compact your VDI
Tags: virtualbox
Published: 2019-12-23 21:11:51

---
title: Clean up and compact your VDI
published: true
date: 2015-05-22 19:24:34 UTC
tags: virtualbox
canonical_url: 
---

### TL;DR

```
Guest OS: sudo sfill -llvz /

Host OS: VBoxManage modifyhd --compact \<\_.vdi\>
```

### Details

My VirtualBox thin server had put on a few pounds over the months of guest OS database imports, static resource creation, temp file creation, log rotation, and a bunch of other stuff I don’t need to store indefinitely. Every time more sectors need to be called upon to store something in the guest, VirtualBox will grow the physical VDI image accordingly, up to the maximum size specified. However, when you delete files from the guest system, the VDI doesn’t shrink accordingly (and with good reason).

If you have implemented a backup strategy — as I have with Time Machine — you probably don’t want to back up a 30 GB VDI file every single time a single bit changes (for example, when you boot the virtual machine). This is particularly true when you have deleted old databases, resources and logs, and the guest OS really only represents about 5 GB of data.

VBoxManage modifyhd allows you to compact a physical VDI, but with _one important precondition_, it only truncates _zeros_ in the guest from the VDI:

> With the — compact option, can be used to compact disk images, i.e. remove blocks that only contains zeros. This will shrink a dynamically allocated image again; it will reduce the _physical_ size of the image without affecting the logical size of the virtual disk. Compaction works both for base images and for diff images created as part of a snapshot.

So simply having deleted a file from your guest will not allow you to reclaim space. You have to zerofill the free space on guest OS’s volumes.

In your Guest (in this case, Ubuntu Server 12.04.02 LTS)

```
sudo apt-get install secure-delete sudo sfill -llvz /
```

The -ll option writes only one pass (instead of the default 38) and the -z option replaces the single pass of data from /dev/urandom with zeros, which is what VBoxManage is looking for.

In your host:

```
VBoxManage modifyhd --compact \<virtual\_disk\_file.vdi\>
```

I shrunk mine from 25 GB to 5 GB in a single step. My SSD allowed me to zerofill about 20 GB in the guest and compact the VDI in less than 90 seconds.

_Originally published at_ [_michaelsanford.com_](http://michaelsanford.com/clean-up-and-compact-your-vdi/) _on August 8, 2013._
Use PHP to generate filter portfolio
Tags: php
Published: 2020-10-05 11:34:56

---
title: Use PHP to generate filter portfolio
published: true
date: 2015-05-19 00:00:00 UTC
tags: PHP
canonical_url: 
---

Overview Filter Portfolio can be very useful for websites, especially when there is a lot of images you want to show to users. It is always nice to keep it into different categories and allow your user to play with them. But adding a tag and a div on hundreds of images is…

   
[Read On](https://www.loginradius.com/engineering/blog/use-php-to-generate-filter-portfolio/)
TCPの空きポートをListenする
Tags: go, linux
Published: 2015-05-18 03:13:00

---
title: TCPの空きポートをListenする
published: true
tags: Go, Linux
date: 20150518T03:13Z
canonical_url: https://qiita.com/shiena/items/14016f3875a136ad0134
---
# はじめに

サーバを起動する時にポートは何でもよいので空きポートをListenしたい事がありました。
ウェルノウンポート以外を順に調べるしかないのかと思っていたのですが、
そんな面倒はなくポート0をListenすると空きポートが割り当てられます。

# サンプル

以下はGoで書いた検証コードです。

```go:main.go
package main

import (
	"fmt"
	"net"
)

func main() {
	l, err := net.Listen("tcp", "localhost:0")
	if err == nil {
		defer l.Close()

		addr := l.Addr().String()
		_, port, err := net.SplitHostPort(addr)

		if err == nil {
			fmt.Printf("    listen port: %s\n", port)
		} else {
			fmt.Printf("    %s\n", addr)
		}
	} else {
		fmt.Println("can't listen")
	}
}
```

実行する度に異なるポートが割り当てられています。

```txt:実行結果
% go run main.go
    listen port: 64522
% go run main.go
    listen port: 64830
% go run main.go
    listen port: 64835
% go run main.go
    listen port: 64838
```


# 参考リンク

* [Javaで空いているポート番号を取ってきたい](http://moznion.hatenadiary.com/entry/2014/11/29/222221)
* [Well-known ports](http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports)
Trying windows 10
Published: 2022-09-20 21:22:20

---
title: Trying windows 10
published: true
date: 2015-05-17 20:00:45 UTC
tags: 
canonical_url: https://www.funkysi1701.com/posts/2015/trying-windows-10/
---

My laptop has been getting a bit cluttered up with stuff so this weekend I gave it a reset.

As I am using windows 8 this was much easier than doing a format reinstall which I have done many times with previous OSes. Open settings and select recovery and after about 4 hours everything was back to factory settings.

I then installed a few updates and then installed the windows 10 preview. One of the requirements for windows 10 is Windows 8 Update (the one that came after 8.1), it took a few reboots and updates until I got that installed.

I had purchased the pro pack which gives you the same features as windows 8 pro but I didn’t notice until after I installed 10 that this hadn’t been installed. I will need to roll back to windows 8 apply the update and then reinstall 10 again. I can’t really be bothered to do that, so I will live without HyperV for now. As it is I have done a lot of sitting around waiting for things to finish installing.

![](https://storageaccountblog9f5d.blob.core.windows.net/blazor/wp-content/uploads/2015/05/win10.jpg?w=888&ssl=1)

I much prefer Windows 10 to Windows 8, an earlier preview had an issue with drivers for my second screen but that appears to have been resolved now. The start menu is back and I prefer it, to being taken to that extra screen of options that windows 8 had.

I prefer the email client that windows 8 had to the windows 10 version as my work emails don’t work with it. I assume this is due to how my exchange server has been configured and maybe a later preview will allow my email to work or failing that I will have to get emails at work fixed properly.

All apps now open in windows which is much nicer. Cortana is very similar to Google Home on my phone where I can talk and ask it stuff. But I never use this sort of feature apart from testing it.

The new web browser has some nice features like the option to scribble over a web page but nothing that special that I think I will change my default browser from Chrome. It will be interesting to see how it performs in browser stats.

I am part way through installing Visual Studio 2015 RC, but I think that will have to be a separate post.
Go言語のperiod(.) importとblank(_) importについて
Tags: go
Published: 2015-05-17 02:14:00

---
title: Go言語のperiod(.) importとblank(_) importについて
published: true
tags: Go
date: 20150517T02:14Z
canonical_url: https://qiita.com/shiena/items/c1ac3192af3b00f413ac
---
# importについて

Go言語のperiod importとblank importについて調べてみました。
import全般の仕様は以下から確認できます。

* [Goプログラミング言語仕様 / インポート宣言](http://golang.jp/go_spec#Import_declarations)
* [The Go Programming Language Specification / Import declarations](http://golang.org/ref/spec#Import_declarations)

## period(.) import

Goプログラミング言語仕様のインポート宣言より引用

> 名前の代わりにピリオド(.)を指定したときは、インポートされたパッケージのパッケージブロックでエクスポートされている全識別子がインポートしたソースファイルのファイルブロックで宣言され、プレフィックスなしでアクセスできるようになります。

period importの仕様は上記の通り単純です。
ただし、以下の理由から利用はおすすめできません。

* period importしたパッケージに含まれる関数と同名の関数を宣言できなくなる
* どのパッケージの関数なのか分かりにくくなる

例外として[「Go言語のパッケージのテストでプライベートな関数や変数を呼び出すには」](http://atotto.hatenadiary.jp/entry/2013/01/19/112012)で解説している使い方は非常に有用だと思います。

### period importのサンプル

```go:main.go
package main

import . "fmt"

func main() {
	Println("period import")
}
```

```shell-session:実行結果
$ go run main.go
period import
```

## blank(_) import

Goプログラミング言語仕様のインポート宣言より引用

> インポート宣言は、インポート「する側」と「される側」の依存関係を宣言します。自分自身のパッケージをインポートすること、またはインポートしたパッケージ内でエクスポートされている識別子を一切参照しないことは誤った使い方です。インポートによる副作用(初期化)のためだけにパッケージをインポートするときは、パッケージ名としてブランク識別子を使ってください。

こちらはinit関数だけを実行する場合に使う事ができます。
[Effective Go / Import for side effect](http://golang.org/doc/effective_go.html#blank_import)ではHTTPのデバッグのために`net/http/pprof`パッケージを利用する方法が挙げられています。

### blank importのサンプル

```go:main.go
package main

import (
	"fmt"

	_ "./blank"
)

func main() {
	fmt.Println("main")
}
```

```go:blank/blank.go
package blank

import "fmt"

func init() {
	fmt.Println("blank/init")
}
```

```shell-session:実行結果
$ go run main.go
blank/init
main
```

**追記**

最終的に消すけど開発途中で消したくないimportがある場合にもblank importを使えます。
次のように全ての`fmt`をコメントアウトしてもimportでエラーになりません。

```go:blank/foo.go
package main

import _ "fmt"

func main() {
	// fmt.Println("begin")
	anyFunction()
	// fmt.Println("end")
}
```
Notes on Raspberry Pi & Arduino
Tags: raspberrypi, arduino, javascript, node
Published: 2015-05-15 21:16:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Notes on Raspberry Pi & Arduino
slug: notes-on-raspberry-pi-and-arduino
date: 2015-05-15 21:16
tags: raspberrypi, arduino, javascript, nodejs
---

Using NOOBS, install Raspbian. It's probably the most supported distro for the Pi. (https://www.raspberrypi.org/help/noobs-setup/)

Setup the Raspberry Pi to connect automatically to WiFi. I've used a TP-Link TL-WN321G without any issues. (http://weworkweplay.com/play/automatically-connect-a-raspberry-pi-to-a-wifi-network/)

I'm using an old pre-2011 Arduino Uno. It's firmware version is actually 0.00, but I was able to get it working with Firmata. Firmata is a library which enables communication between host and arduino. It allows you to use JavaScript frameworks such as http://johnny-five.io/ to control your arduino with Node.

You only need to put Firmata on the arduino once, so I did it on my MacBook. After this, the Arduino just starts up ready to communicate. No more programming required. Tethering is required, as the *host* will now wear the trousers.

First, download the Arduino IDE. On OS X, `brew cask update && brew cask install arduino`. Once installed, run it, make sure the arduino is connected via USB. Make sure the correct board and port are seleted in the IDE. Go to File, Examples, Firmata, and then StandardFirmata. Upload this to your board. Now you're set.

Let's quickly test it. Using Node, install `johnny-five`. Then stick an LED in Arduino pins `13` and `GND`. Then run the hello world blink code:

    var five = require("johnny-five"),
        board = new five.Board();
    
    board.on("ready", function () {
        var led = new five.Led(13);
        led.blink(500);
    });
    
The LED should blink. If it doesn't, it's time to get your Google on.

Moving on, we want to control the Arduino via the Raspberry Pi. For this, you need to manage your power consumption properly.

Step 1. Power on raspberrypi with WiFi dongle connected. Wait for it to connect to network.  
Step 2. Start a continuous ping of the raspberrypi to check it's connectivity.  
Step 3. Power on your arduino with an external power supply.  
Step 4. Plug in the USB into the raspberrypi.  
Step 5. Plug in the USB to the arduino.  

I don't know for sure, but I think that by powering on the arduino with external power first and then connecting it via USB, it disables the USB power consumption, which stops your raspberrypi from throwing a fit.

Next article will cover: johnny-five arduino code/setup
Things to be aware of when change Capybara default_wait_time
Tags: capybara, test, rails
Published: 2019-02-20 23:48:01

---
title: Things to be aware of when change Capybara default_wait_time
published: true
tags: capybara,test,rails
canonical_url: https://blog.tomoyukikashiro.me/post/things-to-be-aware-of-when-change-capybara_default_wait_time
---

This post was originally published at [Things to be aware of when change Capybara default_wait_time](https://blog.tomoyukikashiro.me/post/things-to-be-aware-of-when-change-capybara_default_wait_time)

# About `Capybara.default_wait_time`

According to [api document](http://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Finders#find-instance_method)…

> find will wait for a set amount of time and continuously retry finding the element until either the element is found or the time expires. The length of time find will wait is controlled through Capybara.default_wait_time and defaults to 2 seconds.

## ATTENTION

You had better not set much time to `Capybara_default_wait_time`.

For example, if you set 10 seconds to `Capybara.default_wait_time` when you want to check the element dose not exist. Test time can be long. Because Capybara wait to check the element dose not exist in each test.

```
# in rspec.rb
Capybara.default_wait_time = 10

# in feature test
expect(page).to have_no_selector(:css, "p a#doesnotexist") # wait 10 seconds
```

## Solution

If you need more than 2 seconds(default value in Capybara.default_wait_time) to wait to check you can set `wait` option to find instead.

```
expect(page).to have_selector(:css, "p a#doesnotexist", wait: 3)
```
Password Security
Tags: security, password
Published: 2020-10-05 11:35:07

---
title: Password Security
published: true
date: 2015-05-14 00:00:00 UTC
tags: Security,Password
canonical_url: 
---

When we start thinking about authentication in any kind of software (it can be web, mobile, desktop, or even console), the first thing that comes to mind is username/password, this is an older but still effective technique to protect and identify users. Securing these passwords…

   
[Read On](https://www.loginradius.com/engineering/blog/password-secure/)
Practical Use Cases For The :empty Pseudo-class
Published: 2020-06-29 12:49:26

---
title: Practical Use Cases For The :empty Pseudo-class
published: true
date: 2015-05-12 04:17:54 UTC
tags: 
canonical_url: https://mjswensen.com/blog/practical-use-cases-for-the-empty-pseudo-class/
---

At first, the `:empty` pseudo-class may not seem to be the most useful of the advanced selectors. However, there are situations in which `:empty` is the perfect tool for the job. Here are a couple of examples:

## Tag/label manager UI

Say you were developing an application that allowed users to manage tags or labels (think [Trello](https://trello.com/)). It would be nice to allow users to add titles to their labels, but the labels should also be visually sufficient if no titles are added, like so:

![Tag/label manager UI](https://mjswensen.com/blog/images/css-empty-labels.png)

You’ll notice that the tags without text are wider than they would be if they were simply an empty `<span>` with padding and a background color. The essentials of the code to achieve this is:

```css
.label:empty {
  width: 1rem;
}
```

Simple, yet adds a bit of robustness to the design. I made the labels `contenteditable` and [put it up on CodePen](http://codepen.io/mjswensen/pen/jPWrNe) so that it can be played with:

[![Editable tags example](https://mjswensen.com/blog/images/css-empty-contenteditable.gif)](http://codepen.io/mjswensen/pen/jPWrNe)

## Analytics dashboard UI

Another example use case would be a data collection user interface that hasn’t received any data yet. Suppose an application was tracking the conversion rate of an e-commerce site by geographical region, like so:

![Data collection UI example](https://mjswensen.com/blog/images/css-empty-conversions.png)

In the previous example, the elements for the USA and Canada metrics have text (“1.64%” and “0.53%”, respectively), while that of Mexico is empty. This is relevant code:

```css
.conversion-rate:empty::before {
  content: "No data";
  opacity: 0.25;
}
```

[Here is a link to the live example.](http://codepen.io/mjswensen/pen/jPWrNe) It’s a nice little trick that provides a better experience than simply leaving the space blank in the absence of data.

## Conclusion

As web professionals, we take pride in making sure our designs look great no matter the circumstances—think _responsive design_, for example—and the `:empty` pseudo-class is another tool in our tool box to achieve that.

What other great use cases for `:empty` have you come up with?
Access boot2docker container IP
Tags: docker, osx, boot2docker
Published: 2015-05-10 20:26:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Access boot2docker container IP
slug: access-boot2docker-container-ip
date: 2015-05-10 20:26
tags:
 - docker
 - osx
 - boot2docker
---

When you run boot2docker, all your containers will be running on that VM, not on your local machine. Therefore, you won't be able to access them via their container IPs by default.

To access them, ensure that boot2docker is running, and run:

    $ sudo route -n add 172.17.0.0/16 `boot2docker ip`
    
This tells your machine to direct all traffic on the docker IP subnet to the IP address that your boot2docker is running on.
Strategy Design Pattern
Tags: php
Published: 2020-01-28 09:44:41

---
title: Strategy Design Pattern
published: true
tags: php
canonical_url: 
---

In this post, we will explore what strategy design pattern is and what problems does it solve but first, what is a design pattern ? Here is how Wikipedia defines it:

> In software engineering, a design pattern is a general **reusable solution** to a **commonly occurring problem** within a given context in software design.

So a design pattern is nothing but a **re-usable solution towards commonly occurring problems** you may face while programming.

## Overview

One of the common problems we face in programming is to make decisions based on _different conditions/inputs._

Let's say we have created a framework of our own and we want to be able to allow users to choose _different_ types of logging methods such as logging to file, database or email.

## Example

First, we create our logger classes for the framework that implement common interface:

```
interface InterfaceLogger {
    function log($message);
}

class FileLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to file system
    }   
}

class DatabaseLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to database
    }   
}

class EmailLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to email
    }   
}
```

Let's assume users of our framework are allowed to choose an specific logger through some configuration file by typing `file`, `database` or `email` and our framework is able to know it:

```
$loggerType = App::getConfig('logger');
```

Now we can easily find out which logger to use using strategy design pattern:

```
switch($loggerType) {
    case "file":
        $logger = new FileLogger();
        break;
    case "database":
        $logger = new DatabaseLogger();
        break;
    case "email":
        $logger = new EmailLogger();
        break;
    default:
        $logger = new FileLogger();
}
```

And then throughout our framework, we can use `$logger->log()` method which would automatically know which logger type to use.

As you might have noticed, strategy pattern is very simple one and we might have written similar code a number of times before albeit without realizing it is actually some design pattern.

 ![](http://feeds.feedburner.com/~r/codeinphpfeed/~4/pQDT_rs0aXU)
Replace Nested Conditions with Guard Clauses
Published: 2020-01-28 09:38:59

---
title: Replace Nested Conditions with Guard Clauses
published: true
tags: 
canonical_url: https://codeinphp.github.io/post/replace-nested-conditions-with-guard-clauses/
---

Sometimes we have to write code when we need to put conditions inside conditions (nested conditions) and once all of those are true, we perform some action. Here is dummy example of what I mean:

```
function isAuthorized($userId, $age)
{
    if (isLoggedIn($userId))
    {        
        if (isAdmin($userId) && $age >= 18)
        {            
            if (hasAcess($userId, $resourceId))
            {
                return true;
            }
        }
    }

    return false;
}
```

Although functionally nothing wrong with above code but it is good practice to avoid nested conditions (also nested loops) in some way or the other. This is simple example that may look easy to grasp to the naked eye, this isn't always the case. Obviously we can refactor above code and avoid nested conditions like this:

```
function isAuthorized($userId, $age)
{
    if (isLoggedIn($userId) && isAdmin($userId) && $age >= 18 && hasAcess($userId, $resourceId))
    {        
        return true;
    }

    return false;
}
```

We have shortened the code but still it doesn't look that good and readability is compromised here. Depending on the code editor/IDE you are using and font you are using or if you have even more nested conditions, this doesn't seem good solution or one that is easy to understand.

The solution is something called **Guard Clauses** which essentially mean you put your conditions in inverted way than your original conditions. Guard clauses should return opposite value compared to your original conditions. Here is how we can use guard conditions with above example:

```
function isAuthorized($userId, $age)
{
    if (! isLoggedIn($userId)) { return false; }
    if (! isAdmin($userId) || $age < 18) { return false; }
    if (! hasAcess($userId, $resourceId)) { return false; }

    return true;
}
```

As can be seen, we have got rid of nested conditions by putting reverse conditions on top of the function. We don't proceed any further when any of these is `false`. If none is false, `true` is returned as default value in the end.

The benefit here is that code looks easy to understand and gives quick idea of what it is doing at first glimpse. Pretty simple yet effective stuff.

# Avoid This ;-)

![enter image description here](https://codeinphp.github.io/images/14316395635555160b05859.png)

 ![](http://feeds.feedburner.com/~r/codeinphpfeed/~4/ZGHE7TQtk4U)
Loading spinner using CSS
Tags: css, loader
Published: 2020-10-05 11:35:23

---
title: Loading spinner using CSS
published: true
date: 2015-05-05 00:00:00 UTC
tags: CSS,Loader
canonical_url: 
---

Learn how to create a loading spinner using CSS

   
[Read On](https://www.loginradius.com/engineering/blog/create-a-loading-spinner-using-css/)
Using your Rubber Duck
Published: 2022-09-22 18:30:45

---
title: Using your Rubber Duck
published: true
date: 2015-05-04 20:00:45 UTC
tags: 
canonical_url: https://www.funkysi1701.com/posts/2015/rubber-duck/
---

Rubber Duck is a process in development where you talk through an issue with an inanimate object such as a Rubber Duck. It gets its name from the book The Pragmatic Programmer where it was first used.

I am the only programmer where I work and often I find myself with a question that I can’t find the answer to. I do however have a few friends who are far more knowledgeable than I am about this sort of thing. I often find myself explaining my problem via an email to them. During the process of writing this email I have to explain my problem and this sometime reveals the problem and I don’t even need to send the email. At other times by the time they have replied to me, my brain has moved on with the problem sufficiently that I am close to a solution if I am not already there.

Other people use different items as their ‘Rubber Duck’, people on the [code newbie forum](http://discourse.codenewbie.org/t/whats-your-rubber-duck/61) have used items such as a cat, stuffed octopus, a Lego minfig, or just plain old talking to yourself.

Being the only programmer in my office is difficult. A simple what do you think of this question that could be asked across the office has to be done inside my head and I may think a needlessly complex solution is better than a simple one just because I haven’t thought of the simpler version yet. There are of course advantages to being the only programmer, I can do what I want and learn any technology I like, but I am starting to think the advantages of programming in a group are outweighing programming alone.