How to optimize the performance of ng-repeat in AngularJS?

Today we would focus on improving the performance of Angular JS code by learning the basics of ng-repeat and then how to enhance its capabilities.

Follow us for more learning Fb,G+,Twitter.

ng-repeat :- 
It is directive which create instant of template for each item in the collection. It is identical to looping concept in any language say Java, for example we need to display all the items in an array we would use "ForEach item in items" in Java. Similarly we would say "ng-repeat = item in items" in Angular JS terms. 

Note:- We have angular.forEach function available in AngularJs used for iteration.

Example:- 
We need to display all the name-version pairs on the view.We would implement ng-repeat as we did inthe following example...

ng-repeat example code

Live Demo

Note:-By default, ngRepeat does not allow duplicate items in arrays. We can overcome this by defining our own track by expression. 
Example below we have key = Angular is repeating twice but still in the output we are getting the one key-value pair.
Duplicate key in ng-repeat


How many watches does ng-repeat create for above example?
We knew that Angular creates a $watch for every single ng directive, so above list has 3 + 1 watches (3 names + 1 for ng-directive).Imagine if we have huge array of names how many watches would be created.

How to improve the performance of ng-repeat?

1. Using track by:-
Track by assist Angular in recognizing unique items. Now by default for every item that is getting displayed using ng-repeat, AngularJS calculates hash value to uniquely identify the object. To make sure that whether it has an object before or new object need to be created to display it.

Suppose we are fetching our name-version array in above example on frequent basis this means reference to objects displayed changes multiple times in ng-repeat.So it is recommended to tell AngularJS, how it can identify the unique items. 

Our solution is track by.
"ng-repeat ="name in items track by name.id"

This tells AngularJS that each name is uniquely identified by the name.id value, and to reuse DOM elements as long as the id field does not change.Thus we have used our own key for ng-repeat to identify the objects, instead of generating the unique ID’s each time.

Learning: - implement track by to get unique values

2.Using filters in controller rather than directly in HTML
Filter helps in limiting our data by giving data in user required form, for example we want our version above  to have 2 decimal places at end so we can just change the code as

ng-repeat = "" | filter =limitto:2

But this becomes a headache and a performance issue incase we are filtering the data in the HTML. Better  optimize the triggering of filer in our controller rather than implementing it directly in HTML.

Learning: - Limit DOM filters

3. One-time data binding {{::expression}}

It can be done by simply using the prefix "::"( double colon) before the angular expression.

It helps as AngularJS stops watching the variable and updating it in the UI. So resources are freed for watchlist thus improving the performance.
Remember this approach is useful useful for data that is not expected to change after displayed to the user.

Learning: - Implement bind-once approach if possible

Learn more Angular Concepts


Best and affordable editor for writing visual Basic code??

What is your favorite VBS editor to write scripts?

If we search vb editor on Google you would find thousand of suggestions like notepad++,vbsedit and many more fancy IDE.But sometimes there are situations, like due to organization compliance policies or some other reasons, that we don’t have access to these editors .Then what to do in that case of scenarios.

“Don’t use a lot where a little will do.” -Proverb

Thus we have to achieve maximum out of what we have.

Solution is utilizing the inbuilt feature of developer tab  in  Microsoft excel to code our vbs/vba scripts.

We thought of sharing the same with you all, follow us on  Fb,G+,Twitter for more updates. 

Steps:-

1. Open excel instance.

2. Look for "Developer tab" -> Visual Basic

Opening Visual Basic editor in Excel
Note: - Incase "Developer tab" is not available in the excel ribbon, then, click on Microsoft icon on the top left corner of excel ->Excel Options -> Popular -> check the "Show Developer tab in the ribbon" > OK
We can directly launch Visual basic IDE by using ALT+ F11,after launching the excel instance.

3. Right click on VBA project in the “project explorer “ -> Insert -> module

Inserting Module in Excel

4. Now we ready to write our code, it provides intellisense and debugging 


Debug in VBA project Excel


facilities(like we have watch option in UFT same is available here) 

5. Save as type "Excel Macro-Enabled Workbook"

6. Run (F5) or green play icon on the ribbon panel.
Explore the other features on the panel to learn more.

Run VBA project Excel

Please share your views or your comments about what can be your favorite editor incase you have limited resources, other than Notepad offcourse :)

Learn Vbscript
Selenium

Example scenarios for working with Dictionary Object Using vbscript.

Every day you wake up is a victory. Learn more and share more....

Concept 1:-How to find the occurrence count of item in a given sample?


Sorting using Dictionary object

