Skip to main content

Posts

How to use python to create Union as in C

The below example shows how to use python to create a union and use it.
from ctypes import *
class barley_amount(Union):
   _fields_ = [
   ("barley_long", c_long),
   ("barley_int", c_int),
   ("barley_char", c_char * 8),
 ]
value = raw_input("Enter the amount of barley to put into the beer vat:")
my_barley = barley_amount(int(value))
print "Barley amount as a long: %ld" % my_barley.barley_long
print "Barley amount as an int: %d" % my_barley.barley_long
print "Barley amount as a char: %s" % my_barley.barley_char


(ref: gray hat python)
Recent posts

How to Use C Programming Language with Python

C is one of the first programming language a programmer should learn. But the syntax of the language and semicolons make it hard. But C is the most powerful language ever created. So, we want to use power of C in python and python provides a very good way to do so.

On windows the C runtime is msvcrt.dll which is located in C:\Windows\System32 and on linux it is libc.so.6. We will write a code in Windows and see the result. So Let us C -


from ctypes import *
msvcrt=cdll.msvcrt
message_string="My Name is Anthony\n"
msvcrt.printf("Testing %s",message_string)

In the above code we import all the modules of ctypes, which is responsible for using C in python. Then assign a variable to the dll we need to run the code in the second line. Next, the string we want to print. In the next statement we use pure C function printf() to print our message.

Similarly for Linux OS we need to do a little change. Just replace the second statement to have that libc.so.6. e.g.


from ctypes impo…

Extracting Email id Using Python Regular Expression

Regular expression is handy for extracting important part from a document or a string.  Suppose you want to extract email id from a string then it can be easily done by '\S+@\S+' this expression. Where \S represents non-whitespace character, then followed by an @ sign and again by \S;as actually it is in a generic email id. So , let's get the code and extract email id - 


import re
str = 'I have tried to email you at medhrk@gmail.com but it did not work so I send the mail to you by using your rediff account idhrk@rediffmail.com  at  @2PM'
lst = re.findall('\S+@\S+', str)
print lst

The output will be  - ['medhrk@gmail.com',√≠dhrk@rediffmail.com],

Copying with Pyperclip

Pyperclip is a python module for copying and pasting clipboard content. pyperclip.copy() and pyperclip.paste() functions are the main functions of the modules and works in the same manner as the name implied. Peruse the below code and try to grasp what the code will do -

import pyperclip

while True:
    fh=open('allcopies1.txt','a+')    
    text=str(pyperclip.paste())
    if text not in str(fh.read()):
        fh.write(text)
        fh.write("\n\r\n")
    else:
        print "Already Copied"
        fh.close()
        break
fh=open('allcopies1.txt','r')
for word in fh:
    print word


This program is useful when you need to have a file for storing all the copied content. Make sure the file has a 777 permission. After opening the file we check if the content of the clipboard copied previously? If not then it adds the clipboard content to the file.
A small but useful tool for big future programs. Can you name me instances when it can be used.

ref: …

Web Scraping with Python

The main modules which are needed for web related operations are urllib, urlopen, requests, selenium. Other than this four there are other main and supporting modules like beautifulsoup, webbrowser are there. so, let's start with urllib  -

Follow the below code closely -

import urllib
ts=urllib.urlopen("http://pythonbeginner.in")
for textscript in ts:
    print textscript

This code first fetches the whole content of a website and display them line wise. As simple like that. In web scraping, we have to find a given information in a web page. The projects I have got are mostly something like  -  go through the website on a regular basis and update the price of a product accordingly. Or, it can be useful in share market auto trading etc.  Suppose, we have to find how many times the word 'python' is used in the code. Then what will we do? Web scrapers often face problems like this. Let's look at the second code - 
import urllib,re ts=urllib.urlopen("http://python…

Masking Columns in a database

This simple code was one of my project in fiverr.com, a project worth $20. In this code we have to select a database, find certain values in a column according to id and then replace the value by 'x' or numbers by 'y', so that it will be safe. The other part of the code is to keep the original data in a backup file so that we get the data when needed. Look at the code , and see the comments for better understanding of the code -
See below is the program named databasemask.py , a program which is responsible for masking and backing up the data which will be replaced. Here, in this particular problem we have the database with tables album,customer and invoice , so we declare three dictionaries to hold their values. Lets divulge the secret of the code with comments now -


##As Described above they are for the tables in the database
album = {}
customer = {}
invoice = {}

class Cipherise(): 

"""This class  is for replacing characters with 'x' and numbers with…

Cyberoam Firewall - How to block sites and url

The procedure to block unwanted websites/ip address and ports by a cyberoam firewall is as follows -




First login and then go to objects > hosts . Add a blockIPList as I have done in the above picture. Click ok after adding all the IPs you want to block. In the same way go the object > services . Add the ports you want to block. As I have created a blocked ports.
Then go to Firewall > Rule. Under the LAN to WAN policy create a new rule. As the picture above Enter the services and hosts as previously created.Now  if you want to simply block a website from your network , do the following steps -

Go to web filter > category. Create a category by clicking add category and then adding the websites you want to block.Next add the category to your web policy and block connection from those sites.