Skip to main content


Showing posts from April, 2016

Linked-list implementations of Stack, Queue and Bag from the textbook Algorithms by Robert Sedgewick and Kevin Wayne

Linked list implementation of a implements a generic stack using a linked list. To push() an item, we add it to the beginning of the list; to pop() an item, we remove it from the beginning of the list. Linked list implementation of a queue. Program implements a generic FIFO queue using a linked list. To enqueue() an item, we add it to the end of the list; to dequeue() an item, we remove it from the beginning of the list. Linked list implementation of a bag. Program implements a generic bag using a linked list. The implementation is the same as except for changing the name of push() to add() and removing pop().

How to Set / Change Host Name in CentOS 7 / RHEL 7 / Oracle Linux 7

See also: 
How to fix: unable to resolve host in Ubuntu
CentOS 7 supports three class of Host Names:

Static – The static host name is traditional host which can be chosen by the user and is stored in /etc/hostname file.Transient – The transient host name is maintained by kernel and can be changed by DHCP and mDNS.Pretty – It is a free form UTF -8 host name for the presentation to the user. To temporarily set the host name of centos, use hostname command.

However, once the server is rebooted, the hostname will revert to it's previous setting.

hostnamectl can be used to change the host name and it can change all the three class of host name.
Check the current host name:
$ sudo hostnamectl status $ sudo hostnamectl set-hostname i88ca $ sudo hostnamectl status

How to Mount NFS Share on Windows

To mount an NFS share into Windows we need to use the mount command. There is no GUI interface to perform this task. The command is very simple to use and relatively similar to the same command found in Linux. The examples below will connect to a host named LNXSRV01. The local user account on LNXSRV01 that will be used to mount the share will be i88ca. Open a command-prompt.Mount an NFS share called /exports/dept to the Z:.mount -user:i88ca -p:Password \\LNXSRV01\exports\dept Z: Instead of typing the password into the command-line, we can use ‘*’ to force a password prompt when mounting. mount -user:i88ca -p:* \\LNXSRV01\exports\dept Z: To mount the share into any available drive letter on the Windows server we can replace Z: with ‘*’. mount -user:i88ca -p:* \\LNXSRV01\exports\dept * Set whether the mount type is hard or soft using the mtype option. mount -o mtype=hard -user:i88ca -p:* \\LNXSRV01\exports\dept *

NFS hard mounts vs soft mounts

a) Hard mounts

Advantages: If the connection is lost and it is a minor problem, and you are ok with having all your NFS clients have frozen applications, and possibly have their entire systems frozen and useless until the NFS server comes back online, you may not lose any data when the NFS share becomes available again.

Disadvantages: If an application freezes and you can't bring up the NFS server, your only option appears to be to kill that application, even if it could have easily survived write errors. Also, a simple NFS share where you dump files once in a while, and that is completely unnecessary for the system to function, can freeze the entire system indefinitely if the server loses connection to the client.

b) Soft mounts

Advantages: They work as expected (for the most part) - if the server fails, the application gets an I/O error, and keeps going.

Disadvantage: According to the NFS man page, this leads to silent data corruption because applications get told prematurely th…

How to Install NFS Client on Windows Server

Install NFS Client Feature The NFS client is now an installable feature in Windows 8 and Windows Server 2012 and higher. Launch Server ManagerOn the top-left side of the console, click Manage.Click Add Roles and Features.On the Before you begin screen, click Next.On the Select installation type screen, select Role-based or feature-based installation, and then click Next.On the Select destination server screen, if you are installing to the local server, clickNext. Otherwise, select a server from the Server Pool list.On the Select server roles screen, click Next.On the Select features screen, scroll down the list of available features until you see Client for NFS. Click its checkbox to select it for installation, and then click Next.On the Confirm installation selections screen, review your selections and then click Install.After the installation completes, review the results and then click Close.

Text processing: sed awk perl python

