Bytes, Nibbles, and Bits in Python

Binary

Binary is nothing more than a base 2 numbering system using the numbers 0 and 1.

Bit

A Bit is merely a single number of either 1 and 0 within the binary.

Byte

A Byte consists of 8 bits. A byte containing all 0s will be the integer 0, while a byte containing all 1s will be the integer of 255.

Nibble

A Nibble consits of 4 bits. A nibble containing all 0s will be the iteger 0, while a nibble containing all 1s will be the integer 15 (very useful for hex numbers).

Python code

What I want to do is write a Python class for taking a valid byte (number from 0 – 255), and get its binary representation. I would also like to get the high nibble and low nibble from that binary.

Constructor

Lets start by making a constructor and verifying we have a valid byte.

class Byte(object):
    """Do cool things with a 8 bit number"""

    def __init__(self, number):
        if not self.__isbyte(number):
            raise Exception('"%s" is not a 8 bit integer' % number)
        self.number = number

    def __isint(self, number):
        """Check if a input is of type int"""
        if type(number) == int:
            return True

    def __isbyte(self, number):
        """Check if a input is a byte, 0 - 255"""
        if self.__isint(number):
            if len(bin(number)[2:]) <= 8:
                return True

Alright, this code will let us define a object and verify it is a 8 bit integer.

Binary Representation

Next lets create the pretty binary representation with leading 0s as padding.

def __format(self, num, size=8):
    """Format a number as binary with leading zeros"""
    return str(bin(num)[2:]).zfill(size)

@property
def binary(self):
    """Return Byte in binary"""
    return self.__format(self.number)

Here I wrote a small helper function for extracting the binary representation from the bin function and stripped the leading 0b. The binary property will return the binary.

High Nibble

Being all bytes are 8 bits, we can be sure a byte will have a high nibble (first 4 bits), and a low nibble (last 4 bits).

In order to get our high nibble all we need to do is use the bitwise right shift operator.

def __high_nibble(self):
    """Use Bitwise shift to get high nibble from byte"""
    return self.number >> 4

@property
def high_nibble(self):
    """Return High Nibble in binary"""
    return self.__format(self.__high_nibble(), 4)

Low Nibble

In order to get our low nibble we can use the bitwise AND operator with a mask of 15 (remember 15 is a nibble of all 1s).

def __low_nibble(self):
    """Use Bitwise AND to get low nibble"""
    return self.number & 0x0F  # 0x0F == 15

@property
def low_nibble(self):
    """Return Low Nibble in binary"""
    return self.__format(self.__low_nibble(), 4)

Code in action

There you have it, lets go ahead and give it a try.

In [1]: myByte = Byte(15)

In [2]: myByte.binary
Out[2]: '00001111'

In [3]: myByte.high_nibble
Out[3]: '0000'

In [4]: myByte.low_nibble
Out[4]: '1111'

Working with Libvirt using Python

Today I decide to toy around with a KVM server we have running in house for testing. I started by using the libvirt Documentation, but it was very limited and I had to do some trial and error. I will go over a few basic things I learned using the libvirt Python module:

Normally we us virt-manager to connect to our KVM instances, and the authentication is tunnled over SSH (using SSH Keys) and QEMU. First things first I had to learn how to connect with the same method we used in virt-manager:

>>> import libvirt
>>> conn = libvirt.open("qemu+ssh://root@192.168.1.2/system")
>>> conn
<libvirt.virConnect instance at 0x2b518c0>

Using the open function I was able to successfully connect to our Hypervisor:

>>> conn.getHostname()
'kvm01.company.com'

From here I need only see our running virtual machines, and how to interact with them. I noticed two separate function the listDefinedDomains() and listDomainsID().

These two functions do two separate things, first lets go over listDefinedDomains(), this function will return a list of offline guest by name:

>>> conn.listDefinedDomains()
['rawhide', 'el4-i386', 'el5-64', 'el6-64', ....]

Where as listDomainsID() will return a list of online devices by ID:

>>> conn.listDomainsID()
[1, 2, 10, 3, 17, 7, 9, 8, 5, 6]

Once connected to the Domain you can get its name:

>>> for i in conn.listDomainsID():
...     print conn.lookupByID(i).name()
...
...
build01-dev
data01-dev
build02-dev
CentOS6-x86_64-dev
..

And as you would expect you can connect to either offline or online domains by using their name:

>>> dom = conn.lookupByName('build01-dev')
>>> dom
<libvirt.virDomain instance at 0x2b82c68>
>>> dom.name()
'build01-dev'

