How to split up a git commit
Quick steps
-
git rebase -i
-> mark your commit withedit
-
git reset HEAD~
(remove the marked commit, but keep its changes) - Make several commits (optionally setting the previous author manually)
git rebase --continue
Detailed instructions
Basically, you will review the last n
commits and stop at the splittable commit. Then you'll undo that commit and put its changes into new commits at your liking.
-
Review commits (
rebase
)git rebase -i HEAD~3 # or git rebase -i origin/master
...
AngularJS: How to force Content-Type on GET and DELETE requests
While you usually do not need a Content-Type
on GET request (which have a blank body), an external API may still force you to send one.
Angular's $http
service will strip that header when the request data (body) is blank. [1] This is possibly a misconception of RFC2616.
Here is how to send GET requests with a Content-Type
header in Angular.
Example
Consider this request:
$http({ me...
Configure RSpec to raise an error when stubbing a non-existing method
You can configure RSpec 3.3+ to raise an error when attempting to stub or mock a non-existing method. We strongly recommend to do this as non-verified stubs are a footgun.
You can enable this behavior by adding the following to your spec_helper.rb
:
RSpec.configure do |config|
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
This will also replace stub_existing
from our rspec_candy.
About Ruby's conversion method pairs
Ruby has a set of methods to convert an object to another representation. Most of them come in explicit and implicit flavor.
explicit | implicit |
---|---|
to_a |
to_ary |
to_h |
to_hash |
to_s |
to_str |
to_i |
to_int |
There may be even more.
Don't name your methods like the implicit version (most prominently to_hash
) but the like the explicit one.
Explicit conversion
Explicit conversion happens when requesting it, e.g. with the splat opera...
Sending TCP keepalives in Ruby
When you make a simple TCP connection to a remote server (like telnet
), your client won't normally notice when the connection is unexpectly severed on the remote side. E.g. if someone would disconnect a network cable from the server you're connected to, no client would notice. It would simply look like nothing is being sent.
You can detect remote connection loss by configuring your client socket to send TCP keepalive signals after some period of inactivity. If those signals are not acknowledged by the other side, your client will terminat...
Fix "subprocess installed post-removal script returned error exit status ..." when installing/removing/updating a package with apt
If you get an error like:
subprocess installed post-removal script returned error exit status 78
when installing/removing/updating a package with apt you should check the postinst
, postrm
, prerm
, ... script in /var/lib/dpkg/info/
.
For example in my case I had a problem when removing varnish:
Removing varnish (4.0.3-2~trusty) ...
dpkg: error processing package varnish (--remove):
subprocess installed post-removal script returned error exit status 78
Errors were encountered while processing:
varnish
So I checked ...
Test downstream bandwidth of Internet connection
You want to test your 1GE or 10GE internet uplink? We needed to ensure we have full 10GE to the backbone for a customer project.
Using netcat
To test whether we can achieve the bandwidth internally, you can use netcat and dd like this:
On your first server: nc -v -l 55333 > /dev/null
On your second server: dd if=/dev/zero bs=1024K count=5000 | nc -v $remote_ip 55333
You should see some output like this:
user@xxx:~ % dd if=/dev/zero bs=1024K count=5000 | nc -v removed 55333
Connection to 91.250.95.249 55333 port [...
How to remove properties of ActiveRecord scopes
When dealing with AR scopes, you can remove conditions, order, etc by using the unscope
method.
It is available on Rails 4+.
Examples
Consider an exemplary User
class as follows. For the examples below, we will use a scope that applies all its constraints.
class User < ActiveRecord::Base
scope :active, -> { where(locked: false) }
scope :admins, -> { where(role: 'admin') }
scope :ordered, -> { order(:name) }
end
users = User.active.admins.ordered
^
SELECT "users".* FROM "users" WHERE "use...
A case for Redactor
Redactor is yet another WYSIWYG editor. It definitely has its weak points, but I want to point out that it has clear strengths, too.
Pro
- Simple and beautiful interface.
- Outstandingly organized source code. Have never seen a JS library that was this structured.
- Clear, comprehensive and searchable API documentation. Filled with code examples.
- Easily customizable: specify toolbar buttons, pass various callbacks, etc.
- Features a collection of great [plugins](ht...
PostgreSQL: How to add/remove/modify array values (and how to replace 1 value with multiple values)
PostgreSQL's array data type is pretty useful, but manipulating values of arrays can be awkward because of its syntax.
Consider the following users
table which each example below will start from:
name | topics |
---|---|
Alice | {cats,dogs} |
Bob | {llamas} |
(PostgreSQL uses curly braces to represent arrays, true story.)
Adding values
Use the array_cat
function, or the ||
operator.
These calls will add the values "cats" and "mice" to use...
Keeping web applications fast
Our applications not only need to be functional, they need to be fast.
But, to quote Donald Knuth,
premature optimization is the root of all evil (or at least most of it) in programming
The reasoning is that you should not waste your time optimizing code where it does not even matter. However, I believe there are some kinds of optimizations you should do right away, because
- they are either obvious and easy
- or they are very hard to do optimize later
This is an attempt to list some of those things:
On the server
...
Heads up: Ruby implicitly converts a hash to keyword arguments
When a method has keyword arguments, Ruby offers implicit conversion of a Hash
argument into keyword arguments. This conversion is performed by calling to_hash
on the last argument to that method, before assigning optional arguments. If to_hash
returns an instance of Hash
, the hash is taken as keyword arguments to that method.
Iss...
Ruby: Do not mix optional and keyword arguments
Writing ruby methods that accept both optional and keyword arguments is dangerous and should be avoided. This confusing behavior will be deprecated in Ruby 2.7 and removed in Ruby 3, but right now you need to know about the following caveats.
Consider the following method
# DO NOT DO THIS
def colored_p(object = nil, color: 'red')
switch_color_to(color)
puts object.inspect
end
colored_p(['an array']) # ['an array'] (in red)
colored_p({ a: 'hash' }, color: 'blue') # {:a=>'hash'} (in blue)
colored_p({ a: 'ha...
Enumerators in Ruby
Starting with Ruby 1.9, most #each
methods can be called without a block, and will return an enumerator. This is what allows you to do things like
['foo', 'bar', 'baz'].each.with_index.collect { |name, index| name * index }
# -> ["", "bar", "bazbaz"]
If you write your own each
method, it is useful to follow the same practice, i.e. write a method that
- calls a given block for all entries
- returns an enumerator, if no block is given
How to write a canonical each
method
To write a m...
OR-ing query conditions on Rails 4 and 3.2
Rails 5 will introduce ActiveRecord::Relation#or
. On Rails 4 and 3.2 you can use the activerecord_any_of
gem which seems to be free of ugly hacks and nicely does what you need.
Use it like this:
User.where.any_of(name: 'Alice', gender: 'female')
^
SELECT "users".* FROM "users" WHERE (("users"."name" = 'Alice' OR "users"."gender" = 'female'))
To group conditions, wrap them in hashes:
User.where.any_of({ name: 'Alice', gender: 'female' }, { name: 'Bob' }, { name: 'Charl...
Know what makes your browser pant
I figure we needed a definitive reference for what work is triggered by changing various CSS properties. It's something I get asked about often enough by developers, and while we can do tests with DevTools, I have both the time and inclination to shortcut that for everyone. I'm nice like that. —Paul Lewis
Improving browser rendering performance
As the web is being used for more and more tasks, expectations rise. Not only should web pages offer rich interaction, they must be responsive in both size and interaction.
This imposes a paradoxon that needs to be solved by building performing applications. It's not enough any more to have your web site do crazy stuff, it is also required to do it crazy fast. This card is intended to give you an introduction to this emerging aspect of web development.
Read this introductory [performance study on Pinterest](http://www.smashingmagazine.com/...
Regain unused disk space from OpenStack instances
This is how you regain disk space from OpenStack instances if you are using kvm and qcow.
If your instance used up all configured disk space once the disk file remains big. You can end up in a situation where for example the instance use only 20GB disk space but the disk file on the server has 100GB (or even more).
To resize the disk file do the following:
-
Check storage on the instance:
vm $ df -h Filesystem Size Used Avail Use% Mounted on /dev/vda1 99G 19G 75G 21% / udev 2.0G 12K 2.0...
Angular: Quick and easy animation on changed binding value
With ngAnimate, you can easily animate certain events (see directive support). We'll make use of ngClass
animations to style an element on changed binding value.
Say we have a slider and a separate details container. Each time the slider changes, we want to "flash" the details container by hiding it and fading it back in.
HTML
Add a custom class to the element you want to animate, i.e. the details container:
<div class="details slide-index-{{ currentSlideIndex }}">
{{ co...
Error installing gem with native extension (collect2: error: ld returned 1 exit status)
If you have problems installing a gem and get a error collect2: error: ld returned 1 exit status
it's due to missing development headers of a library (ld
is the linker).
For example, with this output:
$ gem install json
Building native extensions. This could take a while...
ERROR: Error installing json:
ERROR: Failed to build gem native extension.
/home/foobar/.rvm/rubies/ruby-2.2.3/bin/ruby -r ./siteconf20150915-3539-1i9layj.rb extconf.rb
creating Makefile
make "DESTDIR=" clean
make "DESTDIR="
compiling generator.c...
natritmeyer/site_prism
SitePrism gives you a simple, clean and semantic DSL for describing your site using the Page Object Model pattern, for use with Capybara in automated acceptance testing.
The Page Object Model is a test automation pattern that aims to create an abstraction of your site's user interface that can be used in tests. The most common way to do this is to model each page as a class, and to then use instances of those classes in your tests.
If a class represents a page then each element of the page is represented by a method that, when cal...
Migrating legacy jQuery code to .on() and .off()
If you need to upgrade code that uses the old jQuery methods bind
, delegate
, live
, unbind
and die
, the attached article has examples how to migrate to the new on
and off
versions.
httpbin: HTTP Client Testing Service
Some dozen generic API endpoints you can use to test how your HTTP client deals with various responses, e.g.
- a slow connection
- many redirects
- compressed data
I found this useful while debugging an issue with timeouts.
Bootstrap 4 is coming
What's new
- Moved from Less to Sass. Bootstrap now compiles faster than ever thanks to Libsass, and we join an increasingly large community of Sass developers.
-
Improved grid system. We’ve added a new grid tier to better target mobile devices and completely overhauled our semantic mixins.
Opt-in flexbox support is here. The future is now—switch a boolean variable and recompile your CSS to take advantage of a flexbox-based grid system and components. - Dropped wells, thumbnails, and panels for cards. Cards are a brand new co...