Friday, February 28, 2020

Regular Expression In JavaScript

Regular Expression In JavaScript

Regex or Regular expression is an arrangement of characters used to match the character combinations in a given string.

OR

In other words, Regular expression is a search pattern that can search for a particular pattern of characters in a given character sequence. One of the major applications of Regex is form validation. For example, if we want to test that the input in a field is a valid email id or not then we can test the input against an appropriate Regex.

Creating the Regular Expression

Regular expressions are also objects. There are two ways to create a regular expression,

Regular Expression Literals
var v='/pattern/modifier'; // i is the modifier
We can enclose the pattern between slashes.


RegExp Constructor

We can also use the constructor function of RegExp object.
var exp=RegExp('pattern');

We should use the constructor function when the expression can change during the execution. A regular expression can contain a single character or a complicated pattern with multiple characters. Regular expressions can be used to perform all types of text search and text to replace operations.

Using search() and replace() functions

The search() method returns the index position of the match if successful, otherwise, it returns -1;
The replace() method replaces some character sequences in the string with some input character sequence.

//Search and replace with normal string inputs
str='Java, Python and C/C++ programming';
pos=str.search('Python');
document.write(pos);

str='Java, Python and C/C++ programming';
pos=str.replace('Python','JavaScript');
document.write(pos);

Output:

6

Java, JavaScript and C/C++ programming


We can also search and replace with RegExp,

//Search and replace with RegExp inputs 
  str='Java, Python and C/C++ programming';
pos=str.search(/python/i);   //i is the modifier
document.write(pos);         //for NOT case-sensitive
document.write('<br>');      //Matching

str='Java, Python and C/C++ programming';
pos=str.replace(/python/i,'JavaScript');
document.write(pos);
Output:

6

Java, JavaScript and C/C++ programming

Modifiers

The Modifiers have the role to affect the way in which search will be performed,

Modifiers and Their Roles

Modifier

Role

i Used for case-insensitive matching
g Used for a global match (find all matches rather than stopping after the first match)
m Used for multiline matching

Expressions and Brackets

To search specific characters in a range we can use brackets(brackets are used to specify the inclusion or exclusion of boundary alphabets or numbers).

Expressions

Role

[abc] searches for any of the characters within the brackets
[0-9] searches for any of the digits in range 0 to 9(0 and 9 inclusive)
(x | y) searches for anyone x or y separated with |

Quantifiers

There are some quantifiers used for identifying the number of occurrences of an alphabet or digit in the character sequence.

Quantifier

Role

n+ Used to match any string that contains at least one n
n* Used to match any string that contains zero or more occurrences of n
n? Used to matches any string that contains zero or one occurrence of n

Methods Used By Regular Expressions

There are many methods that can use regular expressions,

Methods Used By Regular Expressions

Method

Role

exec() This method executes a search for a match in a string. It returns an array of information or null if not matched.
test() This method tests for a match in a string. It returns true or false.
match() This method returns an array containing all of the matches, including capturing groups, or null on a mismatch.
matchAll() This method returns an iterator containing all of the matches.
search() This method tests whether a string is matched or not and returns the index of the match, or -1 otherwise.
replace() This method executes a search for a match in a string and replaces the matched substring with a replacement character sequence.
replace() This method uses a regular expression or a fixed string as the input to split down a string into an array of substrings.

Examples

Thursday, February 27, 2020

Sorting Arrays In JavaScript

Sorting Arrays In JavaScript

Arrays are used to store the data at contiguous index positions to enable random access to the data. Sorting the data stored in an array is required quite often. JavaScript provides sort() function to sort the arrays.
for eaxmple,

  arr=['orange','red','black','blue','pink'];
  arr.sort();
 for(item in arr)
  {
    document.write(arr[item]+'<br>');
  }

The above array will be sorted in alphabetically sorted order.

Output:
black
blue
orange
pink
red


To sort the elements in reverse order in an array of strings we can use the method reverse()

 arr=['orange','red','black','blue','pink'];
 arr.sort();
 arr.reverse();
 for(item in arr)
  {
    document.write(arr[item]+'<br>');
  }

Output:
red
pink
orange
blue
black


Sorting Array of Numbers


We can pass compare function to sort().

  arr=[45,12,10,71,36,25,17];
  arr.sort(function(a,b){
    return a-b;
  });
 for(item in arr)
  {
    document.write(arr[item]+'<br>');
  }