Using dictionary object we would find the count of occurrence of given value in the sample.
Example: - we need to find the "Help" words in the given string say: - "God help those who help themselves"

Lets connect for more updates at  Fb,G+,Twitter.
Code:-

'Input String
sSample = "God help those who help themselves"
'Splitting the given string
arrSample = Split(sSample)
'Calling the function to get the Count of all the items
Set objCount = fn_Count(arrSample)
arrKey = objCount.Keys
For iRun = 0 To objCount.Count - 1
 MsgBox "Count of '" & arrKey(iRun) & "' =" & objCount.Item(arrKey(iRun))
Next
'*******************************************Function*********************************
'Function Name:-        fn_Count
'Function Description:- Function find the occuerence of given word in the string
'Input Parameters:-     Given String
'Output Parameters:-    Dictionary object
'************************************************************************************

Function fn_Count(arrSample)
    Dim iRow, iItem
    Dim objDic
    Set objDic = CreateObject("scripting.dictionary")
    'Looping through array
    For iRow = LBound(arrSample) To UBound(arrSample)
        iItem = arrSample(iRow)
        If Not objDic.Exists(iItem) Then
            objDic.Add iItem, 1
        Else
         objDic.Item(iItem) = objDic.Item(iItem) + 1
        End If
    Next
    
    Set fn_Count = objDic
End Function

Concept 2:- How to sort items in the given dictionary?
Note: - we can sort dictionary keys in the same manner as we did items.

Code:-

'*******************************************Function*********************************
'Function Name:-        fn_SortDictionary
'Function Description:- Function to sort the items in the given dictionary
'Input Parameters:-     Unsorted Dictionary object
'Output Parameters:-    Sorted Dictionary object
'************************************************************************************
Function fn_SortDictionary(objdict)
  Dim i, j, temp
    For Each i In objdict
      For Each j In objdict
        If (objdict.Item(i) <= objdict.Item(j)) Then
          temp = objdict.Item(i)
          objdict.Item(i) = objdict.Item(j)
          objdict.Item(j) = temp
        End If
      Next
    Next
    Set fn_SortDictionary = objdict
End Function

Concept 3:- How to sort dictionary Key-Item pairs based on the Item or key?

This is different from the above concept as we are not simply sorting the items or keys present in the dictionary but actually we are creating a new sorted dictionary. Some time it is required to sort the Key-Value pairs in ascending or descending order.
Note: - Here we are sorting on the basis of items and some time our item values can be repeating.

Code:-
    'Creating dictionary
    Dim objDic
    Set objDic = CreateObject("scripting.dictionary")
    objDic.Add "USD", "80"
    objDic.Add "SAG", "55"
    objDic.Add "CAD", "80"
    objDic.Add "AUD", "50"
    
   'Function call to sort the dictionary
   Set objSDic = fn_SortDictionary(objDic)
   'Printing the Result of sorted Dictionary in the Msgbox
    For i = 0 To objSDic.Count - 1
        Txt = Txt & objSDic.keys()(i) & objSDic.items()(i) & vbCrLf
    Next i
    MsgBox Txt



  
'*******************************************Function*********************************
'Function Name:-        fn_SortDictionary
'Function Description:- Function to sort the Key and item pairs in the given dictionary
'Input Parameters:-     Unsorted Dictionary object
'Output Parameters:-    Sorted Dictionary object
'************************************************************************************
Function fn_SortDictionary(objIDict)

    'Taking the Orginal Keys
    arrKey = objIDict.keys
    'Taking the count of items values
    arrSort = objIDict.items
    
    'We would sort on the basis of Items but for keeping track which item belongs to the key
    'we would add index value to the existing items
    'Incase we have duplicating items we be still be able to sort.
    'Adding index to all the items
    For i = LBound(arrSort) To UBound(arrSort)
        arrSort(i) = arrSort(i) & ";" & i
    Next
    'Logic for sorting
       
    For i = LBound(arrSort) To UBound(arrSort) - 1
        For j = i + 1 To UBound(arrSort)
            'Split the value of arrsort so that we dont consider the index part
              arrFSortI = Split(arrSort(i), ";")
              arrFSortJ = Split(arrSort(j), ";")
            If Cint(arrFSortI(0)) < Cint(arrFSortJ(0)) Then
                'Concatenating the split array and joining the Index at the end
                Temp = arrFSortJ(0) & ";" & arrFSortJ(1)
                arrSort(j) = arrFSortI(0) & ";" & arrFSortI(1)
                arrSort(i) = Temp
            End If
        Next j
    Next i
    'Creating the Temp Dictionary object
     Set TempDict = CreateObject("scripting.Dictionary")
    'Adding sorted values to the dictionary
    For i = LBound(arrSort) To UBound(arrSort)
        KeyIndex = Split(arrSort(i), ";")
        TempDict.Add Key:=arrKey(KeyIndex(1)), Item:=KeyIndex(0)
    Next i
    'Returning the sorted dictionary
   Set fn_SortDictionary = TempDict