sed - when you need to do simple text transforms on files. awk - when you only need simple formatting and summarization or transformation of data. perl - for almost any task, but especially when the task needs complex regular expressions. python - for the same tasks that you could use Perl for.

jcmd - a utility to send diagnostic command requests to a Java Virtual Machine supporting this feature.

Used without arguments or with the -l option, jcmd prints the list of running Java processes with their process ID, their main class and their command-line arguments. When a process ID is specified on the command line, jcmd sends the diagnostic command request to the process with this ID. When a main class is specified on the command line, jcmd sends the diagnostic command request to all Java processes for which the command-line argument is a substring of the Java process' main class. With the PerfCounter.print argument, jcmd prints the performance counters available on the targeted Java processes. With the -f option, jcmd sends to the targeted Java processes the diagnostic commands stored in the specified file.
Example usage: jcmd -l 4896 8102 -l 23610 com.sun.enterprise.glassfish.bootstrap.ASMain --domain domain1 --domaindir /d/glassfish-
-h Prints a help message. -helpPrints a help message. To find out what …

What Is The Difference Between Eager Zero And Lazy Zero Thick Provision Disks And Thin Provision?

Thick Provision Lazy Zeroed Creates  a virtual disk in a default thick format. Space required for the  virtual disk is allocated when the virtual disk  is created. Data  remaining on the physical device is not erased during creation, but is  zeroed out on demand at a later time on first write from the virtual  machine. Using  the default flat virtual disk format does not zero out or eliminate the  possibility of recovering deleted files or restoring old data that  might be present on this allocated space. You cannot convert a flat disk  to a thin disk. Thick Provision Eager Zeroed A  type of thick virtual disk that supports clustering features such as  Fault Tolerance. Space required for the virtual disk is allocated at  creation time. In contrast to the flat format, the data remaining on the  physical device is zeroed out when the virtual disk  is created. It  might take much longer to create disks in this format than to create  other types of disks. Thin Provision

Three important rules of thumb in developing recursive programs

A recursive method is a method that calls itself either directly or indirectly. There are three important rules of thumb in developing recursive programs:
The recursion has a base case.Recursive calls must address sub-problems that are smaller in some sense, so that recursive calls converge to the base case.Recursive calls should not address sub-problems that overlap.
Success is to be measured not so much by the position that one has reached in life as by the obstacles which he has overcome.
Booker Washington

Why use Font Awesome

Large collection of icons. You'll not only find social media icons here, but other traditional icons as well. CSS support. With CSS, you can adjust the icons according to what suits your site best. You can tinker with the colors, size, shadows and other components. This is something sorely lacking with non-vector images because you're stuck with the icon you chose.Speed. Vector images are lightweight and therefore load faster.Free. You don't have to pay a single thing when you use Font Awesome.
Andre Medeiros’ opinion: React turned out to disappoint me in multiple ways, mainly through a poorly designed API which induces the programmer […] to mix multiple concerns in one component.

Byte Buddy is a code generation library for creating Java classes during the runtime of a Java application and without the help of a compiler.

Other than the code generation utilities that ship with the Java Class Library, Byte Buddy allows the creation of arbitrary classes and is not limited to implementing interfaces for the creation of runtime proxies.

Byte Buddy is a light-weight library and only depends on the visitor API of the Java byte code parser library ASM which does itself not require any further dependencies.

Upgrading for performance

For better performance, It is good idea to upgrade the operating system, the JVM, the CLR, etc. The most common concern for not upgrading is “There might be bugs in the new version.”

To avoid that one can do regular continuous integration and testing, which should be a fundamental part of the development process.

FBI Makes Official Its Decision to Keep Apple iPhone Hack Secret
The U.S. House of Representatives voted unanimously to require law enforcement authorities to get a search warrant before asking technology companies to hand over old emails.

How to use Emoji with GitHub Markdown