Output:
10
12
17
25
36
45
71


To sort in reverse order, we can just change compare function

  arr=[45,12,10,71,36,25,17];
  arr.sort(function(a,b){
    return b-a;
  });
 for(item in arr)
  {
    document.write(arr[item]+'<br>');
  }

Output:
71
45
36
25
17
12
10


Sorting in Random Order

To sort an array of numbers in random order we can use the random() function.

  arr=[45,12,10,71,36,25,17];
  arr.sort(function(a,b){
    return 0.5-Math.random();
  });
 for(item in arr)
  {
    document.write(arr[item]+'<br>');
  }

Output:
25
36
71
17
10
12
45


Find the Largest and Smallest value in an Array

To find the largest and the smallest values of an array, we can sort the array in increasing order. The first element at index zero arr[0] will be the smallest element and the last element at index arr[arr.lenght-1] will be the largest, but this is an inefficient way to find the smallest and the largest and the smallest element of the array.

We can use Math.max for this task,

arr=[45,12,10,71,36,25,17];
function getMax(arr){
          return Math.max.apply(null,arr)
};
 document.write(getMax(arr));

Output:
71

To find the smallest or minimum number, use method Math.min

arr=[45,12,10,71,36,25,17];
function getMax(arr){
          return Math.min.apply(null,arr)
};
 document.write(getMax(arr));

Output:
71

Sorting the Objects

We can sort the objects using our own compare function.

mobiles=[{model:'Iphone',brand:'Apple'},
                {model:'Pixel',brand:'Google'},
                {model:'Oneplus7',brand:'OnePlus'},
                {model:'Galaxy',brand:'Samsung'},
                 {model:'V15',brand:'Vivo'}];

mobiles.sort(function(a,b){
  return a.brand-b.brand;
});
 for(item in mobiles)
  {
    document.write(mobiles[item].brand+'<br>');
  }

Output:
Apple
Google
OnePlus
Samsung
Vivo


Example

Wednesday, February 26, 2020

AKTU Placement and Trainings

AKTU Placements


AKTU offers 100 percent placements assistance for all the affiliated colleges and institutes.  AKTU has recoded the highest remuneration package of 11 LPA this lowest pay package of 4 LPA for the year 2019. The mean software at AKTU colleges varies between 2-3 LPA 42 corporations saw this field amongst which Heinz, Genpact, NTT information, Finserv, Enercon Bharat, ICFAI, BHEL, television, Honeywell, Infogain, L& T Infotech, Godrej, EXI_, BPL, Tech Mahindra, NIIT Technologies, Reliance visited most of the affiliated colleges. Those associated colleges that take shown top positionings represent IET Lucknow, textile Sultanpur, B I T Jhansi, JSS Noida, AKGEC Ghaziabad, KIET Ghaziabad, Galgotias College Noida, IERT Allahabad, ABES Ghaziabad, IPEC Ghaziabad.

University-Industry Interface Cell


University-Industry Interface Cell (UIIC) is the Training and Placement department of Dr. A. P. J. Abdul Kalam Technical University, Lucknow. UIIC has been set up by AKTU as per the vision and guidance of Shri Vinay Kumar Pathak, The Hon.Vice Chancellor to provide access to internship openings, job opportunities, career guidance, skill development along with several tools and opportunities for all the students of AKTU affiliated colleges across Uttar Pradesh.

Objectives Of UIIC:

  • Comprehensive platform for targeted hiring of key skill sets
  • Guidance and support will be provided to the students to enhance their understanding of the industry requirements and to help them build their skills
  • Skill mapping the student population with the industry requirements
  • The industry will be able to access high-quality talent from across the state of UP at nodal locations
  • Awareness sessions and Industry interaction will be facilitated through this forum
  • Technology-based solutions to improve the placement process
  • Provide diverse employment opportunities to cater to the aspirations and talent of the students

About Training By UIIC:

The UIIC portal provides the online interface to search available training and jobs, for direct interaction with the students. Students can visit the home page for details and availability of jobs and placements.

Top AKTU Colleges


 
S.No Name of the Institute Rating 2017 Branches
1 Ajay Kumar Garg Engineering College, Ghaziabad AAA+ Civil Engineering
Computer Science and Engineering
Information Technology
Electrical and Electronics Engineering
Electronics and Communication Engineering
Electronics and Instrumentation Engineering
Mechanical Engineering
2 Dr. Ambedkar Institute of Technology for Handicapped, Kanpur








