Tuesday, January 30, 2018

How To: Schedule Cron Job in Ubuntu

Open a Terminal Window (Command Line) in ubuntu.
Type following command and press Enter.


 crontab -e


This will open editor for you. Write cron command at the end of file.

Use sudo if root privileges required. e.g


 sudo crontab -e


Use following pattern to create new cron job syntax:
  1. The number of minutes after the hour (0 to 59) 
  2. The hour in military time (24 hour) format (0 to 23) 
  3. The day of the month (1 to 31) 
  4. The month (1 to 12) 
  5. The day of the week (0 or 7 is Sun, or use name) 
  6. The command to run 

For example


 0 7 * * * /path/to/your/script.sh


This syntax will run script.sh at 7:00 AM daily.

File must have executable permissions. Run following command to make file executable.


  chmod +x /path/to/your/script.sh


If you want to schedule python file to run via cron, use following command instead.


  0 7 * * * /usr/bin/python3 /path/to/your/pythron-file.py


Just make sure you have already installed python3.

To list existing cron jobs enter following command:


 crontab -l


To remove an existing cron job enter following command:


 crontab -e


Delete the line that contains your cron job and save file.

Wednesday, June 28, 2017

How To: Create Thumbnail Image From Base64 Encoded String using Python 3

In this tutorial we 'll create thumbnail image from base64 encoded string received from client/user using python 3.
Our purpose is to create a thumbnail image for each image saved by client/user so that we can send back thumbnail images instead large size images while sending bulk data over the internet.

We are receiving image in form of base64 encoded string, We 'll apply following steps on it for complete result.

1). Decode string using base64 technique.
2). Create temporary image from decoded string.
3). Create thumbnail from this temporary image.
4). Encode thumbnail using base64 technique, so that we can save thumbnail as well in our database.
5). Remove both newly created temporary image and its thumbnail after saving to database.

1). Decode string using base64 technique.

# UserImage holds base64 encoded string. 
TmpUserImage = UserImage.replace("data:image/jpeg;base64,", "") 
ImgDataDecoded = base64.b64decode(TmpUserImage)

2). Create temporary image from decoded string.

# Using uuid for unique file name.
TmpUUID = str(uuid.uuid4()) 
# File name
FileName = TmpUUID + '_image.jpeg' 
# Thumbnail name
FileNameThumb = TmpUUID + '_image_80x80.jpeg' 
# Writing to file.
with open(FileName, 'wb') as f: 
   f.write(ImgDataDecoded)

3). Create thumbnail from this temporary image.

image = Image.open(FileName) 
size = (80, 80) 
thumb = ImageOps.fit(image, size, Image.ANTIALIAS) 
thumb.save(FileNameThumb)

4). Encode thumbnail using base64 technique, so that we can save thumbnail as well in our database.

with open(FileNameThumb, "rb") as thmbn: 
    TmpStr = base64.b64encode(thmbn.read()) 
TmpStr = "data:image/jpeg;base64," + str(TmpStr)[2:-1] 
# Encode to utf-8 before saving to database 
# (don't forget to decode after fetching from database).
TmpStr = bytes(TmpStr,"utf-8")
# Now save TmpStr to database.

5). Remove both newly created temporary image and its thumbnail after saving to database.

if os.path.isfile(FileName): 
    os.remove(FileName) 
if os.path.isfile(FileNameThumb): 
    os.remove(FileNameThumb)

Don't forget to include following libraries.

# For Thumbnail 
from PIL import Image, ImageOps 
import base64, uuid, os

This is all, you have done it. Please ask in comment if there is any confusion. Happy Coding -:)

Sunday, May 28, 2017

How To: Set and Get Cursor Position in Textbox using JQuery

In this tutorial, we 'll learn how to set and get cursor position in text box using jquery.
1). Open notepad, and paste following html code in it.

<html>
<head>
 <title>Home</title>
</head>
<body>
 <input id="first_name" type="text" value="webdesignpluscode" />
 <input onclick="SetPosition();" type="button" value="Set Position" />
 <input onclick="GetPosition();" type="button" value="Get Position" />
</body>
</html>

2). Click File then Save As... in notepad menu. Save As dialogue will open
3). Enter "home.html" in File name:
4). Select All Files in Save as type:
5). Click Save. Notepad file will be saved as html page.
6). Now open this html page in edit mode.
7). Add following online JQuery library reference inside <head> tag.

<script src="https://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>

You can download and add to project locally.

8). Now add java script block inside <head> tag and copy following code there.


<script type="text/javascript">

// Set Cursor Position
 $.fn.setCursorPosition = function (position)
{
 this.each(function (index, elem) {
 if (elem.setSelectionRange) {
 elem.setSelectionRange(position, position);
 }
 else if (elem.createTextRange) {
 var range = elem.createTextRange();
 range.collapse(true);
 range.moveEnd('character', position);
 range.moveStart('character', position);
 range.select();
 }
 });
 return this;
 };

 // Get cursor position
 $.fn.getCursorPosition = function ()
{
 var el = $(this).get(0);
 var position = 0;
 if ('selectionStart' in el) {
 position = el.selectionStart;
 }
 else if ('selection' in document) {
 el.focus();
 var Sel = document.selection.createRange();
 var SelLength = document.selection.createRange().text.length;
 Sel.moveStart('character', -el.value.length);
 position = Sel.text.length - SelLength; }
 return position;
 };

 function SetPosition() {
 $("#first_name").setCursorPosition(5);
 $("#first_name").focus();
 }

 function GetPosition() {
 alert($("#first_name").getCursorPosition());
 $("#first_name").focus();
 }
 </script>

Complete code can be downloaded from this git repository.

This is all. You have done. Save file, and view it in any browser.

Sunday, March 26, 2017

