Showing posts from 2019

NgTrueValue NgFalseValue equivalent directive in angular 2+

Code : import {Directive, ElementRef, forwardRef, HostListener, Input, Renderer2} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; @Directive({     selector: 'input[type=radio][trueFalseValue]',     providers: [         {             provide: NG_VALUE_ACCESSOR,             useExisting: forwardRef(() => TrueFalseValueDirective),             multi: true         }     ] }) export class TrueFalseValueDirective implements ControlValueAccessor {     @Input() trueValue = true;     @Input() falseValue = false;     constructor(private elementRef: ElementRef, private renderer: Renderer2) {}     private propagateChange = (_: any) => {};     @HostListener('change', ['$event'])     onHostChange(ev) {         this.propagateChange( ? this.trueValue : this.falseValue);     }     writeValue(obj: any): void {         if (obj == null) {             this.propagateChange(

Image lazy load directive code in angular 2+

Code : import {Directive, HostBinding, Input, OnInit} from '@angular/core'; // Define the Directive meta data @Directive({     selector: '[img-preloader]', }) // Class must implement OnInit for @Input() export class ImagePreloaderDirective implements OnInit {     @HostBinding('attr.src') finalImage;     @Input('img-preloader') targetSource: string;     downloadingImage: any; // In class holder of remote image     // finalImage: any; // property bound to our host attribute.     // Set an input so the directive can set a default image.     @Input() defaultImage = 'assets/imgs/img-loader.svg';     @Input() errorImage = 'assets/imgs/img-placeholder.svg';     constructor() {         this.finalImage = this.defaultImage;     }     // ngOnInit is needed to access the @inputs() variables. these aren't available on constructor()     ngOnInit() {         // First set the final image to some default image while we prep

Safe HTML pipe in angular 2+

Code :  import {Pipe, PipeTransform} from '@angular/core'; import {DomSanitizer} from '@angular/platform-browser'; @Pipe({   name: 'safeHtml' }) export class SafeHtmlPipe implements PipeTransform {   constructor(private sanitizer: DomSanitizer) {}   transform(value: any, args?: any): any {     return this.sanitizer.bypassSecurityTrustHtml(value);     // return this.sanitizer.bypassSecurityTrustStyle(style);     // return this.sanitizer.bypassSecurityTrustXxx(style); - see docs   } } How to use: {{ varContainingSomeHTML| safeHtml }}

Make your angular ionic app offline runnable using Ionic Storage

You might be aware that we can make web application offline runnable using service woker. But service worker doesn't work with Ionic hybrid mobile apps as those are blocked webview. Obvious another solution in such case is to use Ionic Storage to cache all required data and then use it as required. After digging deep I realized that I only need to cache the responses of HTTP GET request in my case, as assets and other static stuffs are already served by cordova wether its offline or online mode. So I wrote a custome injectable service which internally uses HttpClient. This implementaion is kind of wrapper for HttpClient class. All I deed is wrote a get() method in a service which is capable of checking network connectivity and based on that make a dicision whether to return cached response or make a actual HTTP GET call using HttpClient, cache the response and then return it back.  Instead of directly using HttpClient, I'm using this new service to make GET calls.

Positive number pipe in angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({   name: 'positive' }) export class PositivePipe implements PipeTransform {   transform(value: number, args?: any): any {     return Math.abs(value);   } } How to use: {{ someNumber| positive }}

Orderby pipe in angular 2+

Code:  import {Pipe, PipeTransform} from '@angular/core'; import * as _ from 'lodash'; import {Many} from 'lodash'; @Pipe({   name: 'orderBy',   pure: false }) export class OrderByPipe implements PipeTransform {   transform(items: any[], args?: string[], orders?: Many<boolean|'asc'|'desc'>): any {     if (args && args.length > 0) {       if (orders) {         return _.orderBy(items, args, orders);       } else {         return _.orderBy(items, args, 'asc');       }     } else {       return items;     }   } } How to use: {{ someList | orderBy: ['createdOn']: 'desc' }}

Hightlight text in search result using pipe angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({   name: 'highlightSearch' }) export class HighlightSearchPipe implements PipeTransform {   transform(value: any, args: any): any {     if (!args) {return value; }     const re = new RegExp(args, 'gi'); // 'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.     return value.replace(new RegExp(args, 'gi'), '<span font-bold>$&</span>'/*re, '<span font-bold>' + args + '</span>'*/);   } } How to use: {{someStringVar | highlightSearch: textToHighlight | safeHtml}}

Groupby pipe in angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({   name: 'groupby' }) export class GroupbyPipe implements PipeTransform {   transform(collection: Array<any>, property: string): Array<any> {     // prevents the application from breaking if the array of objects doesn't exist yet     if (!collection) {       return null;     }     const groupedCollection = collection.reduce((previous, current) => {       if (!previous[current[property]]) {         previous[current[property]] = [current];       } else {         previous[current[property]].push(current);       }       return previous;     }, {});     // this will return an array of objects, each object containing a group of objects     return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));   } }

Filter pipe angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'filter',  pure: false }) export class FilterPipe implements PipeTransform {   transform(items: any[], field: string, value): any[] {     if (!items) { return []; }     if (!value || value.length === 0) { return items; }     return items.filter(it =>         it[field] === value);   } } How to use:  someList | filter: 'enabled': true"

ng-true-value ng-false-value alternative in Angular

In AngularJs (1.x) there is facility to set true value and false value for input type checkbox using ngTrueValue ngFalseValue directives. But its been removed in Angular 2 + . Below is directive which will serve the same purpose as it was in AngularJs (1.x) . Here it simply listens to the change event of input element using HostListener and value of input element is manipulated based on whether its checked or unchecked. import { Directive, Input, forwardRef, HostListener, ElementRef, Renderer2} from '@angular/core';import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgControl} from '@angular/forms';@Directive({ selector: 'input[type=radio][trueFalseValue]', providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TrueFalseValueDirective), multi: true } ]})export class TrueFalseValueDirective implements ControlValueAccessor { private propagateChange = (_: an

AngularJs input text character count directive

This directive will help you to count number of characters in input element its applied on. It will create a paragraph (<p>) element next to element its applied on and will show count in it. You can also customize count message to show. /** * How to use : * * Apply 'char-count' attribute on text input fields/textarea * * Other properties: * char-count-msg="countMsg" : returns a string with count and max-length (Eg: "5 out of 100") * char-count-auto-show-message="true" : auto display count message near to text inputs * */'use strict';(function () { let app = angular.module('testApp'); app.directive('charCount', ['$log', '$timeout', function ($log, $timeout) { return { restrict: 'A', scope: { charCountMsg: "=?", charCountAutoShowMessage: "@" }, compile: function compile() {

Ionic 4 multiple images base64 conversion for upload

There are various ways to save image data on server side. One of the way is to convert images data to base64 and store it in databases like MongoDb. In this post we are going to see how we can use ion – input to select multiple images and then convert those to base64 format. To select images we need to specify type attribute of ion-input as file and accept attribute as image/*;capture=camera this will make ion-input to allow selection of only image files or open camera to capture image. Below is code snippet for all this. You can also restrict image file types using accept attribute. <ion-item> <ion-label position="stacked">Images</ion-label> <ion-input (change)="convertToBs64($event)" multiple="true" type="file" accept="image/*;capture=camera"></ion-input> </ion-item> Next is we need to call a method on change event of ion-input. Remember not to use ionC

Symbol Type in Javascript

Symbol is a primitive type for unique identifiers. Symbols are created with Symbol() call with an optional description. Symbols are always different values, even if they have the same name. If we want same-named symbols to be equal, then we should use the global registry: Symbol.for(key) returns (creates if needed) a global symbol with key as the name. Multiple calls of Symbol.for return exactly the same symbol. Symbols have two main use cases: “Hidden” object properties. If we want to add a property into an object that “belongs” to another script or a library, we can create a symbol and use it as a property key. A symbolic property does not appear in , so it won’t be occasionally listed. Also it won’t be accessed directly, because another script does not have our symbol, so it will not occasionally intervene into its actions. So we can “covertly” hide something into objects that we need, but others should not see, using symbolic properties. There

Expandable recursive tree table with AngularJS and Bootstrap

Below is the code for AngularJs directive which will render a table structure containing tree in its first column and data in further columns. By clicking on tree node one can expand/collapse subsequent rows. Please take a look at sample data provided to understand the data model used in this directive. angularTreeTable.directive.js 'use strict';(function () { let app = angular.module('TestApp'); app.directive('angularTreeTable', function () { return { restrict: 'EA', transclude: true, scope: {tableData: '=', tableConfig: '='}, bindToController: true, templateUrl: 'angularTreeTable.directive.html', controller: function ($scope, StatusMessage, $sce) { let ctrl = this; }, controllerAs: "ctrl" }; });})();   angularTreeTable.directive.html <div class="treeTable"> <table class=&qu

Printing all Permutations of a String - C Programming Tutorial

In this c programming tutorial we are going to see a c program to print all permutations of a given string. Now let's see what is a permutation. A permutation, also called an arrangement number or order, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword Below are the permutations of string CBA. ABC, ACB, BAC, BCA, CAB, CBA Algorithm Paradigm: Backtracking Time Complexity: O(n*n!) Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. #include <stdio.h> #include <string.h> /* Function to swap values at two pointers */ void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */ void permute(char *

Determining if Two Trees are Identical - C Programming Tutorial

In this c programming tutorial we are going to see how we can compare two trees to check whether they are identical or not. Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Below is the simple Algorithm to compare two trees : sameTree(tree1, tree2) 1. If both trees are empty then return 1 2. Else If both trees are non -empty Check data of the root nodes (tree1->data == tree2->data) Check left subtrees recursively i.e., call sameTree( tree1->left_subtree, tree2->left_subtree) Check right subtrees recursively i.e., call sameTree( tree1->right_subtree, tree2->right_subtree) If a,b and c are true then return 1. 3. Else return 0 (one is empty and other is not) Time Complexity : Complexity of the identicalTree() will be according to the tree with lesser num

Frequency of characters in a String - C Programming Tutorial

In this c programming tutorial we are going to see program which computes frequency of characters in a string i.e. which character is present how many times in a string. For example in the string "krishna" each of the character 'k', 'r', 'i','s','h','n', and 'a' has occurred one time. Note that only lower case alphabets are considered, other characters (uppercase and special characters) are ignored. For counting number of characters in a string we need to traverse the whole string from its start to end and store the count for each character that appears in string. For storing character count we can use simple integer array with name say "count" and having size 26 as there are only 26 alphabets (we are ignoring special symbols and uppercase characters). Now to make program efficient we are making use of ASCII values of characters. See the "count[string[c]-'a']++" statement in code, consider in

Implementing Vector - C Programming Tutorial

In this c programming tutorial we are going to see code for implementing vector in c language or creating array of size N (Any size array) in language. So let's proceed, in this c programming tutorial we're just going to create a dynamically sized array of integers. Here's what the definition of a vector interface might look like: // vector.h #define VECTOR_INITIAL_CAPACITY 100 // Define a vector type typedef struct { int size; // slots used so far int capacity; // total available slots int *data; // array of integers we're storing } Vector; void vector_init(Vector *vector); void vector_append(Vector *vector, int value); int vector_get(Vector *vector, int index); void vector_set(Vector *vector, int index, int value); void vector_double_capacity_if_full(Vector *vector); void vector_free(Vector *vector); Note that we are writing this code in header file and we will be calling it vector.h Implementing Vector Below is the code for implementation of

C program for calculating IP header checksum

#include<stdio.h> /*program for calculating header checksum*/ int main() { int i=0, binary_index=0, temp, j, b_temp[17], binary[17]; unsigned long int sum=0; printf("\nEnter packet data\n"); for(i=0;i<10;i++) { scanf("%x",&temp); sum=sum+temp; } //finding binary of sum while( sum!=0 ) { int bit; bit=sum%2; binary[binary_index]=bit; binary_index++; printf(" %d ", bit); sum=sum/2; } //reversing for(i=0;i<=binary_index;i++) { b_temp[i]=binary[i]; } j=0; for(i=binary_index;i>=0;i--) { binary[j] = b_temp[i]; j++; } printf("\n\nAns before adding carry bit:\n"); for(i=0;i<=binary_index;i++) { printf(" %d",binary[i]); } printf("\n\nAns after adding carry bit:\n"); if(binary_index>16) { // adding carry bit temp=1; for(i=binary_index;i>1;i--) { if(binary[i]==1 && temp==1) {binary[i]=0;temp=1;} else if(binary[i]==0 && temp==1) {binary[i]=1;temp=0;break;} else if(binary[i]==0 &&

C++ program code for drawing line using DDA

//use Turbo-c and press alt+f5 to see output #include<math.h> #include<stdlib.h> #include<iostream.h> #include<dos.h> #include<graphics.h> using namespace std void dda(int x1, int y1,int x2,int y2); int main() { int gd= DETECT,gm; //detecting graphics driver automatically int x1,y1,x2,y2; initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); cleardevice(); cout<<"DDA LINE GENERATION ALGORITHM\n\n"; cout<<"ENTER STARTING COORDINATES OF DRAWING LINE\n"; cin>>x1>>y1; cout<<"\nENTER ENDING COORDINATES OF LINE\n"; cin>>x2>>y2; dda(x1,y1,x2,y2); cout<<"\n INPUT ANY NUMBER + ENTER TO CLOSE\n"; cin>>x1; closegraph(); } void dda(int x1, int y1, int x2,int y2) { int i,dx,dy,step; float x,y; float xinc,yinc; dx=(x2-x1); dy=(y2-y1); if(abs(dx)>=abs(dy)) step=dx; else step=dy; xinc=(float)dx/step; yinc=(float)dy/step; x=x1; y=y1; putpixel(x,y,WHITE); for(i=1;i<step;i

J2EE Interview Questions

1) What is J2EE? J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multi tiered, and web-based applications. 2) What is the J2EE module? A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type. 3) What are the components of J2EE application? A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: Application clients and applets are client components. Java Servlets and Java Server PagesTM (JSPTM) technology components are web components. Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components. Resource adapter c

How long you should invest in mutual funds ? How to plan SIP ?

Here are straightforward & Easy-To-Understand Answers to your questions: Investment in Mutual Funds through SIP route ought to be unbroken invested with for a minimum amount of five years. (If you would like your a refund in but five years, then invest in AAA-rated Fixed-Interest instruments like FDs or NCDs (Non Convertible Debentures etc.) etc.) Always invest in 5-star or 4-star rated open-end investment company Schemes of supposed open-end investment company homes (names explicit in paras below), if you would like your cash to be in safe hands. (For radio frequency ratings, visit: ValueResearchOnline ) Please note, massive and extremely massive corporations (= LargeCap corporations) ar usually thought-about terribly Safe Companies to take a position in. Please note, tiny and extremely tiny corporations (= SmallCap and MicroCap corporations) ar usually thought-about terribly Risky Companies to take a position in. Mid-Size corporations (= MidCap corporations) are usua

Indian Government Websites Directory

Hello Readers!.. In this post I am going to provide you list of some important websites of Government of India. The official directory of all websites by Government of India is available on . Most of this website are made under Digital India initiative by Government of India. So following is the list of some important websites, I will be updating this list periodically. National Portal of India ( ) :  National Portal of India is the Official Portal of the Government of India, designed, developed and hosted by the National Informatics Centre (NIC). This portal is a single window access to the information and services being provided by the Indian Government for citizens and other stakeholders. National Informatics Centre (NIC) Logo (External website that opens in a new window). The content in this Portal is the result of a collaborative effort of various Indian Government Ministries and Departments, at the Central/State/District level. Th

Java Interview Questions and Answers

1) What is the difference between an Abstract class and Interface? Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. An class can implement any number of interfaces, but subclass at most one abstract class. An abstract class can have nonabstract methods. All methods of an interface are abstract. An abstract class can have instance variables. An interface cannot. An abstract class can define constructor. An interface cannot.  An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package). An abstract class inherits from Object and includes methods such as clone() and equals(). 2) What are checked and unchecked exceptions? Java defines two kinds of exceptions : Checked exceptions : Exceptions that inherit from the Exception class are checked exceptions. Client code has