AAA+ Computer Science and Engineering
Information Technology
Electronics Engineering
Chemical Engineering
Biotechnology
3 Institute of Engineering and Technology, Lucknow AAA+ Civil Engineering
Computer Science and Engineering
Information Technology
Electrical Engineering
Electronics and Communication Engineering
Electronics and Instrumentation Engineering
Mechanical Engineering
Chemical Engineering
4 Kamla Nehru Institute of Technology, Sultanpur AAA+ Civil Engineering
Computer Science and Engineering
Information Technology
Electrical Engineering
Electronics Engineering
Mechanical Engineering
Civil Engineering
5 KIET Group of Institutions, Ghaziabad AAA+ Civil Engineering
Computer Science and Engineering
Information Technology
Electrical and Electronics Engineering
Electronics and Communication Engineering
Electronics and Instrumentation Engineering
Mechanical Engineering
6 ABES Engineering College, Ghaziabad AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical and Electronics Engineering
Electronics and Communication Engineering
Mechanical Engineering
7 Bundelkhand Institute of Engineering and Technology, Jhansi AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical Engineering
Electronics and Communication Engineering
Mechanical Engineering
Chemical Engineering
8 Central Institute of Plastic Engineering Technology, Lucknow AAA Manufacturing Engineering
Plastic Engineering
9 Feroze Gandhi Institute of Engineering and Technology, Raibareli AAA Computer Science and Engineering
Electronics and Communication Engineering
Mechanical Engineering
Aeronautical Engineering
10 G L Bajaj Institute of Technology and Management, Greater Noida AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical and Electronics Engineering
Electronics and Communication Engineering
Mechanical Engineering
11 Galgotias College of Engineering and Technology, Greater Noida AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical Engineering
Electrical and Electronics Engineering
Instrumentation and Control Engineering
Electronics and Communication Engineering
Electronics and Instrumentation Engineering
Mechanical Engineering
12 IEC College of Engineering and Technology, Greater Noida AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical Engineering
Electronics and Communication Engineering
Mechanical Engineering
13 IILM Academy of Higher Learning, Greater Noida AAA Civil Engineering
Computer Science and Engineering
Electronics and Communication Engineering
Mechanical Engineering
Automobile Engineering
Biotechnology
14 IMS Engineering College, Ghaziabad AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical and Electronics Engineering
Electronics and Communication Engineering
Mechanical Engineering
Biotechnology
15 Institute of Engineering and Rural Technology, Allahabad AAA Computer Science and Engineering
Electronics Engineering
Industrial and Production Engineering
16 JSS Academy of Technical Education, Noida AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical Engineering
Electrical and Electronics Engineering
Instrumentation and Control Engineering
Electronics and Communication Engineering
Mechanical Engineering
17 Naraina Vidya Peeth Engineering and Management Institute, Kanpur AAA Civil Engineering
Computer Science and Engineering 
Electronics and Communication Engineering
Mechanical Engineering
Bio Technology
18 Raj Kumar Goel Institute of Technology, Ghaziabad AAA Civil Engineering
Computer Science and Engineering
Information Technology
Electrical and Electronics Engineering
Electronics and Communication Engineering
Mechanical Engineering
19 Rajkiya Engineering College, Ambedkar Nagar AAA Civil Engineering
Information Technology
Electrical Engineering
20 Rajkiya Engineering College, Azamgarh AAA Civil Engineering
Information Technology
Mechanical Engineering

Errors And Exceptions In Python

Errors And Exceptions In Python


Errors

The errors cannot be handled generally by programmers. Like, syntax errors, recursion error, memory out of bounds, etc. The errors can and should not be handled by the programmer, for example, we can not handle stack overflow or the memory out of bounds errors.

Exceptions  

A program can contain errors or exceptions, for example when the parser detects an incorrect statement(Syntax Error) the program cannot be executed. Few errors in a program are not syntax errors. They are detected during execution of the program only, such errors are known as exceptions. This type of error occurs whenever a syntactically correct program results in an error. The program terminates as soon as it encounters an error. Most exceptions aren't handled by programs but, it is possible to write programs in Python that can handle selected exceptions.

