Saturday, October 27, 2012

Ruby get method arguments

So, say you are writing some Ruby code, and want to get an overview of the arguments for a method, dynamically.

Consider this method with arguments a and b:

def foobar a, b
end

Using method(...), we can pass in the special variable __method__ to get the current method.

In turn, we can get the parameters of the method with .parameters, and we can then iterate over the parameters.

Now our code would look something like this:

def foobar a, b
  method(__method__).parameters.each do |arg|
    # ...
  end
end

In order to get the correct parameter name with it's associated value, the final solution would be:

def foobar a, b
  method(__method__).parameters.each do |arg|
    val = eval arg[1].to_s
    puts "#{arg[1]}: #{val}, #{val.class}"
  end
end

Happy coding!

Tuesday, October 9, 2012

Validate XML and DTD

Back to school again, I found that I needed to write some XML and DTD by hand.

The most important aspect of the process is to have a valid XML document as well as a valid DTD. There are perhaps some online tools for this, but none of them are very intuitive.

However, there is a tool named xmllint which does exactly this.

It is included with libxml (package), so there's a great chance you already have it.

Here is an example on how to use it:

editors.dtd

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT editors (editor)>
<!ELEMENT editor  (title, desc?)>
<!ELEMENT title   (#PCDATA)>
<!ELEMENT desc    (#PCDATA)>

editors.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE editors SYSTEM "editors.dtd">
<editors>
  <editor>
    <title>Vim
    <!--Powerful text editor-->
  </editor>
</editors>

And to validate the DTD and XML, execute the following from your command line:
xmllint --valid editors.xml  --dtdvalid editors.dtd

Note: use can use xmllint to validate XML Schemas just use the above command and replace --dtdvalid with with -schema and provide a schema file instead of the DTD file.

Hope that helps!

Wednesday, August 8, 2012

sed replace example

The following command is probably one of the most useful commands one can use to edit parts of files.

grep -lr "int main()" * | xargs sed -i -e 's/foo/bar/'

This will replace all occurrences of foo with bar in all files recursively if they contain int main(). E.g.

int main() {
    int foo = 0;

    return foo;
}

Will be changed to:

int main() {
    int bar = 0;

    return bar;
}

Sunday, July 8, 2012

iptables redirect port

Sometimes you may want to allow users access certain ports. To do so run the following command:

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

This will allow all HTTP (80) traffic to be redirected to port 3000.

Friday, July 6, 2012

jQuery single draggable in droppable

jQuery UI is a library that works with jQuery which allows you to easily drag and drop elements.

However, sometimes when you have more draggables and wish to let only one reside inside a droppable, you may need to take actions.

Here is some self explaining code that does just that:

$('.item').draggable({
  opacity: 0.35,
  revert: true,
  snap: true,
  zIndex: 2800
});

$('.box').droppable({
  greedy: true,
  drop: function(e, ui) {
    $(this).droppable('option', 'accept', ui.draggable);
    $(this).append(ui.draggable);
  },
  out: function(e, ui) {
    $(this).droppable('option', 'accept', '.item');
  }
});

Thursday, June 28, 2012

cannot load such file -- zlib

When getting started with Ruby, this error might appear:


ERROR: Loading command: install (LoadError)
cannot load such file -- zlib
ERROR: While executing gem ... (NameError)
uninitialized constant Gem::Commands::InstallCommand


However, it is fairly simple to fix. Run the following commands from your terminal.

rvm pkg install zlib
rvm remove 1.9.3
rvm install 1.9.3

Hope that helps!

Thursday, June 21, 2012

Gnome Shell grid workspaces

By default, Gnome Shell tries to maintain only one workspace including the ones that are in use. This can be a great pain when being used to have some sort of structure on your desktop.

There is however a combination of extensions for Gnome Shell that allows you to configure your good 'ol 3x3 or 6x2 set of workspaces! Here are the links:


When both are installed, rigt click anywhere on the workspace indicator on the bottom right side of the screen and select how many workspaces (vertical and horizontal) you want.

Update:

You may also want to hide the bottom panel. By default this is not an option.
However, there are basically two fixes available.

1. With CSS (the most clean way)

Open, and edit ~/.local/share/gnome-shell/extensions/Bottom_Panel@rmy.pobox.com/stylesheet.css on line 6, change the height to 0px.

All credit goes to Brian McSweeney

2. With JavaScript (the alternative way)

For instructions, have a look at this comment at Ask Ubuntu.

All credit goes to Rasmus.

PS

In both cases, remember to update GNOME Shell (Alt + F2) and execute 'r' (for refresh).

Happy tweaking!

Saturday, June 9, 2012

Log out of basic auth with JavaScript

Ever wanted to log out of a basic authentication session with only JavaScript?

The following code requires jQuery, but it is of course possible to hack something together with plain JavaScript.

$.get(document.URL.replace(/(https?:\/\/)/, '$1logout@'));

Update:
I have figured out that this doesn't work all the time, and it seems unreliable. However, it may be used as a last resort.

Saturday, May 26, 2012

MySQL server socket

This error is pretty common:
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111)
The solution is fairly simple, though. In the terminal type the follwing:
service mysqld restart

Wednesday, May 2, 2012

JavaScript capture groups

/\w+-(\d+)-\w+/.exec('foo-36-bar')[1];
//   ^   ^
//   |   |
//   L___L_________ The capture group
//

This JavaScript regex extracts the number 36 from the string.

P.S. The index is 1, because index 0 will yield the entire string.

Sunday, March 18, 2012

Kill a process on a specific port

Here is how you easily can kill processes running on a particular port on Linux:

lsof -ti :8080 | xargs kill -9

This is useful when for some reason your server has stopped working properly.

Thursday, March 15, 2012

Git default editor

Sometimes when installing a new distro and Git, the editor may not be correctly configured.

Therefore, you may want to run the following command to update it:
git config core.editor 'vim'

Wednesday, March 7, 2012

Simple JMS Queue Example

I have two example "applications" communicating using JMS.


The two projects are well documented. Have a look at the READMEs in both projects for details.

Sunday, March 4, 2012

Spotify Fedora Errors

Chances are that bugs may occur when using Spotify on Fedora.

112, 114 and 117 are all error codes.

Here is what you should do:
  1. Log out of Spotify
  2. Delete .config/spotify/ and .cache/spotify/ (usually located in the user's home folder).
  3. Log in to Spotify

Saturday, February 18, 2012

Simple xargs example

Say I want to install an rpm package with dependencies. Without knowing about the dependencies I would try:

rpm -i foo.rpm

However, I would then get a warning that there are unresolved dependencies.

One solution is to use yum install with xargs. Here is an example:

ls | xargs yum install -y

You may also want to use grep or something similar to have a criteria passed to xargs

Thursday, February 16, 2012

AWK instead of AWK & grep

Say I want to use df -h to see my available disk space, however I would only like the output the space currently available for rootfs.

I could do:

df -h | grep rootfs | awk '{print $2}'

This however, is a waste of resources because you are piping unnecessarily many times and it is also not very elegant, the following way is more preferable:

df -h | awk '/rootfs/ {print $2}'