End Function


SQL Interview Questions(Set-2)

Here comes our next bundle of SQL interview questions. We have also given a brush up for the brief answer hints at the bottom. Hope it help you all in achieving your target job.

Keep sharing and Keep learning.

Do follow us for more updates on  Fb,G+,Twitter.

Learn more and share more
Learn more to achieve more...

  1. What is the difference between which and having clause?
  2. What is composite key? How it differs from Candidate key?
  3. We have 2 tables A&B. Write a query to get just non matching account ID from B table using joins.
  4. In the above table modify the query to fetch non matching account ID from both the tables(Means removing the common ID’s)
  5. How to remove duplicate values from a Table A.
  6. In question 5? How to delete only one duplicate row from a table for each combination?
  7. We have 2 tables, Candidate (id, name) and vote (id, Count), write a query to give the name of winning candidate?
  8. Write a query to find the nth maximum salary in a emp table
  9. What is a join? Explain the different types of joins?
  10. Explain the sequence of query execution?
Hints:-


1. Where clause cannot be used with aggregate functions (like sum, max, min, count) so we need to implement having clause.
Example for a Table A we need to count the applications where count is greater than 5, so we cannot create a query like select count (applications) from table A where count (app) > 5, we need to use ‘having’ clause select count (app) from Table A having (count (app)) > 5
Note: - We generally use having clause with group by clause but we can use it alone. If the SQL SELECT statement does not contain aggregate functions, here it would act like a Where clause itself.

2. Composite primary key is used to define more than one primary column for a table.
CREATE TABLE A
(ID integer,test
NAME varchar (30),
CLASS varchar (50),
PRIMARY KEY (ID, NAME));
Candidate key: - A Candidate Key can be any column or a combination of columns that can qualify as unique key in database. And there could be multiple Candidate Keys in one table. Each Candidate Key can qualify as Primary Key but we have only one primary key.
Note:-A table can have multiple Candidate Keys that are unique as single column or combined multiple columns to the table. They are all candidates for Primary Key. Candidate keys that follow all the three rules – 1) Not Null, 2) Unique Value in Table and 3) Static – are the best candidates for Primary Key.

3. We need to implement Left outer join on Table B and Table A.Also we used ‘Where’ clause to restrict the common records in both the tables.
SELECT B.Accountid
FROM Table B AS B
LEFT JOIN Table A AS A ON A.ID = B.Accountid
WHERE A.ID IS NULL
Right Outer Join Example

4. This time we would exclude the common ID’s again by using ‘Where’ Clause and “Full Outer Join”
SELECT  B.Accountid, A.ID FROM Table B AS B
FULL OUTER JOIN Table A AS A ON A.ID = B.Accountid
WHERE A.ID IS NULL OR B.AccountID  IS  NULL
Full Outer Join Example

5.  It deletes any of the rows which are repeating from the table.
delete from Table A  where ID in (select  A.ID  from Table  A  group by ID  having
    count (*) >1)

7. We need to use “Inner Join” as we need the common data of both the tables based on the candidate ID.
SELECT  B.CandidateName
FROM Table Candidate AS B
INNER JOIN Table vote AS ON A.ID = B.ID
GROUP BY B.Name

8. SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary
How it works, sub query it finds the N highest salaries in the Employee table and arranges them in descending order.Now,the outer query will actually rearrange those values in ascending order, which is what the very last line “ORDER BY Salary” does, because of the fact that the ORDER BY Default is to sort values in ASCENDING order. Finally, that means the Nth highest salary will be at the top of the list of salaries, which means we just want the first row, which is exactly what “SELECT TOP 1 Salary” will do for us.

9. Join means a guide to database to combine data from more than one table.
Types of join:-
Inner,Outer,Cross&Self Join

Inner Join: - inner join produces a result set that is limited to the rows where there is a match in both tables, thus it sends the matching data from joining tables

Outer types: - Left Outer, Right outer and Full Outer.

Left outer join: - It gives data from the left join table + the common data from the joining tables.

Right outer join: - Reverse of above, data from the right joining table + common data from the joining tables.

Full outer join:-A full outer join, or just outer join, produces a result set with all of the rows of both tables, regardless of whether there are any matches.
Thus full is the combination of left and right outer joins