Python Part5: Set and exception handling Try except finally

Set

  • Unordered collection of unique, immutable objects. 
  • Literals: 
    • delimited by { and } 
  • Single comma separated items. 
    • >>> p = {1, 2, 3, 4} 
    • >>> p 
    • {1, 2, 3, 4} 
  • Empty { } makes a dict, so for empty set use the set() constructor. 
    • >>> e = set() 
    • >>> e 
    • set()
  • Set() constructor accepts: 
    • Iterable series of values. 
      • >>> s = set([1, 2, 3, 4]) 
      • >>> s 
      • {1, 2, 3, 4} 
  • Duplicates are discarded. 
    • >>> t = [1, 2, 3, 1, 4] 
    • >>> set(t) 
    • {1, 2, 3, 4} 
  • Often used specifically to remove duplicates – not order preserving. 
  • Order is arbitrary. 
    • >>> for x in {1, 2, 4, 8, 32} 
    • print(x)
  • Use in and not in operators. 
    • >>> q = {2, 9, 6, 4} 
    • >>> 3 in q 
    • False 
    • >>> 3 not in q 
    • True 
  • Add(item) inserts a single element. 
    • >>> k = {2, 4} 
    • >>> k 
    • {2, 4} 
    • >>> k.add(8) 
    • >>> k 
    • {2, 4, 8}
  • Duplicates are silently ignored. 
    • >>> k.add(8) 
    • >>> k 
    • {1, 2, 8} 
  • For multiple elements use update(items) passing any iterable series. 
    • >>> k.update([9, 10]) 
    • >>> k 
    • {1, 2, 8, 9, 10} 
  • Remove(item) requires that item is present, otherwise raises KeyError. 
    • >>> k.remove(9) 
    • >>> k 
    • {1, 2, 8, 10}
  • Discard(item) always succeeds. 
    • >>> k.discard(9) 
  • Copy set using S.copy() method. 
    • >>> j = k.copy() 
  • Use constructor. Set(s) 
    • >>> m = set(j) 
  • Copies are shallows. 
  • S1.union(s2) method. 
    • Union is commutative.
  • s.intersection(t) method 
    • Intersection is commutative. 
  • s.difference(t) method. 
    • Difference is non-commutative. 
  • s.symmetric_difference(t) method 
    • Symmetric difference is commutative. 
  • s.issubset(t) method 
  • s.issuperset(t) method. 
  • s.isdisjoint(t)

Handle exceptions. Try … except … finally

  • try: 
    • x = 5 
  • except: 
    • message = str(sys.exc_info()[1]) 
    • x = -1 
  • finally: 
    • # final-block 
    •  x = 0

Python Part4: For loop, argument passing and Tuple

For loop

  • items = [a, b, c, d] 
  • for item in items: 
    •  print(item) 
  •  for i in range(5) 
    •  print(i)

Argument passing

  • Function with arguments.
  • def modify(k) 
    •  k.append(13) 
    •  print(k) 
  • m = [6, 7, 8, 9] 
  • modify(m) 
  • Default arguments.
  • def DisplayMessage(m='nothing') 
    • print(m) 
  • message = 'Welcome to python' 
  • DisplayMessage(Message) 
  • DisplayMessage()

Tuple

  • Heterogeneous immutable collection. 
  • Delimited by parentheses.
    • For example t = ("norway", 4.953, 3) 
  • Items separated by commas.
  • Element access with square brackets and zero-based index. T[index] 
    • >>> t[0] 
    • 'Norway'
  • len(t) for number of elements. 
    • >>> len(t) 
    • 3
  • Iteration with for loop. 
    • for item in t: 
    • print(item) 
      • Norway 
      • 4.953 
  • Concatenation with + operator. 
    • t + (338186.0, 2659) 
    • ('Norway', 4.953, 3, 338186.0, 2659) 
  • Reputation with * operator. 
    • t * 3 
    • ('Norway', 4.953, 3, 'Norway', 4.953, 3, 'Norway', 4.953, 3)
  • Tuple can contain any kind of object. 
  • Nested tuples.
    • A = ((245, 446), (90, 456)) 
  • Chain square-brackets indexing to access inner elements. 
    • A[1][0] 
    • 90 
  • Can’t use one object in parentheses as a single element tuple. 
  • For a single element tuple include a trailing comma. 
    • K = (234, ) 
  • The empty tuple is simply empty parentheses. 
    • E = ()
  • Delimiting parentheses are optional for one or more elements.
    • p = 1, 1, 1, 4, 6, 19 
    • >>> p 
    • (1, 1, 1, 4, 6, 19) 
  • Tuples are useful for multiple return values. 
    • def MinMax(items) 
      • Return Min(items), Max(items) 
    • >>> MinMax([33, 30, 9, 82, 87]) 
    • (9, 87)
  • Tuple unpacking allow us to destructure directly into named references. 
    • lower, upper = MinMax([33, 30, 9, 82, 87]) 
    • >>> lower 
    • >>> upper 
    • 87
  • Tuple unpacking works with arbitrarily nested tuples (although not with other data structure) 
    • (a, (b, (c, d))) = (4, (3, (2, 1))) 
    • >>> a 
    • >>> b 
    • >>> c 
    • >>> d
    •  1 
  • a, b = b, a is the idiomatic python swap.
  • Use the tuple constructor to create tuples from other iterable series of objects. 
    • >>> tuple([234, 444, 897]) 
    • (234, 444, 897) 
    • >>> tuple("car") 
    • ('c', 'a', 'r') 
  • The in and not in operators can be used with tuples - and other collection types – for membership testing. 
    • >>> 5 in (3, 5, 9, 13) 
    • True 
    • >>> 5 not in (3, 5, 9, 13) 
    • False