Fail Fast & Self Healing Using Circuit Breaker

What is Circuit Breaker?

Circuit Breaker is a pattern to monitor the failures and it keeps the count of failure, after reaching the threshold of failure. it stops sending requests to the external server till timeout.

State of the Circuit Breaker

Circuit Breaker has three states:

Closed: It is a normal state. Every request going through the services.

Open: When shit started, If External server is started to failing the requests then the circuit breaker comes in open state once the failure threshold reached. No requests go to the external services. Simply fail fast.

Half-Open: After the timeout, the Circuit breaker went to the half-open state, now requests go to the services and if any requests failed then still state moved to open state otherwise reset to the closed state. Simply automatic healing. 

How it benefits?

It prevents cascading failures and keeps the system responsive.

  • We can set a default response until Circuit Breaker is in open state.
  • Other functionality & API should work.
  • If we know the other system is down then no need to send requests & wait for a response.
  • Automatically check the system status in the half-open state.

Implementations:

"""
Circuit Breaker Imnplementation.
"""
from datetime import datetime
# constants
CLOSED = 0
OPEN = 1
HALF_OPEN = 2
DEFAULT_THRESHOLD = 5 # failure count threshhold
DEFAULT_TIMEOUT = 60 # threshhold timeout in seconds
class FailureException(Exception):
pass
class CircuitBreakerOpen(Exception):
pass
class CircuitBreaker:
def __init__(self, *args, **kwargs):
self.state = CLOSED
self.threshold = kwargs.get('threshold', DEFAULT_THRESHOLD)
self.timeout = kwargs.get('timeout', DEFAULT_TIMEOUT)
self.failures = 0
self.last_failed = None
def _set_state(self):
if self.failures > self.threshold:
timeout = datetime.now() self.last_failed
if timeout.total_seconds() > self.timeout:
self.state = HALF_OPEN
else:
self.state = OPEN
else:
self.state = CLOSED
def _reset_state(self):
self.failures = 0
self.last_failed = None
self.state = CLOSED
def _set_failures(self):
self.failures += 1
self.last_failed = datetime.now()
def run(self, callable):
self._set_state()
if self.state in (CLOSED, HALF_OPEN) :
try:
return callable()
except Exception as e:
self._set_failures()
raise FailureException("Failure!")
else:
self._reset_state()
elif self.state == OPEN:
raise CircuitBreakerOpen("Circuit Open!")
view raw circuit-breaker.py hosted with ❤ by GitHub
https://gist.github.com/logsvikas/ca9182d816437e5488bc62803758686f

Further Reading:

  1. Martin Flower blog: https://martinfowler.com/bliki/CircuitBreaker.html
  2. Netflix blog: https://medium.com/netflix-techblog/making-the-netflix-api-more-resilient-a8ec62159c2d
  3. Netflix Open Source Hystrix: https://github.com/Netflix/Hystrix/

Easily, Delete your tweets from your Twitter account using python

If you want to delete your tweets from your twitter account then it is very easy to do using python.

TL;DR

Please follow these steps to delete your twitter’s tweet status:

Steps:

1: Install tweepy python library either using pip or conda python package manager.

2. Get your Consumer API key and Consumer API secret key from your twitter app.

3. Get your API access token & API secret token from your twitter app.

Python code:

import tweepy
CONSUMER_API_KEY = "xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx"
CONSUMER_API_SECRET = "xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx"
ACCESS_TOKEN ="xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx"
ACCESS_TOKEN_SECRET = "xxxxxxxx-xxxxxxxx-xxxxxxxx"
TWEET_LIMIT = 50
def oauth_token():
auth = tweepy.OAuthHandler(CONSUMER_API_KEY, CONSUMER_API_SECRET)
# auth_url = auth.get_authorization_url()
# verify_code = input("Authenticate at %s and then enter you verification code here > " % auth_url)
# auth.get_access_token(verify_code)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
return tweepy.API(auth)
def delete_tweets(tweet_limit=None):
print("Deleting tweets for user: {}".format(api.verify_credentials().screen_name))
delete_limit = tweet_limit or TWEET_LIMIT
count = 1
for status in tweepy.Cursor(api.user_timeline).items(delete_limit):
try:
api.destroy_status(status.id)
print("{}: Deleted status: {}".format(count, status.id))
count += 1
except Exception as e:
print(e)
if __name__ == "__main__":
print("Delete Tweets Function called!")
api = oauth_token()
delete_tweets(1000)