Syntax Error


#Syntax error
a=12
b='python'
print(a+b)

Output:

Traceback (most recent call last):
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in <module>
    print(a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Process finished with exit code 1

Identation Error

#identation error

for item in range(5):
print(item)

Output:
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 4    print(item)
        ^
IndentationError: expected an indented block

Process finished with exit code 1

Recursion Error

#recursion error
def rec():
    return rec()
rec()

Output:
Traceback (most recent call last):
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 4, in <module>
    rec()
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in rec
    return rec()
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in rec
    return rec()
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in rec
    return rec()
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded

Process finished with exit code 1

Built-in Exceptions

Python provides an excellent exception handling mechanism to handle the exceptions and exception logic gracefully. Python provides a rich set of built-in exceptions. All Built-in Exceptions in Python are inherited from the BaseException type.

 

Exception Class

Event

IOError

Due to an input/output operation is unsuccessful.

ArithmeticError

Due to numeric calculations is unsuccessful.

Floating-pointError

Due to a floating-point calculation is unsuccessful.

ZeroDivisionError

Due to division or modulo by zero takes place for all numeric types.

AssertionError

Due to the assert, the statement is unsuccessful.

OverflowError

Due to the result of an arithmetic operation is too large to be represented.

ImportError

Due to the imported module is not found.

IndexError

Due to the index of a sequence is out of range.

KeyboardInterruptError

Due to the user interrupts program execution, generally by pressing (Ctrl+C).

IndentationError

Due to there is a wrong indentation.

SyntaxError

Raised by the parser when a syntax error is encountered.

KeyError

Due to the specified key is not found in the dictionary.

NameError

Due to an identifier is not found in the local or global namespace.

TypeError

Due to a function or operation is applied to an object of an incorrect type.

ValueError

Due to a function gets an argument of the correct type but of an improper value.

RuntimeError

Due to a generated error does not fall into any category.


There are four main components of exception handling

try

The block of code is expected to have the exception.

except

This block of code is executed if the exception occurs.

else

This block of code is executed if no exception occurred in the code.

finally

This block of code will be executed in all circumstances, whether there is an exception or not.

The common syntax for exception handling

try-except-else-finally
Exception handling


Handling  Common Exceptions

Arithmetic Error

There can be an arithmetic error like Zero Division Error, OverFlow, and Floating-point Error,

Zero Division Error

Zero Division Error occurs when a number is divided by zero.

#Zero Division Error
try:
    a=10
    b=0
    print(a/b)
except ZeroDivisionError:
    print("Zero division Error occured")
else:
    print('No Exception occured')

Output:
Zero division Error occured

Process finished with exit code 0

OverFlowError 

Overflow Error is raised when the result of the evaluation goes beyond the valid range.
#OverFlow Error
import math
try:
    print(math.exp(1000))
except OverflowError:
    print("Over Flow Error occured")
else:
    print('No Exception occured')


Output:

Over Flow Error occured

Assertion Error

The Assertion Error occurs when an Assert fails

#Assertion Error
try:
    a=10
    b='Python'
    assert a==b
except AssertionError:
    print("Assertion Error occured")
else:
    print('No Exception occured')
Output:
Assertion Error occured

ImortError

Import Error occurs when a non-existent module(unable to load) is tried to import.
#import Error
import nibabel
print([10,12,14])
Output:
Traceback (most recent call last):
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 2, in <module>
    import nibabel
ModuleNotFoundError: No module named 'nibabel'

Lookup Errors

LookupError is the base class for the invalid key and index related errors.
Like IndexError and KeyError

IndexError

If the invalid index is accessed IndexError is raised.
#index Error
try:
    l=[10,12,14]
    print(l[3])
except IndexError:
    print('Wrong index')
else:
    print('No exception')
Output:
Wrong index

KeyError

If key is not available in dictionary but tried to access the KeyError is raised.
#Key Error
try:
    l={1:'Apple',2:'Ball',3:'Cat'}
    print(l[4])
except KeyError:
    print('KeyError occured')
else:
    print('No exception')

Output:
KeyError occured

MemoryError

MemoryError is raised when not enoough memory is available for the process to proceed further.

NameError

NameError is occured when a name whether it is global or local is not found.
#NameError
try:
    l={1:'Apple',2:'Ball',3:'Cat'}
    print(a) #a is not defined anywhere
except NameError:
    print('Name error')
else:
    print('No exception')

Output:
Name error
Disadvanatge of Python's Exception Handling is that the Python program with 
exception handling executes slower and the size of code also increases.

Monday, February 24, 2020

File Handling In Python

File Handling In Python

File handling operations like reading, writing, updating and delete the data in files of an operating system is very easy with Python We need a short piece of code to access a file in Python in comparison to other programming languages. Unlike other languages where file input and output operations require a complex process of reading and writing objects, this process is very simple in Python and requires only a few commands to open, read, write and close the file. This tutorial explains how Python can handle files on the operating system.

The open() Function

The main component to handle files in Python is the open() function. The open() function takes two parameters; filename, and the mode.

  • The filename is the path to the file or, if the file exists in the working directory, the name of that file
  • The mode a string value to determine how the file must be opened.

The Modes of File Access

There are different modes to open a file specified by this mode parameter.

  • 'r'- read mode is the default mode and allows us to simply read the file and not to modify the file.
  • 'w'- write mode creates file specified by the filename if it doesn't exist, otherwise, it will erase the file and permit you to write there.
  • 'a'- append mode allows us to write data to the top of the file. It doesn't erase the file, and therefore the file must exist for this model.
  • 'rb'- read mode in binary. this is often almost like ‘r’ mode except that the reading operation is forced in binary mode.
  • 'r+'- This read along with write mode simultaneously and allows us to read and write into files at the same time without having to use 'r' and 'w' separately.
  • 'rb+'- read and write mode in binary and this mode is equivalent to ‘r’ mode except the data is in binary format.
  • 'wb'- write mode in binary and an equivalent to ‘w’ except the info is in binary.
  • 'w+'- write and read mode. This is precisely the same as ‘r+’ but if the file doesn't exist, a replacement one is created else the same file is overwritten.
  • 'wb+'- write and read mode in binary mode and an equivalent as ‘w+’ but the info is in binary representation.
  • 'ab'- append mode in binary and almost the same as ‘a’ except that the info is in binary representation.
  • 'a+'- append and read mode and almost like ‘w+’.This will create a replacement file if the file doesn't exist.
  • 'ab+'- append and read mode in binary. It is equivalent to ‘ a+’ except that the data is in binary representation.
We can summerise the above modes in the following table,

r

r+

w

w+

a

a+

Read
Write
Creates file
Erases file

The Exclusive Modes


Python 3 introduced a new mode for exclusive creation so that you will not accidentally truncate or overwrite and existing file.

x

x+

Read
Write
Creates file
Erases file


  • 'x'-This mode opens in exclusive creation and it will raise FileExistsError if the file already exists.
  • 'xb'- This mode opens for exclusive creation write mode in binary format. The same as ‘ x’ except the data is in binary representation.
  • 'x+'- Exclusive read and write mode, It is equivalent to ‘w+’ and create a new file if the file does not exist. Otherwise, it will raise FileExistsError.
  • 'xb+'- Exclusive read and write mode. This is equivalent to ‘ x+’ but the data in a binary format.
For Example

#Write to the file
with open('myfile.txt', 'w') as f:
    f.write('this is the new file')
#Append to the file
with open('myfile.txt', 'a') as f:
    f.write('\\n Appended message is Python is easy')

print('written successfully')


#Read the file
with open('myfile.txt', 'r') as f:
    f.read()

#This can be done in a better way as 
try:
    with open("fname", "r") as fout:
    # Work with your open file
except FileExistsError:
    #Raise the error


Reading the File Line By Line


with open('myfile.txt', 'r') as fp:
    for line in fp:
        print(line)

The readlines() method


For more control over the data over the data we can use the readlines() method 

with open("myfile.txt", "r") as fp:
    lines =fp.readlines()

for i in range(len(lines)):
    print("Line "+ str(i)+ ": "+ lines[i])



to read the full content of the file the read() method can be used.

with open('myfile.txt') as fl:
    content =fl.read()
    print(content)

The write() Method

The write() method can be used to write the data into a file. We need to inserts line break (\n) character for a new line, as Python itself does not provide a new line character itself.

with open('myfile.txt', 'w') as f:
    f.write("Python is\n")
    f.write("Easy and\n")
    f.write("simple \n")
    f.write("programming language\n")
print('Written Successfully')