Sunday, 27 December 2020

Top 25 Python Trick for String

 Hi Guys !!! Hope all is well

I am going to list down some famous Python trick for dealing with String.

Below is the example code(written in VS code IDE). You can also check my github page

https://github.com/Saurabh-12/Python_Learning

# All these examples are using Python 3

# 1. Is a Substring in a String?
def sub_stringCheck(haystack: str="", needle:str="") -> bool:
return needle in haystack

assest1 = sub_stringCheck("the quick brown fox jumped over the lazy dog", "lazy") #== True
print(assest1)
assest2 = sub_stringCheck("the quick brown fox jumped over the lazy dog", "lazys") #== False
print(assest2)

# 2. Reverse a String
# Use a slice with a decreasing step to return the reversed string.
def string_reverse(forward: str = "") -> str:
return forward[::-1]

print("hello",string_reverse("hello"))
print("goodbye", string_reverse("goodbye"))

# 3. Compare Two Strings for Equality
# Compare equality using == to see if two objects have an equal value.
# Compare identity using is to see if two objects are one and the same.
def are_equal(first_comparator: str = "", second_comparator: str = "") -> bool:
return first_comparator == second_comparator

print(are_equal("thing one", "thing two")) #False
print(are_equal("a thing", "a " + "thing")) # True

# 4. Lowercase, Uppercase, Sentence Case and Title Case of a String
# Python has a number of in-built functions you can use to change the case of a string.

def to_uppercase(input_string:str) -> str:
return input_string.upper()

def to_lowercase(input_string:str) -> str:
return input_string.lower()

def to_sentencecase(input_string:str) -> str:
return input_string.capitalize()

def to_titlecase(input_string:str) -> str:
return input_string.title()

def to_swapcase(input_string:str) -> str:
return input_string.swapcase()

print("THE END OF TIME ", to_uppercase("the end of time"))
print("the end of time ", to_lowercase("The End Of Time"))
print("The end of time ", to_sentencecase("The End of Time"))
print( "The End Of Time ", to_titlecase("the end of time"))
print("tHE eND oF tIME ", to_swapcase("The End Of Time"))

# 5. Concatenate Strings Efficiently
# Use join on an empty string to concatenate the parameters
def concateString(*args) -> str:
return "".join(args)

print("a b c : ", concateString("a", "b", "c"));

# 6. Is the String Empty or None?
def is_Null_Or_Empty(input_string : str = "") ->bool:
if input_string:
if input_string.strip():
return False
return True

print(is_Null_Or_Empty(None)) #True
print(is_Null_Or_Empty("")) #True
print(is_Null_Or_Empty(" ")) #True
print(is_Null_Or_Empty("D")) #False
print(is_Null_Or_Empty("None")) #False

# 7. Trim Leading and Trailing Whitespace
def strip_it(input_string: str) -> tuple:
return (input_string.lstrip(), input_string.rstrip(), input_string.strip())

left, right, full = strip_it(" A padded string ")
print(left)
print(right)
print(full )

# 8. Generate a String of Random Characters
# Use the secrets module to make random choices of characters to add to a string
import string
import secrets

def generate_random_string(length: int = 0) -> str:
result = "".join(
secrets.choice(string.ascii_letters + string.digits)
for _ in range(length))
return result

print(generate_random_string(20))

# 9. Read the Lines in a File to a List
# The file reader object f is being converted to a list implicitly here.
def file_to_list(filename: str = "") -> list:
with open(filename, "r") as f:
lines = list(f)
return lines
print(file_to_list("workData.txt"))

# 10. Find the Substring Between Two Markers
import re

def between(first: str = "", second: str = "", input_string="") -> str:
m = re.search(f"{first}(.+?){second}", input_string)
if m:
return m.group(1)
else:
return ""
print(between(input_string="adCCCTHETEXTZZZdfhewihu",
first="CCC",
second="ZZZ"))
# 11. Remove all Punctuation from a String
import string

def remove_punctuation(input_string: str = "") -> str:
return input_string.translate(str.maketrans("", "", string.punctuation))

print(remove_punctuation("Hello!"))
print(remove_punctuation("He. Saw! Me?"))

# 12. Convert Between CSV and List

def from_csv_line(line: str = "") -> list:
return line.split(",")
print(from_csv_line("a,b,c"))
# 13. take a list and return a CSV line
def from_list(line: list = []) -> str:
ret = ", ".join(e for e in line)
return ret