In-Place QuickSort

Challenge
Create an in-place version of Quicksort. You need to follow Lomuto Partitioning method.

Guideline
Instead of copying the array into multiple sub-arrays, use indices to keep track of the different sub-arrays. You can pass the indices to a modified partition method. The partition method should partition the sub-array and then return the index location where the pivot gets placed, so you can then call partition on each side of the pivot.

Always select the last element in the ‘sub-array’ as a pivot.
Partition the left side and then the right side of the sub-array.
Print out the whole array at the end of every partitioning method.
An array of length 11 or less will be considered sorted, and there is no need to sort or to print them.
Since you cannot just create new sub-arrays for the elements, partition method will need to use another trick to keep track of which elements are greater and which are lower than the pivot.

The In-place Trick

If an element is lower than the pivot, you should swap it with a larger element on the left-side of the sub-array.
Greater elements should remain where they are.
At the end of the partitioning method, the pivot should be swapped with the first element of the right partition, consisting of all larger elements, of the sub-array.
To ensure that you don’t swap a small element with another small element, use an index to keep track of the small elements that have already been swapped into their “place”.
Lomuto-partitioning

Input Format
There will be two lines of input:

nn – the size of the array
arar – the nn numbers of the array
Output Format
Print the entire array on a new line at the end of every partitioning method.

Constraints
1≤n≤50001≤n≤5000
−10000≤x≤10000,x∈ar−10000≤x≤10000,x∈ar
There are no duplicate numbers.

Sample Input

7
1 3 9 8 2 7 5
Sample Output

1 3 2 5 9 7 8
1 2 3 5 9 7 8
1 2 3 5 7 8 9
Explanation
5 is initally selected as the pivot, and the array is partitioned as shown in the diagram. The left side is partitioned next with 2 as the pivot. Finally, the right side is partitioned with 8 as the pivot. The entire array is now sorted.

quick-sort-partition

N = int(raw_input().strip())
ar = map(int, raw_input().strip().split())
def quicksort(ar, l, h):
if l < h:
pi = partition(ar, l, h)
quicksort(ar,l,pi-1)
quicksort(ar,pi+1, h)
def partition(ar, l, h):
p = ar[h]
i = l - 1
for j in range(l,h):
if ar[j] <= p:
i = i + 1
ar[i], ar[j] = ar[j], ar[i]
ar[i+1], ar[h] = ar[h], ar[i+1]
print " ".join(map(str, ar))
return (i+1)
quicksort(ar, 0, N-1)
print " ".join(map(str, ar))

Maximum AND

Given two numbers A and B. Find the value of pair (P,Q) such that A <= P < Q <= B value of P AND Q is maximum where AND is a binary operator. Refer to this link for more information about AND operator : http://en.wikipedia.org/wiki/Bitwise_operation#AND

Input:
First line of input contains number of test cases T. Each test case contains two numbers A and B.

Output: For each test case print the value of maximum AND.

Constraints: 
1<=T<=1000
1<= A < B <=1018

Sample Input(Plaintext Link)
 2
2 3
4 8


Sample Output(Plaintext Link)
 2
6

Hackerearth Coding Challenge

#python sollution
T = int(raw_input())

for i in range(T):
	x, y = map(int,raw_input().split(" "))
	if y % 2 == 0:
		if x < ( y - 1 ) :
			y = y - 1
			x = y - 1
	elif y % 2 != 0 and x < y:
		x = y - 1
	print x & y

Time Conversion

Problem Statement

Given a time in AM/PM format, convert it to military (24-hour) time.

Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.

Input Format

A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12.

Output Format

Convert and print the given time in 24-hour format, where 00≤hh≤23.

Sample Input

07:05:45PM
Sample Output

19:05:45
Explanation

7 PM is after noon, so you need to add 12 hours to it during conversion. 12 + 7 = 19. Minutes and seconds do not change in 12-24 hour time conversions, so the answer is 19:05:45.

Copyright © 2015 HackerRank.
All Rights Reserved

#python