Cross join: - The row count of the result is equal to the number of rows in the first table times the number of rows in the second table. Each row is a combination of the rows of the first and second table.

Self join: - Joining the same table twice

10 .General sequence of query execution :-
1. FROM
2. ON
3. Joins
4. WHERE
5. GROUP BY
6. HAVING
7. SELECT
8. DISTINCT
9. ORDER BY
10. Aggregate functions


More interview Questions. 
Learn Excel Programming concepts.

Approach to find last row or column using VB script in Excel?

We are sharing these techniques so that we can work with dynamic set of data in an Excel.
Finding last row of excel using code


Do follow us for more learning’s Fb,G+,Twitter.

Technique 1:- 
Using UsedRange property:- 
This approach is frequently implemented and one of our favorite. But sometime we have seen that incase some formatting is present in the sheet, it points till the last range of the excel (like 1,048,576 rows in excel -2013) itself rather than the last occupied row of the sheet. 

Technique 2:-
  • Using “CTRL+SHIFT+END” to find the last row 
  • Using “CTRL+SHIFT+Down Arrow” to find the last row 
  • Using “CTRL+SHIFT+left/Right arrow” to find the last column
Code:-
'*******************************************Function*********************************
'Function Name:-        fn_CalRange
'Function Description:- Function to Calculate the last row & last column
'Input Parameters:-     N/A
'Output Parameters:-    N/A
'************************************************************************************
Sub fn_CalRange()
    
    Dim iLastRow
    Set objExcel = CreateObject("Excel.Application")
    'Making Excel visible to user
    objExcel.Visible = True
    Set oCountWB = objExcel.Workbooks.Open("D:\Test.xlsx")
    Set oCountWS = oCountWB.Worksheets("Sheet1")
    
    '****************UsedRange********************
    'Counting the Last row using 'Range' Property
    iLastRow = oCountWS.UsedRange.Rows.Count
    'Counting the Last Column using 'Range' Property
    iLastCol = oCountWS.UsedRange.Columns.Count
    MsgBox "Using Range Property Last Row: " & iLastRow & " Last Column:" & iLastCol
    
    '*****************CTRL+SHIFT+END*************
    '-4162 meaning xlUp
    'Using CTRL+SHIFT+END to find the last row
    iLastRow = oCountWS.Cells(oCountWS.Rows.Count, "A").End("-4162").Row
     MsgBox "Using CTRL+SHIFT+END, Last Row:" & iLastRow
     
     '*****************CTRL+SHIFT+Left Arrow*************
    'Using CTRL+SHIFT+left arrow to find the last Column
    '-4159 for xlToLeft
    iLastCol = oCountWS.Cells(1, oCountWS.Columns.Count).End("-4159").Column
     MsgBox "Using CTRL+SHIFT+Left Arrow,  Last Column:" & iLastCol
     
     '*****************CTRL+SHIFT+Down/Right Arrow************
     iLastRow = oCountWS.Range("A1").CurrentRegion.Rows.Count
     iLastCol = oCountWS.Range("A1").CurrentRegion.Columns.Count
     MsgBox "Using CTRL+SHIFT+Down/Right Arrow,Last Row:" & iLastRow & " Last Column:" & iLastCol
     
End Sub

More Excel Examples

SQL Interview Questions (Set-1)

This is our first set of SQL interview Questions.

Prepare well and crack your dream job. It is said,“Fall seven times, stand up eight.”(Japanese proverb), so work hard to achieve heights.
Work hard to crack SQL interview
Work Hard

Follow us on Facebook for more updates and learning!!!


  1. What are various types of SQL statements?
  2. What is the difference between Truncate, Drop and Delete?
  3. Difference between Local and Global Temp tables?
  4. What are indexes and types of indexes?
  5. How to copy only structure of Table A to Table B?
  6. Meaning of BCP in SQL?


Hints:-

1.
a. Data definition language
  1. Create
  2. Alter
  3. Drop
  4. Truncate

b. Data Manipulation language 
  1. Select
  2. Insert
  3. Delete
  4. Update

c. Data Control Language
  1. Grant 
  2. Revoke

d. Transaction control statements
  1. Commit
  2. Rollback
  3. Save point 


2. Delete, is used to remove rows from a table, we can use where clause to limit the rows to be deleted. After delete we need to perform Commit or Rollback operation to make the changes permanent, thus we can say we have chance to undo the delete operation .It is a DML command. Delete will cause delete triggers on the table to be fired.

Truncate, it is used to remove all rows from a table. The operation cannot be rolled back and no triggers are fired. It is a DDL command and faster as It does not use the concept of undo operation thus even logs are not maintained for the deleted data.