GitHub Markdown supports emoji!  To see a list of every image we support, check out the Emoji Cheat Sheet.

Example to Customize Blockquote in Blogger

Add Custom CSS:
.postblockquote { font-size:16px; padding:18px20px1px20px; margin-left:3px; margin-bottom:40px; background:#f2f1f6; } .postblockquote:before { color: #c73401; font-size: 30px; line-height: 0.5em; margin-right: 0.27em; content: "\f10d"; font-family: FontAwesome; float:left; } .postblockquotea:hover{ color: #666; }
"Everything we do at Facebook is focused on our mission to make the world more open and connected."

-Mark Zuckerberg
How to add Font Awesome to your web site/blog

Why HipChat

HipСhat features code syntax highlighting which comes in very handy. You can use /code in HipChat to paste in code snippets, which the system would display with syntax highlighting.

Offline mode

If you and/or the other conversation participant are offline in Skype, a message to either of you won’t be delivered until you both log in. When it’s done, info might be irrelevant or received too late.

With HipСhat, you’ll get an email notification on messages you’ve received while being offline so you’ll never miss important news.

Slash Commands for Message Formatting on HipChat

Keep your team members on their toes by rendering your messages in style. Or, fix mistakes you made in your last message by replacing words (ah, the relief!).

How to Enable Password-based Login for Amazon EC2 / Google Compute Engine

Although ssh key-based login is preferred to password-based login, sometimes clients still need password-based login. Amazon EC2 / Google Compute Engine disable password-based login by default. To enable it,

# vi /etc/ssh/sshd_config
Find the line
PasswordAuthentication no and change it to
PasswordAuthentication yes
Save the file and restart sshd:
# /etc/init.d/sshd restartCaution: whenever making changes to your sshd.config file, be certain that you have an active shell session in case you've made a fatal syntax error. After restarting sshd, log in from another session to test it before terminating your active terminal session.

How to add IdentityFile to your SSH configuration file

For example, for Amazon AWS EC2, instead of
ssh -i ~/ [email protected] You just want to type:
ssh Add the following to your ~/.ssh/config file:
Host IdentityFile ~/ User ec2-user

How to fix Linux: Unable to negotiate with: no matching cipher found.

If you encounter something similar to:
Unable to negotiate with port 22: no matching cipher found. Their offer: blowfish-cbc,arcfour,arcfour128,arcfour256

You can login using one of the ciphers the server offer, such as: ssh -c blowfish-cbc [email protected]
You can add the server's supported ciphers to your client computer's ssh configuration file ( ~/.ssh/config )
Host Ciphers blowfish-cbc,arcfour,arcfour128,arcfour256

U.S. Web Design Standards

Open source UI components and visual style guide to create consistency and beautiful user experiences across U.S. federal government websites. Tools for creating beautiful online experiences for the American people Built and maintained by U.S. Digital Service and 18F designers and developers, this resource follows industry-standard web accessibility guidelines and reuses the best practices of existing style libraries and modern web design. It provides a guide for creating beautiful and easy-to-use online experiences for the American people.

Example of serving / sending a file from RESTFul web service

@[email protected](MediaType.APPLICATION_OCTET_STREAM)public Response getFile(){ File file =new File(...);return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition","attachment; filename=\""+ file.getName()+"\"").build();}