hh, mm, ss = raw_input().split(":")
h = int(hh)
T = ss[2:]
if T == 'PM' and h < 12:
    print str(12 + h) + ":" + mm + ":"+ss[0:2]
elif T == 'AM' and h == 12:
    print '00'+":"+mm+":"+ss[0:2]
else:
    print hh+":"+mm+":"+ss[0:2]

Diagonal Difference

Problem Statement

Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals.

Input Format

The first line contains a single integer, N. The next N lines denote the matrix’s rows, with each line containing N space-separated integers describing the columns.

Output Format

Print the absolute difference between the two sums of the matrix’s diagonals as a single integer.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15
Explanation

The primary diagonal is:

11
    5
        -12

Sum across the primary diagonal: 11 + 5 – 12 = 4

The secondary diagonal is:

        4
    5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 – 19| = 15

Copyright © 2015 HackerRank.
All Rights Reserved

#Python solution
N = int(raw_input())
sum1 = 0
sum2 = 0
for i in range(N):
    list1 = map(int, raw_input().split(" "))
    sum1 = sum1 + list1[i]
    sum2 = sum2 + list1[N-(i+1)]
print abs(sum1-sum2)

Save Quantumland

Problem Statement

In Quantumland, there are n cities numbered from 1 to n. Here, ci denotes the ith city. There are n−1 roads in Quantumland. Here, ci and ci+1 have a bidirectional road between them for each i<n.

There is a rumor that Flatland is going to attack Quantumland, and the queen wants to keep her land safe. The road between ci and ci+1 is safe if there is a guard in ci or ci+1.

The queen has already placed a few guards in some of the cities, but she is not sure if they are enough to keep the roads safe. She wants to know the minimum number of new guards she needs to hire.

Input Format

The first line will contain an integer t: denoting the number of testcases.

For each testcase, there will be 2 lines.

The first line will contain an integer n.
In the next line, there will be n integers b1,b2…bn.

If bi=1, that means there is a guard in city ci.
If bi=0, that means there are no guards in city ci.

Constraints

1<=t<=1000
1<=n<=100
Output Format

Print the minimum number of new guards that need to be hired to make Quantumland safe.

Sample Input

2
5
1 1 0 1 0
5
0 0 1 0 0
Sample Output 1

0
2
The following figure represents the first testcase. The cities with guards are marked in blue.

cover(1).png

All the roads are safe. No more guards are needed. The output is 0.

The next figure represents the second testcase. The old guards are marked in blue, and the new guards are marked in yellow.

cover3.png

Note: There can be more than one way to make Quantumland safe using the minimum number of new guards. In the second testcase, we could also place new guards in city 1 and city 4 instead of city 2 and city 4.
Contest On Hackerrank

#Sollution

import sys

t = int(raw_input().strip())
for a0 in xrange(t):
    n = int(raw_input().strip())
    count  = 0
    a = map(int,raw_input().strip().split(' '))
    for i in range(len(a) - 1 ) :
        if a[i] != 1 and a[i+1] != 1:
            a[i+1] = 1
            count = count + 1
    print count

Emma’s Notebook

Problem Statement

Emma is writing bits (1s and 0s) in her notebook. Every second, she writes more bits.

In the 1st second, she writes two bits in her notebook. She starts with 0 and alternates between 0 and 1. They look like this:

0 1
In the 2nd second, she writes three more bits in her notebook. This time, she starts with 1 and keeps alternating between 0 and 1. Now, they look like this:

0 1
1 0 1
After 6 seconds, her notebook looks like this:

0 1
1 0 1
0 1 0 1
1 0 1 0 1
0 1 0 1 0 1
1 0 1 0 1 0 1
If you count carefully, you can see that Emma wrote 15 1’s in her notebook after 6 seconds. She wants to know how many 1’s she can write in t seconds.

Input Format

Input contains just one integer: t.

Constraints

1<=t<=105
Output Format

Print the number of 1’s Emma can write in t seconds.

Sample Input 1

3
Sample Output 1

5
Explanation 1 Add one more row to the example of the 2nd second above and then you will see five 1’s in total.

Sample Input 2

6
Sample Output 2

15
Explanation 2 See the example after 6 seconds above.
Contest on Hackerrank.

#Sollution

import sys

t = int(raw_input().strip())
a = t/2
if t%2 :
    sum1 = ((a+1)*(a+2))/2