Drop, is more dangerous as it removes table from the database unlike above commands which were only removing rows from the table. Like truncate it cannot be rolled back and no triggers are fired in this case, further this also a DDL command.

3. Temporary tables (temdb) are automatically deleted when they are not in use. 
  1. Local, It is prefixed with  single ‘#’ when while creation. Like create table #Study(ID int not null). Further they are available only to the connection that creates it and are deleted when the connection is closed. We can create a same local temp table with the same name but in a different connection.
  2. Global, It is prefixed by ‘##’ values, like create table ##Study (ID int not null).They are visible to all the connections of SQL server and are destroyed only when the last connection referencing the table is closed.


4Index: - It is an structure associated with a table or view which speed up the query retrieval time. An index contains keys which are combination of one or more columns of table or view. These keys are stored in B-Tree structure for efficient search of data from a table.

Types:-
Clustered Index:- Example like phone directory, where each entry in the directory represents one row of the table. A table can have only one clustered index.
Non Clustered Index: - Example , index at the back of the book, where indexed values contains pointers to the actual rows(page number in a book).

Syntax:-Create index (index name) ON table_Name (Column name)


5. Select * into TableB from TableA where 0=1

6. BCP (Bulk copy Program) is a command line utility to bulk copy data between an SQL server and a data file (both in or out).We can use table or query to export/import data. Example we need to move data from database A to file B , so we would write bcp database A .TABLE A out file B.


How to randomize rows of data in a Excel?

Problem:- How to randomize the given set of data in an Excel?

Solution: - We would try to shuffle the rows of data in a given excel. We would try it manually first followed by code written in Vb-script.

Using RAND() FUNCTION to shuffle excel data
Manual Approach:- 
Step1:- Add column(say Random) in the starting of the excel

Step2:- Apply formula to the first cell (=Rand ()) and drag it across all the cells of the same column in the sheet.

Step3:- Apply on the Filter on the first row of the excel (Data - > Filter)

Step4:- Now sort the Column one data in ascending order .All set we have our randomize data in the end.

















Automation Approach:- 
We would use Vbscript code to automate the randomization of excel data. We would replicate the above manual steps by using coding.Please refer our tutorial on Excel automation to understand the below code.


Note:-
Please do the following changes to run the below code:-

  • sFileName = Change it to Your file that need to be randomized
  • Change the sheetname in the code line   Set oReadSheet = oReadWB.Worksheets("Sample")

'Function Call to Randomize data in Excel
fn_Randomize

'*******************************************Function*********************************
'Function Name:-        fn_Randomize
'Function Description:- Function to shuffle Excel data
'Input Parameters:-     N/A
'Output Parameters:-    N/A
'************************************************************************************
Sub fn_Randomize()
    'FileName of the Excel
    Dim sFileName
    sFileName = "D:\Automate\DataSheet\RandomTest.xlsx"
    'Creating the Excel Object
    Set oExcel = CreateObject("Excel.Application")
    'Making Excel Visible
    oExcel.Visible = True
    'Creating the Workbooks object
    Set oReadWB = oExcel.Workbooks.Open(sFileName)
    'Creating the Read sheet object
    Set oReadSheet = oReadWB.Worksheets("Sample")
    'Inserting 'Random' column as our first column in the sheet
    oReadSheet.Columns(1).Insert
    oReadSheet.Range("A1").Value = "Random"
    'Running the loop till for all the rows of excel which have data
     For iRow = 2 To oReadSheet.UsedRange.Rows.Count
        'Applying Random formula on the first column of the cell
         oReadSheet.Cells(iRow, 1) = "=Rand()"
        'Copying only the value and removing the formula from the cell
        'Try commenting the below line of code and see the cell still contains "=Rand"
        oReadSheet.Cells(iRow, 1).Value = oReadSheet.Cells(iRow, 1).Value
     Next
    'Now sorting the Data
    'Clearing any formuales on the Temp sheet
    oReadSheet.Sort.SortFields.Clear
    'Sorting on the basis of Colunm =1 in the asencding order
    Call oReadSheet.Sort.SortFields.Add(oReadSheet.Columns(1), , xlAscending)
    'Giving the range to be sorted(till the end of the sheet)
    'Start cell is A2 as we have header on the Top
    'End of sheet is taken as XFD1048576 as per Excel-2007
    Call oReadSheet.Sort.SetRange(oReadSheet.Range("A2:XFD1048576"))
    'Applying the sort
    oReadSheet.Sort.Apply
    MsgBox "Data is Randomized..Cheers!!"
    Set oExcel = Nothing
End Sub