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 !!!

Friday, 30 October 2020

Use Git like Pro : Collection of all widely used command

Hi Guys !!! Hope all is well

Git Status

git status

git status -- short


Manipulate the Changes

git add file_name  >> adds the file file to the stage section

git restore file_name >> discards changes to the file

git restore --staged file_name >> removes the file from the stage section


Inspecting the diffs

git diff . >> displays the not-staged changes in your working tree

git diff --staged >> displays the staged changes

git diff dev >> displays changes between the working tree and the dev branch.

You might use a commit hash or tag instead.

git diff master..dev >>displays changes between the branches master and dev


Committing

git commit -m 'Commit message'

git config --global core.editor your-editor-executable-path


git commit --amend

Using git commit --amend you can either change the last commit message or

you can add an additional change to the last commit. If you want to push your changes,

though, you have to use git push -f in either case


Switch

The switch command can be used to switch between branches.

git switch branch-name >> switches to a branch-name branch

git switch -b abc >> creates branch abc and switches to it

git switch - >> switches you to the previous branch


Checkout

git checkout [branch_name] >> works as a switch but can also move HEAD to any commit/tag as well.

So, when switching to the previous branch you just need to write 

git checkout - 

 Switching back and forth different branches means, you only have to write

 git checkout -

Branches

git branch >>> returns a list of the local branches.

Use -r to list only remote branches or -a to get them all

git branch abc >>> creates abc branch

git branch -d abc >>> deletes abc if already merged.

If not, use -D to force deletion.

Log Results

git log >>> to see the commits’ history.

git log -p >>>Display the changes alongside the commit description:

git log -2 >>> display two recent commits

git log branch-name  >>>Display log for a specific branch/revision:

Filter log for a specific file(s) only (glob pattern applies here):

git log *.js # or git log branch-name:*.js

Filter commits by the author (accepts partial name):

git log --author saurabh

Filter by date:

git log --since 2019-10-01

Filter by date using dynamic date ranges (days, weeks, months, years):

git log --since 2months --until 1week

Forgot to add a file to that last commit

git add missed-file.txt

git commit --amend

Added a wrong file in the repo

git reset /assets/img/misty-and-pepper.jpg

If you have gone as far as committing that change, no need to worry.

You just need to run an extra step before:

git reset --soft HEAD~1

git reset /assets/img/misty-and-pepper.jpg

rm /assets/img/misty-and-pepper.jpg

git commit

Git's magical time-traveling

git reflog

Spelling mistake on branch name

git branch -m feature-brunch feature-branch

If you have already pushed this branch, there are a couple of extra steps required.

We need to delete the old branch from the remote and push up the new one:

git push origin --delete feature-brunch

git push origin feature-branch

Git Merge

Merging is a common practice for developers using version control systems.

Whether branches are created for testing, bug fixes, or other reasons, merging commits changes to another location.

To be more specific, merging takes the contents of a source branch and integrates them with a target branch.

In this process, only the target branch is changed. The source branch history remains the same.

Merge the master branch into the feature branch using the checkout and merge commands.

$ git checkout feature

$ git merge master

(or)

$ git merge master feature

This will create a new “Merge commit” in the feature branch that holds the history of both branches.

Git Rebase

  • Rebase is another way to integrate changes from one branch to another

  • Rebase compresses all the changes into a single “patch.” 

  • Then it integrates the patch onto the target branch

Unlike merging, rebasing flattens the history because it transfers the completed work from one branch

to another. In the process, unwanted history is eliminated.

Rebase the feature branch onto the master branch using the following commands.

$ git checkout feature

$ git rebase master

This moves the entire feature branch on top of the master branch. It does this by re-writing the project

history by creating brand new commits for each commit in the original (feature) branch.

Interactive Rebasing

This allows altering the commits as they are moved to the new branch.

This is more powerful than automated rebase, as it offers complete control over the branch’s commit history.

Typically this is used to clean up a messy history before merging a feature branch into master.

$ git checkout feature

$ git rebase -i master

This will open the editor by listing all the commits that are about to be moved.

pick 22d6d7c Commit message#1

pick 44e8a9b Commit message#2

pick 79f1d2h Commit message#3

This defines exactly what the branch will look like after the rebase is performed.

By re-ordering the entities, you can make the history look like whatever you want.

For example, you can use commands like fixup, squash, edit etc, in place of pick.

Graph OPTION

git log --online --graph

 git log --online --graph -5 // SHOW only 5 most recent commits


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...