Algorithms: Array Parity


You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this “outlier” N.

[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)


package main

import (

func find_outlier(integers []int32) int32 {
      test_result := integers[0] % 2 + integers[1] % 2 + integers[2] % 2;
      var expected_result int32 = 1
      if test_result <= 1{
         expected_result = 0
      for _, value := range(integers) {
           if  value % 2 != expected_result {
               return value
      return -1
func main() {
	fmt.Println(find_outlier([]int32{160, 3, 1719, 19, 11, 13, -21}))


def find_outlier(integers):
    test_bed = sum([integers[0] % 2,integers[1] % 2,integers[1] % 2])
    if test_bed <= 1:
        base_result = 0 #series is mostly even
         base_result = 1 
    for i in integers:
      if i % 2 != base_result:
         return i
    return None


 #![allow(unused)] fn find_outlier(integers: &[i32]) -> i32{
    let test_bed: i32 = integers[0] % 2 + integers[1] % 2 + integers[1] % 2;
    let mut expected_result: i32 = 1;
    if test_bed <= 1{
        expected_result = 0;
    for i in integers.iter(){
        if *i != expected_result{
            return *i
    return -1
fn main() {
  assert_eq!(find_outlier(&[160, 3, 1719, 19, 11, 13, -21]),160);

Algorithm Interview Questions: Square


Given an integral number, determine if it’s a square number:
In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.


isSquare(-1) returns  false
isSquare(0) returns   true
isSquare(3) returns   false
isSquare(4) returns   true
isSquare(25) returns  true  
isSquare(26) returns  false


import math
def is_square(n):
    upper_index = n
    lower_index = 0
    while upper_index >= 1:
      upper_index = math.ceil(upper_index/2)
      if upper_index**2 == n:
         return True
      elif upper_index**2 > n:
      elif upper_index**2 < n:
          for index in range(upper_index+1,(upper_index*2)+1):
             if index**2 == n:
                 return True
    return False # fix me


package main

import (
func is_square(num int32) bool{
     n := float64(num)
     lower_bound := n
     for lower_bound >= 0 {
          lower_bound = math.Ceil(lower_bound/2)
          if math.Pow(lower_bound,2.0) == n{
             return true
          }else if math.Pow(lower_bound,2.0) > n{
          }else if math.Pow(lower_bound,2.0) < n{
              for i := lower_bound +1; i < lower_bound * 2; i += 1{
                     if  math.Pow(i,2.0) == n {
                            return true
              return false
     return false
func main() {
	fmt.Println("Hello, playground")


fn is_square(n: i32) -> bool{
    let mut lower_bound = n;
    while lower_bound >= 0{
      lower_bound = (lower_bound as f64 / 2.0 as f64).ceil() as i32;
      if lower_bound.pow(2) == n{
          return true
      }else if lower_bound.pow(2) > n{
      }else if lower_bound.pow(2) < n{
          for i in (lower_bound+1..lower_bound*2){
              if i.pow(2) == n{
                 return true
        return false
    return false

fn main() {

Troubleshooting Linux: Part 1

  • I am looking for a command line solution that would return me the primary (first) IP address of the localhost, other than

    The solution should work at least for Linux (Debian and RedHat) and OS X 10.7+

    I am aware that ifconfig is available on both but its output is not so consistent between these platforms.

    ip route get 1 | awk '{print $(NF-3); exit}'</pre>
    <div class="post-text">
    Is there any Linux command to translate domain name to IP?
    You have multiple options to resolve this. You can use dig, nslookup as well as host.
    ~$ nslookup
    Non-authoritative answer:
    Address: 2620:100:6040:1::a27d:f801
    ~$ dig
    ; &lt;&gt; DiG 9.11.3-1ubuntu1.5-Ubuntu &lt;&gt;
    ;; global options: +cmd
    ;; Got answer:
    ;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 1369
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
    ; EDNS: version: 0, flags:; udp: 65494
    ;			IN	A
    ;; Query time: 35 msec
    ;; SERVER:
    ;; WHEN: Mon Apr 15 21:16:32 CDT 2019
    ;; MSG SIZE  rcvd: 56
    $ host has address has IPv6 address 2620:100:6040:1::a27d:f801 mail is handled by 1 mail is handled by 10 mail is handled by 10 mail is handled by 5 mail is handled by 5

    As you can see above, most of them returned the non-authoritative answer to your request.

    • I am programming a server and it seems like my number of connections is being limited since my bandwidth isn't being saturated even when I've set the number of connections to "unlimited".

      How can I increase or eliminate a maximum number of connections that my Ubuntu Linux box can open at a time? Does the OS limit this, or is it the router or the ISP? Or is it something else?

    #on client side, modify your tcp stack parameters
    sysctl net.ipv4.ip_local_port_range #increasing this will increase the number of ports connections you can make over a single IP
    sysctl net.ipv4.tcp_fin_timeout #This answers the question of, how long to hold on to socket while in wait state.
    sysctl net.ipv4.tcp_tw_reuse=1 #This indicates that socket can be used for making connection while in time wait. Please be careful with this option. I can fully explain why lol
    #on server side
    sysctl net.core.somaxconn=1024 #This decides how many requsts a listening socket can queue.
    ifconfig eth0 txqueuelen 5000 #This sets the number of traffic that can be queue on your network card.
    sysctl net.core.netdev_max_backlog=2000 #This defines how many of those networks that made it through the NIC will be queued
    sysctl net.ipv4.tcp_max_syn_backlog=2048 #Thia queue decides how many unacknowdleged sync can be held.


    • Is there some simple sysctl variable to allow non-root processes to bind to "privileged" ports (ports less than 1024) on Linux, or am I just out of luck?

    Yes, you can use option to set net.ipv4.ip_unprivileged_port_start. This allow you to control where "privledge" port starts.


Troubleshooting: findmnt


  • I am using

    mount -o bind /some/directory/here /foo/bar

    I want to check /foo/bar though with a bash script, and see if its been mounted? If not, then call the above mount command, else do something else. How can I do this?

    CentOS is the operating system.

    You can use findmnt to solve it by passing the directory to the -M option;

    # findmnt -M /home/blackswan/point
    TARGET                SOURCE           FSTYPE OPTIONS
    /home/blackswan/point /dev/sda1[/test] ext4   rw,relatime,errors=remount-ro


  • I am currently using the last version of owncloud. Since the installation, I cannot login anymore. A quick look at /var/log/apache2/error.log explains why :WARNING: could not create relation-cache initialization file “global/pg_internal.init.7826”: No space left on device
    DETAIL: Continuing anyway, but there’s something wrong.
    WARNING: could not create relation-cache initialization file “base/17999/pg_internal.init.7826”: No space left on device
    DETAIL: Continuing anyway, but there’s something wrong.

You can check the space left on your root  device using -D option.

# findmnt -D /
/dev/sda1 ext4   39.1G  7.1G   30G  18% /
  • Is there a Linux command to easily find out which partition/mount a directory or file is on?

    (This is probably a RTM question, and I feel guilty for asking it, but somehow, I can’t find a good answer on google just yet..

You can easily find this using the -T command options; this tells you where a particular path is mounted.

# findmnt -T /home/blackswan/Documents
/      /dev/sda1 ext4   rw,relatime,errors=remount-ro

Helpful links:

Linux: Find a directory mount path

You have a linux system and you want to find where a particular file path is mounted.

You can use the the findmnt command to see where a particular path is mounted.

findmnt -T /usr/share/applications
/      /dev/sda1 ext4   rw,relatime,errors=remount-ro

Linux: Mount Namespace

.The purpose of each namespace is to wrap a particular global system resource in an abstraction that makes it appear to the processes within the namespace that they have their own isolated instance of the global resource.

Mount Namespace

They isolate the list of mount points seen by the processes in a namespace. Or, to put things another way, each mount namespace has its own list of mount points, meaning that processes in different namespaces see and are able to manipulate different views of the single directory hierarchy.

Shared subtrees

The key benefit of shared subtrees is to allow automatic, controlled propagation of mount and unmount events between namespaces. This means, for example, that mounting an optical disk in one mount namespace can trigger a mount of that disk in all other namespaces.

  • MS_SHARED: This mount point shares mount and unmount events with other mount points that are members of its “peer group” (which is described in more detail below). When a mount point is added or removed under this mount point, this change will propagate to the peer group, so that the mount or unmount will also take place under each of the peer mount points. Propagation also occurs in the reverse direction, so that mount and unmount events on a peer mount will also propagate to this mount point.
  • MS_PRIVATE: This is the converse of a shared mount point. The mount point does not propagate events to any peers, and does not receive propagation events from any peer
  • MS_SLAVE: This propagation type sits midway between shared and private. A slave mount has a master—a shared peer group whose members propagate mount and unmount events to the slave mount. However, the slave mount does not propagate events to the master peer group
  • MS_UNBINDABLE: This mount point is unbindable. Like a private mount point, this mount point does not propagate events to or from peers. In addition, this mount point can’t be the source for a bind mount operation
Peer groups

A peer group is a set of mount points that propagate mount and unmount events to one another. A peer group acquires new members when a mount point whose propagation type is shared is either replicated during the creation of a new namespace or is used as the source for a bind mount.  Conversely, a mount point ceases to be a member of a peer group when it is unmounted, either explicitly, or implicitly when a mount namespace is torn down because the last member process terminates or moves to another namespace.

Default Propagation

So what happens when we bind a mount? From the kernel’s perspective, the default when a new device mount is created is as follows:

  • If the mount point has a parent (i.e., it is a non-root mount point) and the propagation type of the parent is MS_SHARED, then the propagation type of the new mount is also MS_SHARED.
  • Otherwise, the propagation type of the new mount is MS_PRIVATE.

But you have to beware when working with unshare. When creating a new mount namespace, unshare assumes that the user wants a fully isolated namespace, and makes all mount points private by performing the equivalent of the following command (which recursively marks all mounts under the root directory as private):

    mount --make-rprivate /

To prevent this, we can use an additional option when creating the new namespace:

    unshare -m --propagation unchanged 

Useful Links:


Python: Break and Continue

The break statement, like in C, breaks out of the innermost enclosing for or while loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

for i in range(3,10,2):
   if i == 7:
     print("I encountered {}".format(i))
else: #This only executes if for loop runs all the way through
  print("I just exited")

One alternative to breaking is using return inner function and this can be quite useful when you are trying to multilevel return.

Detecting A Break

You can use the continue keyword to detect if a break occurred during your loop or not. An example will be the application below;

for x in range(5):
  for  y in range(7):
      if y == 3:
         break #break out of the inner loop
       This continue is a way to detect if we did not have a short stop during our loop and finished the loop process
    continue #The purpose of the continue is to  detect if we did not break out
  #Anything here will only executes if we broke out of the inner loop
  print("Yes, there was a break")

Multi-level break

There are certain situations that will require breaking out of  outter loop from inner loop and this, python does not support natively. You have couple of options as discussed in this stackoverflow thread; ranging from refactoring to functions  using ‘return‘ all the way to using extremes like exceptions.

Useful Links