print(from_list(["a", "b", "c"]) )

# 14. Weave Two Strings
# Use zip_longest from the itertools module to zip two strings of unequal length
import itertools

def interleave(left: str = "", right: str = "") -> str:
return "".join([i + j for i, j in itertools.zip_longest(left, right, fillvalue="")])
print(interleave("ABCD", "01"))

# 15. Remove Unwanted Characters from a String
# Use the replace function. Remember: We can’t change the value of a string in-place — strings are immutable.
def remove_unwanted(original: str = "",
unwanted: str = "",
replacement: str = "") -> str:
return original.replace(unwanted, replacement)

print(remove_unwanted(original="M'The Real String'", unwanted="M") )

# 16. Find the Index Locations of a Character in a String
def find_char_locations(original: str = "", character: str = "") -> list:
return [index for index, char in enumerate(original) if char == character]

print(find_char_locations("The jolly green giant.", "e"))

# 17. Translate a String to Leetspeak
def to_leetspeak(normal_speak:str="") -> str:
leet_mapping = str.maketrans("iseoau", "1530^Ü")
return normal_speak.translate(leet_mapping).title().swapcase()

print(to_leetspeak("the quick brown fox jumped over the lazy dogs"))

# 18. Use Base64 Encoding on Strings
# Base64 is a method to encode binary data as a string for transmitting in text messages.
import base64

def encode_b64(input_string: str = "") -> object:
return base64.b64encode(input_string.encode("utf-8"))


def decode_b64(input_string: str = "") -> object:
return base64.b64decode(input_string).decode("utf-8")

print(encode_b64("Saurabh"))
print(decode_b64(b"U2F1cmFiaA=="))

# 19. Encode and Decode UTF-8 URLs
"""
UTF-8 allows us to use extended, double-word characters — such as emojis. T
hese need to be encoded before they can be used in a URL
"""
import urllib.parse

def encode_url(url: str = "") -> str:
return urllib.parse.quote(url)


def decode_url(url: str = "") -> str:
return urllib.parse.unquote(url)

print(encode_url("https://saurabhsharma123k.blogspot.com/?title=❤❤❤"))
print(decode_url("https%3A//saurabhsharma123k.blogspot.com/%3Ftitle%3D%E2%9D%A4%E2%9D%A4%E2%9D%A4"))

# 20. Splitting Strings
strings = "Saurabh Sharma Blog have nice articles"
print(strings.split()) # return whitespace seprated list of string"

# 21. Checking for Anagrams
from collections import Counter
def is_anagram(s1, s2):
return Counter(s1) == Counter(s2)
s1 = 'listen'
s2 = 'silent'
s3 = 'runner'
s4 = 'neuron'
print('\'listen\' is an anagram of \'silent\' -> {}'.format(is_anagram(s1, s2)))
print('\'runner\' is an anagram of \'neuron\' -> {}'.format(is_anagram(s3, s4)))

# 22. Checking for Palindromes
def is_palindrome(s):
reverse = s[::-1]
if (s == reverse):
return True
return False

s1 = 'racecar'
s2 = 'hippopotamus'

print('\'racecar\' a palindrome -> {}'.format(is_palindrome(s1)))
print('\'hippopotamus\' a palindrome -> {}'.format(is_palindrome(s2)))

#23. Find in String
var="Saurabh Kumar Sharma"
str="Sha"
print (var.find(str))
#24. Count : Returns the number of occurrences of substring ‘str’ in the String.
var='This is a good example'
str='is'
print(var.count(str))

# 25. Python replacing strings
a = "I saw a wolf in the forest. A lonely wolf."

b = a.replace("wolf", "fox")
print(b)

c = a.replace("wolf", "fox", 1)
print(c)


Thanks
Saurabh 
Happy Coding !!!

Monday, 21 December 2020

Some famous Python one liner code

  Hi Guys !!! Hope all is well

I am going to list down some famous Python one liner code example.