Now that we understand the process of connecting to our Hypervisor and parsing our Domains, lets go over how to start and stop these Domains, or as libvirt calls it create and destroy.

Lets start out with a offline (or destroyed) domain:

>>> dom = conn.lookupByName('rawhide')
>>> dom.isActive()
0

To bring this Domain online we need to use the create() function:

>>> dom.create()
0
>>> dom.isActive()
1

And to power it down you would destroy() it:

>>> dom.destroy()
0
>>> dom.isActive()
0

I hope this helped out a few of you out there, I know this was rather confusion when I first started messing around with it.

Line Equations in Python

The other day I was playing with some Python challenges found on a popular sites, this challenge worked with xy coordinates on a 2D plane.

I wanted to show some of the code I wrote and how they work.

The Plane

Being the data is a tuple of x, y coordinates we will use the Cartesian Coordinate System.

I started my code off as a simple Python class:

class Line(object):

    def __init__(self, data):
            self.first, self.second = data

Using this Class I can input two points in a tuple like this:

data = ((1,1), (2,3))

These coordinates would look like this on a 2D plane:

plane1

The Line

The coordinates ((1,1), (2,3)) holds quite a bit of data when it comes to the terms of Algebra.

Slope

The Slope of a line will tell us how steep it is, and can be calculated with the change in Y / change int X.

def slope(self):
        '''Get the slope of a line segment'''
        (x1, y1), (x2, y2) = self.first, self.second
        try:
                return (float(y2)-y1)/(float(x2)-x1)
        except ZeroDivisionError:
                # line is vertical
                return None

Using the slope method tells us this line has a slope of 2.

>>> data = ((1,1), (2,3))

>>> line = Line(data)

>>> m = line.slope()

>>> print m
2.0

Y Intercept

The Y Intercept tells us at what point a line will meet the Y axis. To get a Y Intercept we use the equation b = y – mx where m is our slope.

def yintercept(self, slope):
        '''Get the y intercept of a line segment'''
        if slope != None:
                x, y = self.first
                return y - slope * x
        else:
                return None

And if we plug all our data back in we get a intercept of -1:

>>> b = line.yintercept(slope)

>>> print b
-1.0

Solve for Y

Now that we know the slope of our line, and where our line meets the Y Axis we can plug in any X coordinate and solve for where Y will be:

def solve_for_y(self, x, slope, yintercept):
        '''Solve for Y cord using line equation'''
        if slope != None and yintercept != None:
                return float(slope) * x + float(yintercept)
        else:
                raise Exception('Can not solve on a vertical line')

And just like that we can when X is equal to 3 our Y will be 5, just look at the graph above and imagaine.

>>> line.solve_for_y(3, m, b)
5.0

Solve for X

And lastly using our slope and Y intercept we can solve for X when Y is some value:

def solve_for_x(self, y, slope, yintercept):
        '''Solve for X cord using line equatio'''
        if slope != 0 and slope:
                return float((y - float(yintercept))) / float(slope)
        else:
                raise Exception('Can not solve on a horizontal line')

And we can do the reverse of above to verify they are both working, when X is equal to 5 our Y should be 3:

>>> line.solve_for_x(5, m, b)
3.0

Put it all together

class Line(object):

    def __init__(self, data):
            self.first, self.second = data

    def slope(self):
            '''Get the slope of a line segment'''
            (x1, y1), (x2, y2) = self.first, self.second
            try:
                    return (float(y2)-y1)/(float(x2)-x1)
            except ZeroDivisionError:
                    # line is vertical
                    return None

    def yintercept(self, slope):
            '''Get the y intercept of a line segment'''
            if slope != None:
                    x, y = self.first
                    return y - slope * x
            else:
                    return None

    def solve_for_y(self, x, slope, yintercept):
            '''Solve for Y cord using line equation'''
            if slope != None and yintercept != None:
                    return float(slope) * x + float(yintercept)
            else:
                    raise Exception('Can not solve on a vertical line')

    def solve_for_x(self, y, slope, yintercept):
            '''Solve for X cord using line equatio'''
            if slope != 0 and slope:
                    return float((y - float(yintercept))) / float(slope)
            else:
                    raise Exception('Can not solve on a horizontal line')

DIY Living Room Bar


Material Used:

Framing: 2x4
Bar Top: 1x12
Work Area Top: 3/4" Plywood
Foot Rest: 1x6, 1x4
Panel: Standard Siding
Below Counter space: 1x6
Wine Rack: 1x6, 1x4
Trim: Random Molding

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com

View post on imgur.com