else :
    sum1 = (a*(a+1))/2
sum2 = ((a+1)*(a+2))/2 -1
print sum1 + sum2

Calendar Module

Problem Statement

Calendar Module

Calendar module allows you to output calendars and provides additional useful functions related to the calendar.

class calendar.TextCalendar([firstweekday])

This class can be used to generate plain text calendars.

Sample Code

>>> import calendar
>>> 
>>> print calendar.TextCalendar(firstweekday=6).formatyear(2015)
                                  2015

      January                   February                   March
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
             1  2  3       1  2  3  4  5  6  7       1  2  3  4  5  6  7
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       8  9 10 11 12 13 14
11 12 13 14 15 16 17      15 16 17 18 19 20 21      15 16 17 18 19 20 21
18 19 20 21 22 23 24      22 23 24 25 26 27 28      22 23 24 25 26 27 28
25 26 27 28 29 30 31                                29 30 31

       April                      May                       June
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
          1  2  3  4                      1  2          1  2  3  4  5  6
 5  6  7  8  9 10 11       3  4  5  6  7  8  9       7  8  9 10 11 12 13
12 13 14 15 16 17 18      10 11 12 13 14 15 16      14 15 16 17 18 19 20
19 20 21 22 23 24 25      17 18 19 20 21 22 23      21 22 23 24 25 26 27
26 27 28 29 30            24 25 26 27 28 29 30      28 29 30
                          31

        July                     August                  September
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
          1  2  3  4                         1             1  2  3  4  5
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       6  7  8  9 10 11 12
12 13 14 15 16 17 18       9 10 11 12 13 14 15      13 14 15 16 17 18 19
19 20 21 22 23 24 25      16 17 18 19 20 21 22      20 21 22 23 24 25 26
26 27 28 29 30 31         23 24 25 26 27 28 29      27 28 29 30
                          30 31

      October                   November                  December
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
             1  2  3       1  2  3  4  5  6  7             1  2  3  4  5
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       6  7  8  9 10 11 12
11 12 13 14 15 16 17      15 16 17 18 19 20 21      13 14 15 16 17 18 19
18 19 20 21 22 23 24      22 23 24 25 26 27 28      20 21 22 23 24 25 26
25 26 27 28 29 30 31      29 30                     27 28 29 30 31

To learn more about different calendar functions click here.

Task

You are given the date of the day. Your task is to find what day it is on that date.

Input Format

Single line containing space separated month, day and year in MM DD YYYY format.

Constraints

2000<year<3000
Output Format

Output the correct day in capital letters.

Sample Input

08 05 2015
Sample Output

WEDNESDAY
Explanation

Day on 5th August 2015 is WEDNESDAY

Copyright © 2015 HackerRank.
All Rights Reserved

import datetime 
date_time = raw_input()
print datetime.datetime.strptime(date_time,"%m %d %Y").strftime('%A').upper()

Sherlock and Divisors

#codeifyoucansolve
Watson gives an integer N to Sherlock and asks him: What is the number of divisors of N that are divisible by 2?.

Input Format
First line contains T, the number of testcases. This is followed by T lines each containing an integer N.

Output Format
For each testcase, print the required answer in one line.

Constraints
1≤T≤100
1≤N≤109

Sample Input

2
9
8

Sample Output

0
3

Explanation
9 has three divisors 1, 3 and 9 none of which is divisible by 2.
8 has four divisors 1,2,4 and 8, out of which three are divisible by 2.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        try
            {
        //DataInputStream in = new DataInputStream(System.in);
            Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while(T>0)
            {
            int N = sc.nextInt();
                
            if(N%2 == 1)
                {
                 System.out.println('0');               
            }
            else
                {
                int count=0;
                int i=1;
                int t =(int) Math.sqrt(N);
                while(i<=t)
                    {
                    if(N%i == 0)
                    {
                        if(i%2 == 0)
                           count += 1;
                        int k = N/i;
                        if((k!=i) && (k%2 == 0))
                           count += 1;
                    }
                        i=i+1;                    
                }
                System.out.println(count);
              }
            }
            T = T - 1;
        }
        catch(Exception e)
            {}
    }
}

Compile : http://ideone.com/5jTOAL
Folow on Twiter : https://twitter.com/codeifucansolve