1. Swap two variables
a = 1b = 2
ab = ba
print(a,b#>> 2 1

2. Multiple variable assignment
Here you can use it to assign list elements to the given variables, which is also called unpacking. The * will do packing the remaining values again, which results in a sublist for c.
ab, *c = [1,2,3,4,5]
print(a,b,c#>> 1 2 [3, 4, 5]

3. Sum over every second element of a list
a = [1,2,3,4,5,6]
s = sum(a[1::2])
print(s#>> 12

4. Delete multiple elements
slicing syntax can also be used to delete multiple list elements at once
a = [1,2,3,4,5]
del a[::2]
print(a#>> [2, 4]

5. Read file into array of lines
c = [line.strip() for line in open('file.txt')]
print(c#>> ['sks1', 'sks2', 'sks3', 'sks4']

6. Write string to file
with open('file.txt''a'as ff.write('hello world')
print(list(open('file.txt'))) #['sks1\n', 'sks2\n', 'sks3\n', 'sks4\n', 'hello world!']

7. List creation
# List creation 
list_1 = [('Hi 'yfor y in ['sks''mks','pks']]
print(list_1#>> ['Hi sks', 'Hi mks', 'Hi pks']

8. List mapping
l = list(map(int, ['1''2''3']))
print(l#>> [1, 2, 3]
You can also use Pythons map() function to cast every list element to another type.

9. Set creation
squares = { x**2 for x in range(6if x < 4 }
print(squares#>> {0, 1, 4, 9}

10. Palindrome check
phrase = 'deleveled'
isPalindrome = phrase == phrase[::-1]
print(isPalindrome#>> true

11. Sum of Even Numbers In a List
a = [1,2,3,4,5,6]
s = sum([num for num in a if num%2 == 0])
print(s)

12. Creating Lists
lst = [i for i in range(0,10)]
print(lst#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# or 
lst = list(range(0,10))
print(lst)

13. Mapping Lists or TypeCasting Whole List
print(list(map(int,['1','2','3']))) #[1, 2, 3]
print(list(map(float,[1,2,3]))) # [1.0, 2.0, 3.0]
print([float(ifor i in [1,2,3]] )# [1.0, 2.0, 3.0]

13. Printing Patterns
n = 5
print('\n'.join('😀' * i for i in range(1n + 1)))

14. Prime Number
print(list(filter(lambda x:all(x % y != 0 for y in range(2x)), range(213))))

15. Find Max Number
findmax = lambda x,yx if x > y else y 
print(findmax(5,14))


Thanks
Saurabh 
Happy Coding !!!

Wednesday, 16 December 2020

Five Handy Tools for Android Development

 Hi Guys !!! Hope all is well

I am going to list down five very handy tools to use in Android development.

  1. scrcpy
  2. uiautomatorviewer
  3. Charles Proxy
  4. Stetho
  5. Source Tree

Scrcpy

https://saurabhsharma123k.blogspot.com/2020/05/vysor-alternative-app-scrcpy.html

This easy-to-install, lightweight and speedy application uses your Android device’s already established USB connection to mirror its screen on your desktop.
  • open source
  • completely ad-free
  • does not require any root access
  • Interacting with real devices gives an emulator-like experience 
  • The image quality has a high frame rate and is very crispy
uiautomatorviewer 
This tool lets you take UI XML snapshots of what you are currently viewing on your device. 
This is of course an alternative to Android Studio’s built-in Layout Inspector, but I have personally found this tool to be faster, simpler, and more reliable.

 To access the tool, navigate to
\Android\Sdk\tools\bin
Run the uiautomatorviewer binary and tap on this icon:
Image for post
If you have an Android device connected via USB, the tool will take an XML snapshot of the current view and provide you with a view element tree

Charles Proxy
https://www.charlesproxy.com/
What is this? I’ll let its website explain it:
Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

If your app interacts with a REST API, you can debug each of your outgoing requests and incoming responses.

 Charles will snoop your app’s network communication and output every detail of your request including the URL, method, headers, or request body as well as the raw JSON data returned from the server. 

This is the single source of truth of your app’s network communication and it makes network debugging a breeze.'

 It’s also a great way to prove to your back-end developer that a bug is their fault by sending them the a raw curl command of your network request 😏:

Stetho
Stetho is an Android debugging tool created by Facebook. 
It is a free open-source platform that allows access to a Chrome Developer Tools feature native to the desktop browser.
Stetho features a network inspection function for image preview, JSON response helpers, and exporting traces to the HAR format.

Source Tree
SourceTree is a free, open-source tool that allows you to manage Git repositories through its simple Git GUI. 
See all of your changes and branches clearly without having to write a single command line. 
SourceTree also allows you to stage and discard changes by the file, hunk, or line.

If you are working on an Android app, be sure to try out these tools to make your life easier!

Thanks
Saurabh 
Happy Coding !!!

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...