try{ response.setContentLength((int) file.getContentLength()); response.setHeader("Content-Disposition","attachment; filename="+ file.getName()); ServletOutputStream outStream = response.getOutputStream();byte[] bbuf =newbyte[(int) file.getContentLength()+1024]; DataInputStream in =new DataInputStream( file.getDataInputStream());int length =0;while((in !=null)&&((length =!=-1)){ outStream.write(bbuf,0, length);} in.close(); outStream.flush();}catch(Exception e){ e.printStackTrace();}return Response.ok().build();

Differences between Glassfish and WildFly


The JNDI name is used by the application to reference the datasource. That’s a fundamental difference between GlassFish and WildFly. GlassFish's JNDI name may look like jdbc/myds, but in WildFly you need to append the prefix java:/, resulting in java:/jdbc/myds. They appears in configuration file, persistence.xml and @Resource annotations

JavaMail Session

Glassfish: mail/myApp
WildFly: java:/mail/myApp
They appears in configuration file and @Resource annotations.
Security Realm
If you use a database as a security repository, in GlassFish it is called JDBCRealm, which is pretty restrictive. It requires you to provide a fixed database model. In WildFly, it is more flexible, you can actually specify a SQL query that finds in the database what the security domain needs to authenticate and to authorize users.

The role-group mapping you have in the file WEB-INF/glassfish-web.xml is corresponding to
<?xml version="1.0" encoding="UTF-8"…

How to access unmapped table in EclipseLink

TABLE allows access to unmapped tables. This can be used to access join, collection, history, auditing, or system tables for use in JPQL queries. TABLE requires 2.4+.TABLE exampleSELECT e, a.LAST_UPDATE_USERFROM Employee e, TABLE('AUDIT') a WHEREa.TABLE='EMPLOYEE'ANDa.ROWID= COLUMN('ROWID', e)

How to access unmapped columns in an object's table in EclipseLink

COLUMN allows access to unmapped columns in an object's table. This can be used to access foreign key columns, inheritance discriminators, or primitive columns such as ROWID. COLUMN can also be used in JPQL fragments inside the @AdditionalCriteria annotation. COLUMN requires EclipseLink 2.4.COLUMN examplesSELECT e FROM Employee e WHERECOLUMN('MANAGER_ID', e) = :id SELECT e FROM Employee e WHERECOLUMN('ROWID', e) = :id

How to use a Dropbox folder as a Git remote

git-remote-dropbox is a transparent bidirectional bridge between Git and Dropbox. It lets you use a Dropbox folder or a shared folder as a Git remote! This Git remote helper makes Dropbox act like a true Git remote. It maintains all guarantees that are provided by a traditional Git remote while using Dropbox as a backing store. This means that it works correctly even when there are multiple people operating on the repository at once, making it possible to use a Dropbox shared folder as a Git remote for collaboration. Once the helper is installed, using it is as simple as adding a remote like dropbox://path/to/repo. To clone repositories in folders or shared folders mounted in your Dropbox, you can run: git clone "dropbox://path/to/repo" To add a remote to an existing local repository, you can run: git remote add origin "dropbox://path/to/repo" The repository directory will be created automatically the first time you push. After adding the remote, you can treat it jus…

How to run Multiple Daemon Processes in Docker

We can use supervisord and run the supervisord daemon that will take care of keeping all the other wanted daemons alive.

Here is a example Dockerfile:

FROM centos:7 RUN yum install -y epel-release && \ yum update -y && \ yum install -y httpd \ mysql-server \ supervisor && \ yum clean all RUN /sbin/service mysqld start && \ mysqladmin -u root password '' RUN echo "[supervisord]" > /etc/supervisord.conf && \ echo "nodaemon=true" >> /etc/supervisord.conf && \ echo "" >> /etc/supervisord.conf && \ echo "[program:mysqld]" >> /etc/supervisord.conf && \ echo "command=/usr/bin/mysqld_safe" >> /etc/supervisord.conf && \ echo "" >> /etc/supervisord.conf && \ echo "[program:httpd]" >> /etc/supervisord.conf && \ …

How to show who is logged on and what they are doing on Linux

$ w The output of the command is the user's login name, the name of the terminal the user is on, the host from which the user is logged in, the time the user logged on, the time since the user last typed anything, and the name and arguments of the current process.

You can use both w and ps commands to find out who's doing what.

How to run docker in the background

Container should be run on background with docker run -d image your-command. Instead of running with docker run -i -t image your-command, using -d is recommended because you can run your container with just one command.

However, with -d option. Your container immediately stops unless the commands are not running on foreground.

For example, to run Apache service on a container. The intuitive way of doing this is
$ docker run -d apache-server apachectl start However, the container stops immediately after it is started. This is because apachectl exits once it detaches apache daemon.

Docker doesn’t like this. Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.

You can solve this by directly running apache executable with foreground option.
$ docker run -e APACHE_RUN_USER=www-data \ -e APACHE_RUN_GROUP=www-data \ -e APACHE_PID_FILE=/var/run/ \ …

How to fix doceker: exec format error

For example, you want to execute the following shell script.

echo "hello, world" Dockerfile
ADD /usr/local/bin/ RUN chmod +x /usr/local/bin/ CMD ["/usr/local/bin/"] When you run the container, your expectation is the container prints out hello, world. However, what you will get is a error message:
$ docker run -i hello_world_image2016/04/25 10:28:58 exec format error
You see this message when you didn’t put shebang in your script, and because of that, default entrypoint /bin/sh -c does not know how to run the script.

To fix this, you can either add shebang

#!/bin/bash echo "hello, world" or you can specify from command line.
$ docker run -entrypoint="/bin/bash" -i hello_world_image

Difference between CMD and ENTRYPOINT in Docker

Every commands, either passed as an argument or specified from CND instruction are passed as argument of binary specified in ENTRYPOINT.

/bin/sh -c is the default entrypoint. So if you specify CMD date without specifying entrypoint, Docker executes it as /bin/sh -c date.
By using entrypoint, you can change the behaviour of your container at run time that makes container operation a bit more flexible. ["/bin/date"] With the entrypoint above, the container prints out current date with different format. docker run -i clock_container +"%s" docker run -i clock_container +"%F"
You can only have one of each of CMD and ENTRYPOINT in your Dockerfile. CMD has a few different forms: it can specify an executable, or just specify parameters for the executable in ENTRYPOINT. ENTRYPOINT always specifies the executable as its first argument.
CMD [“apachectl”, “-D”, “FOREGROUND”] or
CMD [“-D”, “FOREGROUND”] ENTRYPOINT [“apachectl”] As you can see, each token in the full comma…

Dockerfile: automation of Docker image creation

Once, you write build instructions into Dockerfile, you can build the same image just with docker build command.

Dockerfile is also useful to tell what a job the container does to somebody else. Others can tell what the container is supposed to do just by reading Dockerfile. They don’t need to know login to the container and figure out what the container is doing by using ps command.

centralized logging and monitoring using the ELK stack ( ElasticSearch, LogStash, and Kibana)

ELK stack ( ElasticSearch, LogStash, and Kibana) has the advantage of being free, well documented, efficient, and widely used. 
ElasticSearch established itself as one of the best databases for real-time search and analytics. It is distributed, scalable, highly available, and provides a sophisticated API. 
LogStash allows us to centralize data processing. It can be easily extended to custom data formats and offers a lot of plugins that can suit almost any need. 
Kibana is an analytics and visualization platform with intuitive interface sitting on top of ElasticSearch.

Consul makes it simple for services to register themselves and to discover other services via a DNS or HTTP interface. Register external services such as SaaS providers as well.

Old tools, like Nagios, are not designed to handle constant changes in running servers and services. Consul provides a different, not to say new, approach to managing near real-time monitoring and reaction when thresholds are reached. Consul has multiple components, but as a whole, it is a tool for discovering and configuring services in your infrastructure. It provides several key features:Service Discovery: Clients of Consul can provide a service, such asapi or mysql, and other clients can use Consul to discoverproviders of a given service. Using either DNS or HTTP, applications can easily find the services they depend upon.Health Checking: Consul clients can provide any number of health checks, either associated with a given service ("is the webserver returning 200 OK"), or with the local node ("is memory utilization below 90%"). This information can be used by an operator to monitor cluster health, and it is used by the service discovery components to route tra…