Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all 595 articles
Browse latest View live

Baidu Place API

$
0
0

Overview

The Place API is a simple interface for returning a certain POI data for a region and providing a single POI query service. The user can send requests using C #, C ++, Java and other development languages ​​and receive json, xml data.

Place API has full support for HTTP / HTTPS two forms of request. Subsequent introduction to HTTP request as an example.

Features:-

The Place API provides a regional search for POI services and POI details services.

  1. Area search POI service provides three regional retrieval methods:
    City Search (corresponding to JavaScriptAPI’s Search method)
    Rectangle search (corresponding to the SearchInBound method of the JavaScript API)
    Round area search (corresponding to JavaScript’s SearchNearBy method).
  2. POI Details Service provides detailed information on individual POI inquiries, such as praise.

Instructions for use:-

Use restrictions:

Place API is a free API interface, the number of calls limited to 100,000 times / day.
Ak is the API request string required parameters, please get the key , if not Baidu account first need to register Baidu account.
HTTP / HTTPS requests under the same account, quota, concurrent sharing.

Hello, World example:
The following is a simple example of the place API, set the search city for Beijing, retrieve the keyword “hotel”, retrieve 10 data after the search.
Http : //api.map.baidu.com/place/v2/search?q= Hotel & region = Beijing & output = json & ak = your_key

Place service address:-

Baidu Map Place API Service Address:
Http : //api.map.baidu.com/place/v2/search // v2 place zone search POI service

Http : //api.map.baidu.com/place/v2/detail // v2 POI details service

Composition Description:
Domain name: api.map.baidu.com
Service name
Service version number: v2 version of the new parameters than the previous version.
Place method name: such as search that area POI query, detail that POI details.

Place area to retrieve POI services:-

Service Address:

Http : //api.map.baidu.com/place/v2/search

Place area to retrieve common interface parameters

The following parameters apply to the Place API for the three regional retrieval methods.
baidu-table1

Code Description:

For the query and region parameters, because these two parameters can be Chinese or some special characters (such as: spaces), for example: query can take “snacks”, region can be “Beijing”, in order to avoid submitting to the background garbled , So the two parameters for the value of the encoding process, encoding UTF-8 characters in two characters hexadecimal value. Query and region parameters when the value of the characters are not in the table below to be encoded.baidu-table2

If the query and region parameters are used to preserve the literal characters of the word characters, for example, the query keyword takes the value of “snack”, the search keyword contains a question mark, which must also be encoded, “?” Hexadecimal Is “% 3F”, so the entire search keyword “snack” is encoded as “% 3F% E5% B0% 8F% E5% 90% 83”.

Note:

  1. javascript in general use encodeURIComponent function to encode special characters.
  2. Java can use the function URLEncoder.encode to encode special characters.
  3. C # can use the function HttpUtility.UrlEncode to encode special characters.
  4. php can use the function urlencode to encode special characters.

Place Search example:

Search within the city
Http : //api.map.baidu.com/place/v2/search?query= bank & page_size = 10 & page_num = 0 & scope = 1 & region = Beijing & output = json & ak = {your key}

Rectangle area retrieval
Http : //api.map.baidu.com/place/v2/search?query= food & page_size = 10 & page_num = 0 & scope = 1 & bounds = 39.915,116.404,39.975,116.414 & output = json & ak = {your key}

Circular area retrieval
Http : //api.map.baidu.com/place/v2/search?query= Hotel & page_size = 10 & page_num = 0 & scope = 1 & location = 39.915,116.404 & radius = 2000 & output = json & ak = {your key}

// multiple keywords and cohort search
http : //api.map.baidu.com/place/v2/search?query= hotel $ bank & scope = 2 & output = json & location = 39.915,116.404 & radius = 2000 & filter = sort_name: distance | sort_rule: 1 & ak = {your key}

Place area search method

The Place API provides three types of search methods for cities, rectangles, and circles based on the type of regions that are supported for retrieval. The instructions are as follows:
Retrieve request parameters in the citybaidu-table3

City search example (return json data):

Http : //api.map.baidu.com/place/v2/search?query= Baidu Mansion & region = `Shenzhen & city_limit = true & output = json & ak = {your key}

Rectangle area retrieval parametersbaidu-table4

Rectangle search example (return json data):

Http : //api.map.baidu.com/place/v2/search?query= Bank & bounds = 39.915,116.404,39.975,116.414 & output = json & ak = {your key}

Round area search parameters

Round area search example (return xml data):

baidu-table5

Http : //api.map.baidu.com/place/v2/search?query= Bank & location = 39.915,116.404 & radius = 2000 & output = xml & ak = {your key}

The Place API retrieves the returned result field

Status fieldbaidu-table6

The result field (in the resultset of a data, for example, gray that extended field):

baidu-table7

Place Search Service

Service Address:

Http : //api.map.baidu.com/place/v2/detail
Provides detailed information about a POI point, such as praise, evaluation, etc.

Request Parameter Description:

baidu-table8

The return value is the same as the Place API search return result field.

Service example:

Http : //api.map.baidu.com/place/v2/detail?uid=5a8fb739999a70a54207c130&output=json&scope=2&ak= {your key}

return value:

{ 
    "Status" : 0 , 
    "Message" : "the ok" , 
    "Result" : { 
        "name" : "Baidu building staff canteen" , 
        "LOCATION" : { 
            "LNG" : 116.308022 , 
            "LAT" : 40.056892 
        } , 
        " address " : " Tenth Street (near brilliant international) Haidian District 10 " , 
        " Detail " : 1 , 
        " UID " : " 5a8fb739999a70a54207c130 " , 
        " detail_info " : { 
            " Tag " : " dishes; the other " , 
            " detail_url " : " Http://api.map.baidu.com/place/detail?uid=5a8fb739999a70a54207c130&output=html&source=placeapi_v2 " , 
            " type " : " cater " , 
            " price " : " 11.0 " , 
            " overall_rating " : " 4.0 " , 
            " taste_rating " : " 4.0 " , 
            " service_rating " : " 4.0 " , 
            " environment_rating " : " 4.0 " , 
            " IMAGE_NUM " : " 2 " , 
            " comment_num " : ". 8 " , 
            " shop_hours " : " As early as 9:00 To "8" , 
            "atmosphere" : "" , 
            "featured_service" : "" , 
            "recommendation" : "Mala Tang, grilled fish" , 
            "description" : "Store 
        introduction :" } 
    } 
}

Status code appendix:-

baidu-table9


Google Mobile Vision

$
0
0

Overview

Google provide API for Android and iOS.

  1. Detect Faces
  2. Scan Barcode
  3. Recognize Text

Detect Faces

Face detect API provide you to detect human face automatically in visual media such are digital images or video. The detect faces API provide following functionalities.

Face Recognition: The Google Detect Face API provide only Detect the human face from images or video it does not provide functionalities like recognition of the face.

Face Tracking: By Using Detect Face in a video, it detects faces and tracking them.

Landmark: A landmark is a point within a face. The left-right eye and nose base are example of landmarks

Classification: A face can be classified with to whether eyes are open or closed, a face is smiling or not.
googleMobileVision-image1

Link:

ANDROID: https://developers.google.com/vision/android/detect-faces-tutorial
IOS: https://developers.google.com/vision/ios/detect-faces-tutorial

Scan Barcode

The google provides API for scanning the barcode in real time, on the device in any orientation. The Scan Barcode API also detect multiple barcodes at once. Scan Barcode read the following barcode formats.

  • 1D barcodes: EAN-13, EAN-8, UPC-E, CODE-93, CODE-128, ITF, CODABAR.
  • 2D barcodes: QR CODE, DATA MATRIX PDF-417, AZTEC.

Scan Barcode automatically parses 2D barcodes value, for the following supported formates.

  • URL
  • CONTACT INFORMATION
  • CALENDER EVENT
  • EMAIL
  • PHONE
  • SMS
  • ISBN
  • WIFI
  • GEO LOCATION
  • AAMVA driver license/ID

googleMobileVision-image2

Link:

ANDROID: https://developers.google.com/vision/android/barcodes-overview
IOS: https://developers.google.com/vision/ios/barcodes-overview

Text Recognition

Google provide API for mobile is to Text Recognition.
The Text Recognition is the process of detecting text from image or video. Once text detected, the recognizer then determines the actual text in each block and segment it into lines and words. This API detect text in real time
The google Text Recognition API can recognize text in any Latin base language. This includes

  1. CATALAN
  2. DANISH
  3. DUTCH
  4. ENGLISH
  5. FINNISH
  6. FRENCH
  7. GERMAN
  8. HUNGARIAN
  9. ITALIAN
  10. LATIN
  11. NORWEGIAN
  12. POLISH
  13. PORTUGESE
  14. ROMANIAN
  15. SPANISH
  16. SWEDISH
  17. TAGALOG
  18. TURKISH

Text Structure:

The Text Recognizer segments text into blocks, lines, and words:

  • a Block is a contiguous set of text lines such as a paragraph or column.
  • a Line is a contiguous set of words on the same vertical axis, and
  • a Word is a contiguous set of alphanumeric characters on the same vertical axis.

googleMobileVision-image3

Google WebLight

$
0
0

What is Google WebLight?

Sometimes you have seen (generally in mobile) the website you referred is automatically changed.
The Design or CSS will not work and The responsive site becomes normal but the Text content will remain same These all happens because of the Google convert or Transcode the web page to light Mode.
As per the reports, The Google WebLight saves 80% of data and it will load web page four times faster.

Difference Between Original Page and light Page

Let’s take one Example of Original page and light page

Original Webpage:

URL: http://www.yudiz.com/
In the below Image you can see that the Yudiz’s Main Page
The Site contains Responsive design with better User Interface.

weblight-image1

Light Webpage:

URL: http://googleweblight.com/?lite_url=http://yudiz.com
In the below Image you can see that the Yudiz’s Main Page in Light Mode Responsive Site becomes a normal page. If you want to see the original site then you can simply click on View Original.

weblight-image2

How Google Weblight Works?

Generally, in mobile and in Chrome browser when it detects a slow internet connection, The GoogleWebLight is automatically enabled.
Actually, for faster performance on slow internet connection the Google Weblight compress the JavaScript, Page CSS, and Jquery.
On this simple things Google Weblight Works.

Advantages of Google Weblight:

As we discuss the Google Weblight Saves the 80% data.
Works four times faster than normal.
This is for smartphones but you can also use it in Computers.
Google Weblight doesn’t affect to Google Advertisements.
The User has a 2G or Slow Internet connection and the user looking for only text information can use this feature and saves the Data and Time.

Disadvantages of Google Weblight:

A website that stores cookies that can not be transcoded (In Future that may be transcoded).
As we have seen in the Example of Yudiz’s WebSite, The websites become normal and No better User Interface.

How to show your Original Website?

Sometimes it happens the awesome websites looks ugly in Google Weblight version.
If you want to stop that then you can write following code in PHP.
Add Cache-Control: no-transform to your header file.
By using this code your website never transcodes in Google Weblight.

How to Use Google Weblight in your Computers?

If you are generally looking for the text content on Blogger or on any website at that time you can use Google Weblight in your computer also by the following URL.

http://googleweblight.com/?lite_url=[YOUR_WEBSITE_URL]
For Example:
http://googleweblight.com/?lite_url=http://yudiz.com

UI Design vs UX Design: What is the difference?

$
0
0

Overview

Nowadays, term “UI” (User Interface) and “UX” (User Experience) are being more used and sometimes the user has many complications between them.

So, now below are the simple terms to understand UI (User Interface) and UX (User Experience).

UI is not UX why ?? Go Go Go for touching this complication….

ui-image1

Generally,
UX create interface Useful
UI create interface Mind aesthetically

What is UI (User Interface)?

In simple terms UI (User Interface) is a combination of page layouts, visual elements (like Icons, Call to action buttons) that interact with an interface.

ui-image2

UI – Make connection with User Emotions

What is UX (User Experience)?

On another way, UX (User Experience) is an internal experience, in another term internal process that interacts user to a device.

UX – Make it easier to users to achieve Goals

In an easy term when user is in front of any product, website or application than UI (User Interface design) is a part of any product, website or application that faces the user when he looks at the product, website or application, and the UX(User Experience) is how they feel when the look at any product, website or application.

Procedure for UI & UX

1. Personas & Research

First, UX designer asks the simple list of question to the Client. What he or she exactly wants and who are the target audience.

2. Site Map & User Flow

Site Map and User Flow help designers & clients to think about how the user arrives at the website and where he or she go next. So the designer can design your site knowing where content

3. Wireframing

ui-image3

UX Designer to make a wireframe for the client, so you can save lots of time and inconvenience. So, draw a wireframe in the notebook and take a screenshot for that or use some wireframing tools or wireframes clickable using tools like InVision.

4.Type Scale

Choose a brand color and fonts it’s important, and set simple Type Scale for that and also share Type Scale to your client.

After all, that UI Designer chooses typography and color scheme. Choosing a color scheme is not just a personal preference of UI designer but all these depend on UX Designer Persona.

UI designers construct a visual flow that will provide as a guide to users, and advice them to what we do and when to do it.

Example:
At the current trend and with a simple way Google is the best example for that.

Just logo, search bar and with the 2 buttons, they all reflect as a search page.

ui-image4

but when you type something inside the text box, you got a bulk of information within one sec.

ui-image5

Now, you got the idea with a simple and same layout you got the bulk of knowledge within 10sec. and you observe google in a dramatically different way.

From my point of view, we have questioned why we differentiate them?
My question is what is the difference between Blue paint and chemicals material the paint is made from?

No difference between Blue paint & the chemicals material, because of the combination of both made Blue paint.

For the better design of any product, website or application you need to achieve a combination of Great UX (User Experience) and awesome UI (User Interface).

Custom Notification

$
0
0

A notification is a message or information you can display to the user outside of your Android Application. Notifications can be clicked to perform an action or to open a new activity to indicate that an event has occurred.

Custom Notification is a notification with our own designed UI, through which we can access all different default/custom controls and can interact with all the controls of notification. We can give unique feel to our application through custom notification.

There are two types of views of notification.

  1. Normal View.
  2. Big View.

Steps To Create Custom Notification

Step 1:

Create new project in Android Studio. Create three layouts. First layout with one button to create notification, second layout for displaying Normal View, third layout for displaying Big View as per our need.

Normal Notification layout.
custom-notification-image1

Big Notification layout.
custom-notification-image2

Show Notification layout.
custom-notification-image3

Step 2:

Now after that, We need to use RemoteViews to create and deal with Custom Notification. RemoteViews is a view hierarchy which is displayed in another process.That is inflated from layout resource file, and it provides operations for change content of the inflated hierarchy. In simple terms RemoteViews is used to interact and bind custom layouts with widget and notification. And also used Broadcast to perform action of UI click.

How to set layout and how to access the controls is shown below.

private void setRemoteViews(RemoteViews remoteViews) {

   // set Intent to open app on notification click.
   Intent openAppIntent = new Intent(this, MainActivity.class);

   // call broadcast when any control of notification is clicked.
   Intent closeNotification = new Intent("close_notification");
   Intent playPauseIntent = new Intent("play_pause");
   Intent previousInt = new Intent("previous_intent");
   Intent nextInt = new Intent("next_intent");

   PendingIntent pendingCloseIntent = PendingIntent.getBroadcast(this, 0, closeNotification, PendingIntent.FLAG_UPDATE_CURRENT);
   PendingIntent pendingPlayPauseIntent = PendingIntent.getBroadcast(this, 0, playPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
   PendingIntent pendingPreviousIntent = PendingIntent.getBroadcast(this, 0, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT);
   PendingIntent pendingNextIntent = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
   PendingIntent pendingOpenIntent = PendingIntent.getActivity(this, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);

   // Using RemoteViews to bind custom layouts into Notification
   remoteViews.setOnClickPendingIntent(R.id.notify_player_control_iv_cancel, pendingCloseIntent);
   remoteViews.setOnClickPendingIntent(R.id.custom_notificaiton_rl, pendingOpenIntent);
   remoteViews.setOnClickPendingIntent(R.id.notify_player_control_iv_pause, pendingPlayPauseIntent);
   remoteViews.setOnClickPendingIntent(R.id.notify_player_control_iv_next, pendingNextIntent);
   remoteViews.setOnClickPendingIntent(R.id.notify_player_control_iv_previous, pendingPreviousIntent);
}

BroadcastReceiver to perform action. We need to register this broadcast in application’s manifest and unregister it when activity is destroyed.

private BroadcastReceiver mDeleteReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       notifManager.cancel(100);
   }
};
private BroadcastReceiver mPreviousReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       Toast.makeText(MainActivity.this, "Previous Song", Toast.LENGTH_SHORT).show();
   }
};
private BroadcastReceiver mPlayPauseReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {

       Toast.makeText(MainActivity.this, "Play-Pause Song", Toast.LENGTH_LONG).show();
   }
};
private BroadcastReceiver mNextReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       Toast.makeText(MainActivity.this, "Next Song", Toast.LENGTH_LONG).show();
   }
};

Step 3:

Method to Create Notification.

Normal View is supported in all the version but to take the advantage of Big View of notification the SDK version of device should be jelly_bean or above that. Using NotificationCompat.Builder we will set notification. WE need to set Intent into PendingIntent which is passed as an argument in Notification object.

private NotificationCompat.Builder mBuilder;
private static boolean supportBigNotifications = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
private static boolean supportSmallNotifications = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
private Notification notifyPlayer;
private RemoteViews remoteViews;

private void showCustomNotification() {

   RemoteViews mContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.your_custom_notification);
   Intent intent = new Intent(getApplicationContext(), MainActivity.class);

   if (supportBigNotifications) {
       remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.player_big_notification);
   }

   PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
   // Create Notification.
   mBuilder = new NotificationCompat.Builder(getApplicationContext());
   notifyPlayer = mBuilder.setSmallIcon(R.drawable.movie_image)
           .setContentIntent(pendingIntent)
           .setOngoing(true)
           .build();

// Assign remoteview to notification
   if (supportSmallNotifications) {
       notifyPlayer.contentView = mContentView;
       if (supportBigNotifications) {
           notifyPlayer.bigContentView = remoteViews;
       }
   } else {

       if (supportBigNotifications) {
           notifyPlayer.bigContentView = remoteViews;
       }
   }

// manage clicks of notification
   setRemoteViews(mContentView);
   if (supportBigNotifications) {
       setRemoteViews(remoteViews);
   }
   NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
   mNotificationManager.notify(100, notifyPlayer);

}

Step 4:

Now final step to view notification in notification bar. Call showCustomNotification() on button click. When user will click this button, you will find one notification on your notification bar with different buttons.

findViewById(R.id.btn_show_notify).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
       showCustomNotification();
   }
});

This was the simple and easy way to create notification with custom layout without any user permission.

Everyone is talking about IOT

$
0
0

What is IOT (Internet Of Things)?

The internet of things is a system of interrelation of physical devices, digital machine, objects that are provided with unique identifiers and ability to exchange data over network without requiring human to human and human to computer interaction.

IoT have applications across industries through their unique flexibility and capability to be suitable in any environment. They increase data collection, automation, operations, and much more through smart devices and powerful enabling technology.

IoT is an advanced automation and analytics system which exploits networking, sensing, big data, and artificial intelligence technology to deliver complete systems. These complete systems allow greater transparency, control, and performance when applied to any industry or system.

IoT has become part of every aspect of our lives. Now a day’s applications based on Internet of things are enhancing the comforts of our lives and also giving us more control by simplifying routine work life and personal tasks.

Every device you own and every object you imagine will be connected to the internet. Whether through your smartphone, wearable technology or everyday household objects, the internet of things will connect us in a ways we can’t imagine.

Why IoT has become hottest subject of today?

Dynamic control of industry and daily life
Improve the resource utilization ratio
Provide Better relationship between human and nature
Forming an intellectual entity by integrating human society and physical systems

IOT’s unbelievable Contribution in our life

Some example of IOT in real life implementation are as follow:

1) SMARTER COFFEE

  • Smarter Coffee is a coffee machine that lets you put on the brew from the comfort of your own bed. With the help of iOS and Android app, you’ll be able to make a cup of coffee in seconds after silencing your phone’s alarm.
  • If you don’t want to do manually, you can have Smarter Coffee. It will make you a fresh one at 6:00AM every day, five minutes after you wake up, or whenever you want. It’ll also keep your cup warm for 20 minutes after it’s been made. What an age we live in!

iot-blog-img1

2) AWAIR

  • Awair is an air-quality sensor that send smart phone alerts and recommendations to improve your indoor air quality.
  • Awair tracks toxins in your air and advice to help you keep it clean and safe. Awair tracks many factors of air quality like dust, chemicals, humidity, temperature and CO2. These elements can effect in many ways, including sleep and breathe.
  • Awair is very helpful for asthma or allergies patients.

iot-blog-img2

3) PIPER

  • Piper is all in one home security system
  • The video Monitoring and home automation device lets you stay connected with your home via Piper app.
  • You can view a live HD video of your home. It also includes a clever motion and sound detector to send alert notification when something out of ordinary happens.
  • Piper is also available with many home automation accessories to control lights and other appliances remotely.

iot-blog-img3

“The internet of things has the potential to change the world, just as the internet did, may be even more…”
Keep reading 📖 keep learning ☺

Artificial Intelligence

$
0
0

Artificial intelligence And It’s 4 Hottest Applications

Now a day, people are quite eager to know about artificial intelligence, it has just become a trend to talk about it.

What is AI?

If we take a glance about what AI is, then it is one of the sub-field of computer science. It’s goal is so simple, they are enabling the mechanism to perform the task by the machine which are done by humans in particular, tasks associated with people acting intelligently.

Any Mechanism can be considered AI if it performs something that we would normally think of as intelligent in humans.

This gives us four possible goals to pursue in artificial intelligence:

  • Systems that think like humans->Systems that think rationally.
  • Systems that act like humans->Systems that act rationally.

Why AI is Succeeding today and tomorrow…?

It is arguable that the core technologies of artificial intelligence have not changed drastically. Today’s A.I. engines are quite similar to years’ past A.I. engines. The techniques of yesteryear fell short, not due to inadequate design in the structure, but because of the expectations going high. In short, the major difference between A.I. then and now is that the capacity of computational, data raw volumes are readily available so the technology can really shine.

Incredible applications of AI

Self Driven Vehicle:🚗

Great example of artificial intelligence in everyday life is a self-driving car. It is more convenient to give safety by tragic accidents. Not by programming only, but it can also learn on its own. The more time the machine spends driving, the better it will be at driving. It is done by the same concerns the number of scenarios it encounters and by that we can save life when that critic scenario actually occurs. Human can do mistakes by getting emotional sometimes, but machine doesn’t. Live more safe, more years and enjoy the driving.

ai-image1

Art with Artificial Intelligence:🌠

You might be thinking of what is the concern of AI with Art, right? It’s not your fault because, we tend to think that let the robot do all unpleasant work like help us with household chores, manage routine accounting and reports compiling, control vehicles, etc. At the other hand poetry, literature, music, and art are for people.Is it right?Absolutely. Then you should know about Aaron, a computer program which can paint big colourful awesome painting.

ai-image2

Aaron is programmed in LISP. This application may recognize simple objects and shapes. Mr. Cohen, who is Aaron’s author, taught it how to draw better. The program works as a independent artist.However it is not the algorithms will be more difficult than those of self-driving cars. Scientists believe that this won’t happen soon.

Customer Support in Business:😖

In 21st Century, Entrepreneur became quite aware with experienced problems connected with the human factor. They must like using cognitive customer assistants, Cognicor is the best example. Cognicor provides the service of “users with automated complaint resolution” This is a type of chatbots, virtual assistants that help customers via chatting. Other examples of that are the female assistant Natasha in hike, Slackboot in slack application. It provides the support to user when they needs.

ai-image3

Advantage of AI:

  • A creative technology that is new for clients.
  • Possible to control the communication, programming like set a chatbot according to your requirements: dialogue flow, type of language, etc.
  • Possible to speak to the customer’s language without using the services of a translator.
  • 24×7 customers support with no vacations and sick leaves.

Intelligent shopping:🎁

Those past years online retailers was following the traditional formula —colourful websites, smoother checkout and easier access to credit card info. But this shopping season a growing number of retailers are deploying a new direction to help boost sales: artificial intelligence.

ai-image4

As AI has become more powerful, it can help online shopaholics in three main ways:

  • They are recommending personally to customers as per their tastes which is based on browsing or purchase history.
  • Chatbots to help for how to navigate on online shopping and physical stores.
  • Websites that draw customer behaviour to make them more appealing and feel convenient.

The hottest common use of AI are visual search, they are offering the items which are uploaded and liked by customers and for personalize recommendation.
As we know that Artificial intelligence became the core of today’s technology revolution.More big achievements are still yet to come. There is no wonder if we find more robots than people in the world after few years.Create the world full of intelligence with Artificial intelligence..!!!

Have a good day…!!

Angular 4

$
0
0

Overview

The good news is that Angular 4 is almost exactly the same as Angular 2, from a developer’s point of view. Most of the changes are “in” the framework. Upgrading is as simple as installing the new dependencies
Igor Minar (who works on Angular) requests developers to stop calling it AngularJS,
Angular2 and Angular4. Everything after Angular 1 (which will now be referred to as AngularJS) is simply “Angular“. The versions only denote Angular’s growth over time.

Angular 4 is going to be faster.The Angular team talks about an average 60% reduction in your application size.

Let’s talk about some of the major improvements in the newer version of Angular 4.0

*ngIf and else?

With the new syntax, you can provide an “else” clause. This is a more convenient way to express a conditional.
Here, we wrap our “else” clause in a “ng-template” component – a new component introduced in Angular 4.

using else:

<div *ngIf="isValid;else other_content"> content here ... </div> 
<ng-template #other_content>other content here...</ng-template>

you can also use then else:

<div *ngIf="isValid;then content else other_content">here is ignored</div> 
<ng-template #content>content here...</ng-template> 
<ng-template #other_content>other content here...</ng-template>

or then alone:

<div *ngIf="isValid;then content"></div>
<ng-template #content>content here...</ng-template>

Renderer 2

One of the reasons we all love Angular so much is it’s DOM abstraction capabilities. We don’t need to document.querySelector(‘#id’) anymore. So why should we have to get access to the DOM element when we need to manipulate the UI.
That’s why we use the Renderer service. It’s an abstraction for UI rendering manipulations.

What is Render service: Separate Angular 2 runtime into two layers, application layer and render layer. The application layer only contains APIs and runtime that application code interacts with directly. The rendering layer provides common protocol for performing UI updates. This two layers allow Angular 2 applications to run in different platforms while providing the same set of abstractions to application.

Coming back to the deprecation…

The old Renderer will still work, but it will be removed at some point in the future. it’s recommended that you switch to the new Renderer 2.
Making the switch is as simple as updating the name of the injected component (from Renderer to Renderer2) and updating the names of methods (if the method names have changed).

Angular Universal

The Angular Universal project allows you to render your Angular app server side. If you aren’t familiar with this library you can check out the git repo or this really nice video by Nir Kaufman.

The originally community driven project was taken up by the Angular team and is now up to date with Angular v4.

TypeScript 2.1 and 2.2 compatibility

We’ve updated Angular to a more recent version of TypeScript. This will improve the speed of ngc and you will get better type checking throughout your application

Reduced Size and Improved Performance

The Angular team has made some serious changes to the AOT (Ahead Of Time compilation) engine.

If you don’t already know this, Angular can be rendered in 2 ways –

  1. JIT (Just in time) – the application is compiled in the browser.
  2. AOT (Ahead of time) – the application is compiled beforehand using ngc (angular compiler).

All the Angular documentation and most of the demo apps you’ll find online use JIT.

This means that the application is compiled in your user’s browsers.
What it really means is that your application isn’t as fast as it can be. The weight of the application is higher than it needs to be because –

  1. The download includes the compilation library which accounts for about 50% of the weight of the framework.
  2. The templates are not pre-compiled, which means the browser has to do a lot of work before it can show the user something.

AOT compilation, on the other hand compiles your code before the user gets it. That means that the code –

  1. takes lesser time to download (because the compilation library is not included).
  2. is executed faster (because the browser doesn’t need to spend time compiling the application).

If you want to learn more about how you can add AOT in your application, check out Angular’s docs on AOT.

Upgrading to Angular 4

Allright. So you have decided that you want the potential 60% size reduction in your application and you want to blow your users away with even better load times.

How do you make the move?

The Angular team says that it’s as simple as –
1. Upgrading the Angular dependencies to the latest version.

For Mac

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform
-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save

For Window

Npm install @angular/common@latest @angular/compiler@latest @angular/compiler-
cli@latest@angular/core@latest@angular/forms@latest@angular/http@latest@angular/platform-browser@latest@angular/platform-browser-dynamic@latest@angular/platform-server@latest@angular/router@latest @angular/animations@latest typescript@latest --save

Then run whatever ng serve or npm start command you normally use, and everything should work.

Conclusion

Even though version 4 doesn’t bring any breaking changes, future versions might. It’s best to keep making your app run as fast as possible.

As always console.log(‘happy coding!’);


How to make Custom Field in WordPress?

$
0
0

Overview

By reading the title the first question that arise in our mind is that “What is custom field?” The answer for this is: Custom field is the meta-data which means it is an arbitrary extra related information. Meta-data is the key-value pair. The key is the name which identifies the specific field and that remains same for each post and value is the information for each specific field which varies for each post.

How to create custom fields?

Custom fields are hidden by default if you want to make it visible click on “Screen Options” on the top right corner of the wp-admin then checkmark the custom field checkbox so that it will be visible at the bottom of the page.

Custom-field-1

Many themes or plugins use custom fields for achieving their functionalities. To create new custom field, add name and value in their respective fields and for already created custom field select the name from the drop down and then write value into value field.

Custom-field-2

For example here, I am creating two custom fields “Reading Time” and “Genre”.

Custom-field-3

How to display that custom fields into your page?

To display all the custom fields into your page you need to write:

<?php  the_meta(); ?>

Then the output generated will be as below:

<ul class="post-meta">
    <li><span class="post-meta-key">Reading Time:</span> 10 min</li>
    <li><span class="post-meta-key">Genre:</span> Motivation</li  >
    <li><span class="post-meta-key">slide_template:</span> default</li>
    <li><span class="post-meta-key">title-position:</span> default</li>
    <li><span class="post-meta-key">image-position:</span> default</li>
</ul>

Here first two are the custom fields that I have created and rest of three are theme default.

Custom-field-4

The problem with this method is that it will display all the custom fields and will not allow to display any specific custom field.

To display any specific custom field you need to write:

get_post_meta(int $post_di,string $key = ‘’,bool $single = false)

$key -> Name of the custom field that you want to display

In our example if we want to display only reading time and genre then write the below code:

<?php echo "<span>Reading Time:</span> ".get_post_meta($post->ID,'Reading Time','true'); ?>

<ul class="list-unstyled clearfix">
       <li class="pull-left"><?php echo "<span>Reading Time:</span> ".get_post_meta($post->ID,'Reading Time','true'); ?></li>
       <li class="pull-right"><?php echo "<span>Genre: </span>".get_post_meta($post->ID,'Genre','true'); ?></li>
</ul>

Custom-field-5

Conclusion

I hope that you have enjoyed reading the blog and it might help you in your upcoming project!! Have a great weekend.

Upcoming Software Testing Trends

$
0
0

Overview

As Plato has said that “Necessity is the mother of Invention” he has rightly said the present state of technology. More and more different demands emerge and as a result, so does new technology develop. At our age, meaning at youth, we are best to amalgamate new learning from surroundings. It takes a time to adapt to new things, but if we do not adapt we miss out to be a part of newer and better world. So is the same case with testing industry, Software testing domain is an ever expanding and emerging domain with remarkable changes in the last decade. New technologies are conquered and are disrupting existing technologies. For that reason, Tester got challenges from these changes.

A next generation is coupled with open source tool

The next generation will be proof for a plenty of Open source tools in a deed. In a future Agile model, DevOps, Test and Defect management and test automation will be accepted by more and more company for proper execution. There will be active and involved participation by some of the open source tools.

Amalgamation of quality with speed

Every company and individual will want the best product as time will pass, for the improvement of the company or to be in the remarkable position in the market. In future software testing market will be majorly judged by Quality and time.

Agile and Devops will be KING

According to Forrester, businesses are not focused at centralised Test Center of supremacy. Test automation makers are a part of agile teams. The old testing angle is approaching towards QA engineering and testing is behold to become more iterative, progressive, and will become correctly integrated with development. Even, the development will be such as way how we are testing the application.

Considerable part will be big data testing

We are decked on a pick of a hazardous volume of Big Data now and we need a very strong tactic for Big Data Testing. High analytical tools, approach, and frameworks are being in demand by testing datasets. Big data testing is an area that is expected to become huge.

Growth in IoT (internet of things)

The growth of IoT growing borderline more customers bank on IoT Testing before going to use the products. If the product is not tested for its functionality, security, and performance– it will come below scanner. According to a survey, more than 70% of devices in IoT are accessible to security obstacle.

Changing gear from performance testing to engineering

“A better user experience is needed for the progress of the product”.
A Performance will be consistency across platforms, operating system, and devices depending on how much market value it has, and which totally depends on the user of the product. An urgency to provide the best UX is making businesses to revise their policy. These policies are now converting in Performance engineering and after Performance testing.

Mobile app testing will remain unchanged in Automation testing

Mobile testing will remain unchanged as last year. The pick of test automation trends generates the needs to shift in the mobile devices and technology in businesses. Mobile app testing will be undoubtedly in the top which involves functional, compatibility, performance, usability and security testing as the leading areas. Due to mobile test automation landscape, probabilities of open source framework, Mobile DevOps and apps market will tend to increase.

Merger of developers and QA roles.

The Role of Developers & QA will be assumed to break by the growing consent of DevOps opinion. As the time goes, testing activity will be a part of the daily task for developers and manager like to catch bugs, before it goes to the testing program developer. So be ready, the experts’ estimate that the developers and testers role will blend in upcoming years.

Adoption to Hardware Testing

Mr Jonathon Wright, Director of Hitachi, says that “IoT is all about hardware and not a software. Testing hardware is going to be a change for testers.”

Rise in software testing budget

Clearly the huge focus and need for high-quality product excellence in Information and technology world, testing has become essential than just a need.Raising the demand for Quality product results in increasing IT budget 40-50% for software testing and QA.
As new technologies are coming in software testing world older are override with newer. So be updated with future trends in testing.

Keep reading 📖 keep learning ☺

Foundation 6: An advanced responsive front-end framework over Bootstrap 3

$
0
0

Overview

Nowadays Foundation 6 has been an advanced responsive framework which provides basic grid system, typography, basic form controls, HTML & CSS UI components, etc. In this blog we are going to learn what makes a Foundation 6 an advanced framework and how it differs from Bootstrap 3.

Basic grid system

We all know that what basic grid system is. It consists of 12 units i.e 12 blocks of your screen. It is mostly similar to bootstrap. But now question is how it is different from bootstrap?

No big difference is there. Only class names are different from bootstrap 3. Here is the grid structure for Foundation 6:

.small-* = For Extra small devices (Mobile Phones)
.medium-* = For Medium size devices (Tablets, Laptops,etc.)
.large-* = For Large devices (Large Desktops)

Apply one of the above unit with .columns class for any grid. Here .row is used for fixed width container.

The most amazing things for grids are Incomplete Rows, Centered Columns & Block Grids. Let’s understand them briefly.

foundation-image1

Incomplete Rows:

This is the new concept in Foundation 6. Sometimes we don’t need to use all 12 units of grids. For ex: Suppose we have to use only 9 units of grid. So what we have to do is we just use 3 units from 12 i.e. we have just used .small-3 or .large-3 totally 3 times to make it one row having total width of 9 units.

For this we have to just add .end class in last column. In Foundation 6 every last column of row is right aligned by default for row alignment. Whenever we will add .end class it directly left aligns the specific block with respect to others.

Example:

foundation-image2

Centered Columns:

This topic includes how we will display any grid into center align. Sometimes it is necessary for us to display any grid to center align. If we use any of the grid class it will align either left or right. So what we do is just use any specific unit with centered suffix.

For ex: small-centered, large-centered

Also for non-centered columns for any specific screen just use any specific unit with uncentered suffix.

For ex: small-uncentered, large-uncentered

Block Grids:

In Block grids .column-block class is used which will apply the margin at bottom of the block equal to the width of gutters.

Example:

foundation-image3

Flex Grid

Flex grids are consisting of flexible grids which means no floating grids are there. The flex grids are using display: flex property to set grids side by side from each other.

Note: You can use either normal basic grid system (Floating Grids) or Flex Grid at a time. Just goto Foundation demo download page then from Customize Foundation select Flex Grid and then download custom foundation demo. It will give you only the Flex Grid Structure.

Now the most important topics are: Horizontal Alignment, Vertical Alignment, Source Ordering & Block Grids. Let’s understand each in brief.

Horizontal Alignment:

Here block alignment set as per our requirement. In a bootstrap we can only set text as left , right , center. But here we can also set block. We can use the below class for horizontal alignment:

  1. Align-left
  2. Align-right
  3. Align-center
  4. Align-justify
  5. Align-spaced

foundation-image4

Vertical Alignment:

Here using flex grid we can set blocks vertically as per our requirement. There are equal heights in all blocks. We can give alignment to all blocks. Give some class and set it as we want.

  1. align-middle
  2. align-top
  3. align-bottom
  4. align-self-top
  5. align-self-bottom
  6. align-self-middle

foundation-image5

Source Ordering:

Here if we want to change place of blocks in different screen size then we can change using class and one css property order. Foundation 6 provides this type of advanced functionality.

Example:

Classname{
order: 1;
}

We can set order as per our requirement to show blocks in different screen sizes.For main screen.

foundation-image6

Block change in small device

foundation-image7

Block Grids:

Using Block grids we are able to show number of blocks in particular device. Here are some classes used:

.size-up-n (n=>1 to 9)
Here size is used for any device unit i.e.(small|Medium|Large).

HTML:

<div class="row small-up-1 medium-up-2 large-up-3">
    <div class="column">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor </div>
      <div class="column">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor </div>
      <div class="column">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor </div>
</div>

Example:
For Large Devices:

foundation-image8

For Tablet:

foundation-image9

For Small screen:

foundation-image10

Right to Left Support

Nowadays some websites has multiple language functionality. For normal languages our designs are set properly but what will be done if the current website has Arabic or any other language support which has Right to Left behaviour?

Well no worries about that because our latest framework provides this functionality also. You have to just define lang and dir attributes intag as shown below:

<html class="no-js" lang="ar" dir="rtl">

Cards

This is the new concept in Foundation 6. Cards gives us a very nice visual effect just like some greeting cards. Please check below screenshot for this.

The card has it’s own Header, Content and Footer sections. Now what you have to do is just use them as shown in below code and get pretty cards as shown below:

HTML:

<div class="card">
      <div class="card-divider"></div>
      <img src="images/nature-1.jpg">
      <div class="card-section">
            <h4>Lorem ipsum dolor sit amet</h4>
            <p>Morbi tristique senectus et netus et malesuada fames ac turpis egestas</p>
      </div>
</div>

foundation-image11

Media object

Media Object is generally used to display content and image block side by side with some headings. Here is an example and screenshot for that:

HTML:

<div class="media-object  stack-for-small">
      <div class="media-object-section">
            <div class="thumbnail">
                  <img src="images/graphic.jpg">
            </div>
      </div>
      <div class="media-object-section">
            <h4>Lorem ipsum dolor sit amet</h4>
            <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium dolorem que laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
      </div>
</div>

Example:

foundation-image12

The amazing part is that if we use .stack-for-small class it will stack the blocks like below screenshot in small devices.

foundation-image13

Off-canvas Navigation

Off-canvas navigations are currently in trending. It is outside the viewport and slides when it will be activated. You may also change the position of it i.e. left, right, top or bottom using following classes:

  • .position-left
  • .position-right
  • .position-top
  • .position-bottom

This is the great functionality given by Foundation 6. Isn’t it??? Now let’s check one example for it. Currently we are viewing left Off-canvas navigation.

Example:

<div class="off-canvas position-left" id="offCanvas" data-off-canvas>
    <!-- Your navigation code here -->
</div>
 <div class="off-canvas-content" data-off-canvas-content>
    <!-- Your page content here -->
</div>

foundation-image14

Here position-left class defines the position from where our menu will be slides. This is the container that holds your Off-canvas navigation. Here it is mandatory to define data-off-canvas attribute as your navigation container. Similarly data-off-canvas-content is a container for your page content which will slides to right after left navigation is activated and it is also a mandatory attribute. That’s it.

Conclusion

Here some functionalities are not available in bootstrap 3 and Foundation 6 is an advanced responsive front-end framework which will provide so many new functionalities. Also it is easy to use.

Some feature like Flex Grid, Off-canvas Navigation, RTL Support etc. are extra features and they are easy to use in website design. Also it is less time consuming.

Things to Keep in Mind for iOS 11 App Development – Part 1

$
0
0

Overview

iOS 11 is world’s most advanced mobile OS. It provides most amazing possibilities for AR(Augmented Reality) to the application and some other cool stuffs as well. With iOS 11 iDevices has become much better and more capable than ever.

Drag and Drop

  • This feature mainly focus for an iPad. It moves almost everything magically from one application to another application. It has been designed for large and multi touch displays.
  • For an iPhone it is done within application itself.
  • In tableview, there are two new delegate for drag and drop functionality
    UITableViewDragDelegate
    UITableViewDropDelegate

How to implement in your application?

First need to set delegates:

//Delegate.
tableView.dragDelegate = self
tableView.dragInteractionEnabled = true

How to drag items in UITableView?

UITableViewDragDelegate

//Method will allow to lift and drag item.
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let image = arrImg[indexPath.row]
        let provider = NSItemProvider(object: image as NSItemProviderWriting)
        let item = UIDragItem(itemProvider: provider)
        item.localObject = image
        return [item]
 }

    // Multiple items lift and drag.
func tableView(_ tableView: UITableView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
        let image = arrImg[indexPath.row]
        let provider = NSItemProvider(object: image as NSItemProviderWriting)
        let item = UIDragItem(itemProvider: provider)
        item.localObject = image
        return [item]
}

First Method(itemsForBeginning session), will lift only one item and drag it but by implementing Second Method(itemsForAddingTo session) you can select and drag multiple items.

ios11-image2

UITableViewDropDelegate
First need to set delegate:

//Delegate.
                tableView.dropDelegate = self

 //Method Will Check Drop Items can be Handle or not.
    func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
        return session.canLoadObjects(ofClass: NSString.self)
    }

//Method will allow drop animation and operations.
    func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
        return UITableViewDropProposal(dropOperation: .copy, intent: .automatic)
    }

//Method will performDrop items to particular indexPath.
    func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
        let destinationIndexPath: IndexPath

        if let indexPath = coordinator.destinationIndexPath {
            destinationIndexPath = indexPath
        } else {
            let section = tableView.numberOfSections - 1
            let row = tableView.numberOfRows(inSection: section)
            destinationIndexPath = IndexPath(row: row, section: section)
        }

        coordinator.session.loadObjects(ofClass: NSString.self) { items in
            guard let string = items as? [String] else { return }

            var indexPaths = [IndexPath]()

            for (index, value) in string.enumerated() {
                let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
                self.arrImg.insert(value, at: indexPath.row)
                indexPaths.append(indexPath)
            }
            tableView.insertRows(at: indexPaths, with: .automatic)
        }
    }

  • Here First and Second Methods are optional. First Method(canHandle session), will check table view and can handle drop or not. Second Method(dropSessionDidUpdate session), is used for animation while dropping item and also check for valid drag session.
  • Third Method(performDropWith coordinator), will perform drop of items at particular indexPath.

Swipes Actions

ios11-image3

How to implement to your application?

Two New Methods in UITableViewDelegate.
– (leadingSwipeActionsConfigurationForRowAt indexPath)
– (trailingSwipeActionsConfigurationForRowAt indexPath)

//Method Swipe from left.
    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(style: .normal, title: "Favourite") { (action, view, bool) in
            print("Favourite")
            bool(true)
        }
        action.image =  imageLiteral(resourceName: "favourite")
        action.backgroundColor = UIColor.orange
        let configuration = UISwipeActionsConfiguration(actions: [action])
        return configuration
    }

//Method Swipe from Right.
 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, bool) in
            print("Delete")
            bool(false)
        }
        action.image =  imageLiteral(resourceName: "Delete")
        let configuration = UISwipeActionsConfiguration(actions: [action])
        return configuration
    }

Conclusion

I hope my above blog has helped you to get your hands on iOS 11 Application Development.

Things to Keep in Mind for iOS 11 App Development – Part 2

$
0
0

Overview

In Part 2 of my Blog, you will learn more about some new features released in WWDC 2017 for iOS where I will cover topics like how to use and implement search controller within navigation bar and what’s new in Swift 4 (Swift 4 is in beta so still there’s a lot to come). To learn about Drag and Drop, Swipes Actions and other updates, please refer my previous blog Things to Keep in Mind for iOS 11 App Development – Part 1

Search Controller

Navigation bar now also provides support for searchController.

ios11-search controller

How to implement in your application?

– Declare Variable.

var searchController : UISearchController!

– In viewDidLoad.

self.searchController = UISearchController(searchResultsController: nil)
self.navigationItem.searchController = searchController

What’s new in Swift 4?

Multiline String

  • In previous versions of swift, if you want to move text to a new line developer needs to add `\n’ to break line but now it is no more needed.
  • Now developer can write multiple lines of string by using “”” (three double quotation). Write whole string between “”” and you have your string with multiple lines without using “\n”.

Implementation

let multiLine = """
Yudiz refers to the spirit of youth.
The Google ranking recognizes us as a top mobile app development company, globally.
Example of “Double Quotes” without any escaping.
"""
print("MultiLineString: - \(multiLine)")

Output
MultiLineString: –
Yudiz refers to the spirit of youth.
The Google ranking recognizes us as a top mobile app development company, globally.
Example of “Double Quotes” without any escaping.

String Character

  • Until now, if you want to perform string manipulation, we wrote string.characters.xxx. But now it’s no longer required.

Implementation

let stringCharacters = "HelloWorld!"
for character in stringCharacters {
    print("Individual Character: - \(character)")
}

Output
Individual Character: –
H
e
l
l
o
W
o
r
l
d
!

Swap Array Elements

  • There is a small change that I think you must be aware of it, as you will need this in your app at any point.
  • Swap function takes the two indexes which are to be swapped.

Implementation

var arrNames = ["Kevin","Nishal","Vishal","Ravi","Chirag","Shivam","Mahavir"]
arrNames.swapAt(1, 2)
print("Swap: - \(arrNames)")

Output
Swap: –
[“Kevin”, “Vishal”, “Nishal”, “Ravi”, “Chirag”, “Shivam”, “Mahavir”]

One Side Range

  • Side Range returns number of elements (based on your condition) from array without using loop.

Implementation

var arrNames = ["Kevin","Nishal","Vishal","Ravi","Chirag","Shivam","Mahavir"]
let lessThan = arrNames[..<3]
print("Less than: - \(lessThan)")
let greaterThan = arrNames[3...]
print("Greater than: - \(greaterThan)")

Output
Less than: –
[“Kevin”, “Nishal”, “Vishal”]
Greater than: –
[“Ravi”, “Chirag”, “Shivam”, “Mahavir”]

Create Dictionary using single array

Implementation

let arrNames = ["Kevin","Nishal","Vishal","Ravi","Chirag","Shivam","Mahavir"]
let createDictionary = Dictionary(uniqueKeysWithValues: zip(1..., arrNames))
print("Created Dictionary: - \(createDictionary)")

Output
Created Dictionary: –
[2: “Nishal”, 4: “Ravi”, 5: “Chirag”, 6: “Shivam”, 7: “Mahavir”, 3: “Vishal”, 1: “Kevin”]

Grouping elements of array with key

  • Now grouping dictionary is easier than ever.
  • This feature will be very useful for ‘contacts’ type of app.

Implementation

let arrNames = ["Kevin","Krishna","Nishal","Vishal","Vipul","Ravi","Chirag","Shivam","Mahavir"]
let groupElements = Dictionary(grouping: arrNames, by: { $0.first! })
print("Group Name: - \(groupElements)")

Output
Group Name: –
[“V”: [“Vishal”, “Vipul”],
“N”: [“Nishal”],
“C”: [“Chirag”],
“R”: [“Ravi”],
“K”: [“Kevin”, “Krishna”],
“M”: [“Mahavir”],
“S”: [“Shivam”]]

JSON Encoder and Decoder

  • One of the best feature in Swift 4.
  • In order to use this feature, custom class/struct/enum must be Codable.
  • You can customize behaviour if required.

Implementation

//Define Models
struct Address: Codable {
    var state : String
    var city : String
    var zipCode : String
}

class Person: Codable {
    var name : String
    var address : Address   
    init(name: String,address: Address) {
         self.name = name
         self.address = address
    }
}

//Fill data
let address = Address(state: "Gujarat", city: "Ahmedabad", zipCode: "380061")
let person = Person(name: "Kevin", address: address)

//Encoding and Decoding code
let encoder = JSONEncoder()
if let encode = try? encoder.encode(person) {
    if let json = String(data: encode, encoding: .utf8) {
        print("Json Encoded Data: - \(json)")
    }       
    // Decode
    let decoder = JSONDecoder()
    if let decode = try? decoder.decode(Person.self, from: encode){
        print("Decoded Name: - \(decode.name)")
        print("Decoded Address: - \(decode.address)")
    }
}

Output
Json Encoded Data: –
{
“name”:”Kevin”,
“address”:{
“state”:”Gujarat”,
“city”:”Ahmedabad”,
“zipCode”:”380061″
}
}

Decoded Name: –
Kevin

Decoded Address: –
Address(state: “Gujarat”, city: “Ahmedabad”, zipCode: “380061”)

Conclusion

So that’s it for blog part 2, lets hope for more this type of features and enhancements in final version.
Happy Coding !!

JMeter

$
0
0

Overview

The Apache JMeter is a pure java open source testing software. Firstly, JMeter was developed by Stefano Mazzocchi of the Apache Software Foundation. It is freely available as it is open source. JMeter was designed to do the Performance & Load Testing. It also covers functional & regression testing. JMeter is used for testing the Web Application or FTP Application. JMeter is used for database testing purpose nowadays. JMeter can be used to analyze & measure the performance of Web Application.

For Installation Purpose, it requires JDK 5 or higher. Compatible of running on any environment/workstation that accept JVM (Java Virtual Machine).

Working of JMeter

JMeter merge/combines a group of users that are sending the requests to the destination/target server and returns the results that shows the Performance of the target server/application. Results will be displayed in the form of Charts, Tables, Graphs, Trees or in the form of Log File.
Following Figure will help you to understand the working of JMeter easily.

jmeter-image1

Performance Testing

Performance Testing can be done using JMeter, Load Runner etc. Stress & Load Testing both are the parts of performance testing.

jmeter-image2

Few Elements of JMeter are discussed below

jmeter-image3

1.Thread Group

Collection of Threads is known as Thread Group. Each Thread represents a single user using the application under test.
If you set the number of threads as 1000.JMeter will create and combine 1000 user requests to the server under test.

jmeter-image4

2 Samplers

As we know that JMeter supports testing HTTP, HTTPS, FTP & many other protocols.
Thread Group simulate user requests to the server. The requests can be HTTP Request, FTP Request or JDBC Request etc. That is Samplers.

3. Listeners

Listeners displays the results of the execution of test. They display results in the form of Graphs, Trees, Tables as well in Log File.

jmeter-image5

4. Configuration Elements

CSV DataSet Config
For example, if you want to test a website for 1000 user’s login with different credentials then no need to record the scripts 1000 times. Username & Password will be stored in a text file. JMeter has an element that allows to read the username & password from that text file. It is CSV DataSet Config.

Login Config Element
It is used to simulate single user login. It is suitable for login parameter only.

Performance Testing using JMeter

Step 1: Insert Thread Group

  1. Run JMeter & Select the existing Test Plan.
  2. Then, Insert the Thread Group.
  3. Right Click on Test Plan & Insert a new Thread Group: Add -> Thread(Users) -> Thread Group.

jmeter-image6

Now, Enter Thread Properties in Thread Group as below.

jmeter-image7

Number of Threads- 1000 i.e. 1000 users are connected to the destination website.
Ramp Up Period- Time Delay before starting another user. 1000 users/1000 seconds thus the delay between each user will be 1 sec.
Loop Count- 10 i.e. Single user is connecting the website 10 times.

Step 2: Insert JMeter Elements

Right Click on Thread Group:
Add -> Config Element -> HTTP Request Defaults

jmeter-image8

Enter target server in server name or IP as HTTP runs on 80 port number thus enter 80 as given below.

jmeter-image9

Right Click on Thread Group: Add -> Sampler -> HTTP Request.

jmeter-image10

Example: If you enter calendar in Path Field, It will send URL request http://www.google.com/calendar to the Google Server.

If you put the path field blank, Apache JMeter will send the URL request http://www.google.com to the Google Server.

jmeter-image11

Here, I will put it blank.

Step 3: Insert Listener for viewing the results.

Add -> Listener -> Graph Results

jmeter-image12

You can view the results in the form of Graph, Table, Tree etc. Here I have selected Graph.

jmeter-image13

Step 4: Finally, Execute the Test & get the result

Click on Run & result will be displayed.

jmeter-image14

Throughput should be more & Deviation should be less which shows good performance. Server Performance is said to be good if Throughput is more & Deviation is less.

Database Testing using JMeter

Step 1: Insert Thread Group

  1. Run JMeter & Select the existing Test Plan.
  2. Then, Insert the Thread Group. Right Click on Test Plan & Insert a new Thread Group:
    Add -> Thread(Users) -> Thread Group.

jmeter-image15

Step 2: Insert JDBC Connection Configuration

  1. Right click on Thread Group.
  2. Then, Add -> Config Element -> JDBC Connection Configuration

Now, Add the Details in Database URL as jdbc:mysql://localhost:3306/registration_table where 3306 is port number, registration_table is my database. Add com.mysql.jdbc.Driver in JDBC Driver Class & Add root in Username.

jmeter-image16

Step 3: Insert JDBC Request.

  1. Right Click on Thread Group.
  2. Then, Add -> Sampler -> JDBC Request

Now, you can select any query type. Here, I am selecting Select Statement. Now, enter “select * from customer” where customer is my Table Name in registration_table Database.

jmeter-image17

Step 4: Insert Listeners for viewing the result

In this, I will add 2 Listeners such as View Results in Table, View Results Tree.

  1. Right Click on Thread Group.
  2. Add -> Listener -> View Results Tree.
  3. Again, Add -> Listener -> View Results in Table.

jmeter-image18

Step 5: Run JMeter

It will display the results in form of table as well as in tree.

jmeter-image19

jmeter-image20

Orientation Problem: Media Query (@media) is a Better Way

$
0
0

Overview

In current trend of web design, there is a requirement of responsive view for web layout or mobile first design. There are several framework and tools available in the market for making responsive design, for example bootstrap, zurb-foundation, etc.

But main question is that: “How the design is converted into responsive mode?” And the solution behind this is so simple, that is the use of “media query“. You can also make site responsive without using bootstrap or zurb-foundation, only help with media query.

Media query is type of code which works in stylesheet format and the code which checks viewport and height as well as width of the device where the site is currently running. Based on that you can write css for that view.

Types of media

There are several type of media and which are as below:

  • all – Suitable for all devices.
  • aural – Intended for speech synthesizers.
  • braille – Intended for braille tactile feedback devices.
  • embossed – Intended for paged braille printers.
  • handheld – Intended for handheld devices (typically small screen, monochrome, limited bandwidth).
  • print – Intended for paged, opaque material and for documents viewed on screen in print preview mode. Please consult the section on paged media.
  • projection – Intended for projected presentations, for example projectors or print to transparencies. Please consult the section on paged media.
  • screen – Intended primarily for color computer screens.
  • tty – Intended for media using a fixed-pitch character grid, such as teletypes, terminals, or portable devices with limited display capabilities.
  • tv – Intended for television-type devices.

Media types for web

But we are talking here for web so we take mainly two media type which is used for web and that are, “Print” and “Screen

Print is mainly used for to define look and feel of print format.
Syntax :

@media print { }

Screen is used for to changes layout view in different different device or resolutions.
Syntax :

@media screen { }

For use of the web or specially website structure there are mainly four screen media query condition are used which decide where device is from that resolution or not, and add css regarding that resolution.

For Large device ( Large desktop, large laptop, high resolution monitor )

@media (min-width: 1200px) { }

For Medium device ( desktop, laptop, simplemonitor )

@media (min-width: 992px) and (max-width: 1199px) { }

For Small device ( Tablet)

@media (min-width: 768px) and (max-width: 991px) { }

For Extra Small device ( mobile and Small Tablet, Phablet )

@media (max-width: 767px) { }

The all above media query condition are for specific device width and default view as portrait, for an example if your device is “Iphone 6” than you device width is 375px and height is 667px so for that you have to write css in “Extra Small” device condition.

Orientation

Now, actual question is come when the device is switch in to landscape mode especially for small and Extra Small devices. For that you have to write another media query which contain orientation mode of the device, this media automatically determine mode of the device.

Portrait Orientation:

For Small device

@media (min-width : 768px) and (max-width : 1024px) and (orientation : portrait) { }

For Extra Small device

@media (min-width : 0px) and (max-width : 767px) and (orientation : portrait) { }

Landscape Orientation:

For Small device

@media (min-width : 768px) and (max-width : 1024px) and (orientation : landscape) { }

For Extra Small device

@media (min-width : 0px) and (max-width : 767px) and (orientation : landscape) { }

For an example we take same case above on “iphone 6” the design in iphone portrait and landscape mode both are same because of they both come under the Extra Small device media query. But we want different styling in landscape mode of “iphone 6” so we need to write that style code under landscape mode orientation.

Conclusion

If you have a good hand on html and css so for making changes for responsive view you do not have to add bootstrap or zurb-foundation, you just simply write media query in your pre-written stylesheet and that’s it.


8 Steps To Create Icons

$
0
0

Simple Grid Square

Standard icons starts with a solid base. We just need simple square to start making icons.

create-icon-image1

Start creating your icon sketches using pencil and paper on the square gridded paper that you were using in you school days. You should design icon on square block as most of the icons needs to fit into the square space including icons

For app as well as icons for website, once you start designing the icon leave white space around it so it will be easy to add background when required and it will prevent the icon from getting cut off.

It isn’t necessary that icon drawn will always be in square shape, it can be a little rounded or in a rectangular shape. It should be in center of the grid to maintain equal space. You can use gridlines to draw straight angles for icon or to ascertain position of strokes for the icon.

Start Making With Geometry

Icons are usually small, so it should be created in a way that end user can recognise it by just having the glimpse of it. So mostly the icons are created using geometrical shapes and mostly used shapes are circle, squares and triangles.

Each of these shape is known and simple so they can be combined to create new elements.

create-icon-image2

Look at the icon for audi, It is only base on four circles join together, this icon is very simple and more creative and readable in any of the size. other way of “geometric” we can use the Alphabets, It will glow the brand with uniqueness. LinkedIn is the one of the best example, Icons with Letters.

Make A Special Shape

As we discussed earlier using geometrical shapes are very useful, but you want to create your own shape. It’s really important when you are working for brand specific icons.
Even to create complicated icons, you need to start with basic shapes that also need to be something different. When you are designing some unique icons, follow the below points.

Don’t use images, it doesn’t look good in small icons.
As we told don’t use images, so what about text? Right user can’t see small text.
Of course some movements are valuable, but when you are using flat icons styles it looks like miracle.
Use direct lines with connected points on grid. Curves can go difficult rapidly.
Color icons looks really good but also identify with black and white border.

Give The Spacing

Give appropriate spacing around icons, so that it is readable and identifiable. When you are particularly designing app icons, we need to take care of spacing and it should be placed within the frame for better user experience.

create-icon-image3

Create a uniform border around edge of app icon. Also, fill the area with color which look like unseen.

Maximize The Usage Of Brand Colors

When you are creating icons related to brand then you must stick to your color palette. You may diverge from your brand icon but the color should stay consistent throughout the design. If you are working on bunch of icons then you should start with either black in white or white in black. Then afterwards you can add color relevant to your brand in the later phase. If it looks good with black and white then surely it will look amazing with color.

Make With Consistency

Make sure every detail in the icon design goes perfect. If you cut the angled corner in the design then be consistent with all the corner.

When you design the icons you think that the small details are not much important and will not be visible in small size, it is very important in retina display and HD displays

create-icon-image4

Often designers use the icons in the buttons in whole designs, so icons are more eyecatcher then normal text. When you make the icon be carefull, it will help during making websites.

Design Each And Every Size

Icons should be designed in a way that it can be used at any size. For example favicon icons are uploaded at 32px * 32px. If you have not designed the resizable icon then you should start again with the icon design or else create separate icon for small size, such as favicon icon.

create-icon-image5

Not Make Embellish

Finally, keep your icon design simple. Hold out against your wishes to decorate the design. Still, some of the nicest apps looks imperfect with the bad icon design.

create-icon-image6

Decoration in icons doesn’t look good always (for e.g. adding an image in place of icon will look messy in design)

How Typefaces & its Pairing important in Design Process ?

$
0
0

`

Overview

Not only color palette but selecting typefaces play an important role to create look and feel of your design. Once selected, pairing typefaces come into the scene. Pairing right fonts for your design makes it attractive and appealing.

Typeface Categories

There are 4 main categories:

  1. Serif
  2. Sans Serif
  3. Decorative
  4. Script

1) Serif

A small decorative flourish at the end of the stroke of a character or letter is known as serif. Serif fonts are easier to read in print than sans-serif. Serif fonts are almost bracketed but not all. Garamond, Abril Fatface, etc. are serif fonts.

Usages:

  1. In Print: Serif fonts are commonly used in print such as magazines, books, etc. as they are readable and legible.
  2. In Web: Serif fonts are worthwhile in headings, main body heading, and documents which are purposely used for print.

Classification:

  1. Old Style: It is the style inspired by Renaissance calligraphy to replace Blackletter style of type. It normally has left leaning curve axis with weight stress at about 8’o clock and 2’o clock. e.g. Garamondtypeface-old-style
  2. Transitional: Emerged in the mid-18th century, these are the fonts that represent a transition between old and didone fonts. They have a contrast between thin and thick strokes and strokes have vertical stress. e.g. Baskerville, Times New Roman,etc.typeface-transitional
  3. Didone(or Modern): Emerged in late 18th century, these are the fonts that have greater contrast between thin and thick strokes and strokes have vertical stress plus a ‘ball’ shaped curve. e.g Bodoni, Playfair Display, etc.typeface-modern
  4. Slab Serif: Gained popularity in the 19th century, these fonts have less variation or difference in stroke width. Strokes are rectangular in shape. Often used for posters and in small print. e.g Rockwell Fonttypeface-slab

2) Sans Serif

Characters or letters that don’t have a stroke at the end are known as sans-serif.’ Sans ‘ means without. Sans serif fonts emit simplicity, modernity, and minimalism. Helvetica, Futura, etc. are sans-serif fonts.

Usages:

  1. In Print: Sans serif fonts are used in newspaper headlines, photo captions, etc.
  2. In Web: Sans serif fonts are worthwhile in headings and normal text.

Classification:

  1. Grotesque: Emerged in early 19th century, represents the first design of sans serif. The strokes appear to be squarish bowls in design. ‘g’ letter usually has a loop in it while ‘R’ has curved leg and ‘G’ is usually spurred. Cap height and ascender height of letters are generally same. e.g Franklin Gothictypeface-grotesque
  2. Neo-Grotesque: Neo-grotesque a.k.a transitional sans serif came after grotesque.They are simple in appearance and has limited width variation. These fonts are easier to use for body text. e.g. Helvetica.typeface-neo-grotesque
  3. Humanistic: Humanistic fonts are a mixture of Roman inscriptional letters and calligraphy. These fonts have higher variation in strokes, are clear and easily read. e.g. Frutigertypeface-humanistic
  4. Geometric: As the name says these fonts are based on geometric shapes. Emerged in 1920 Jakob Erbar was the first geometric typeface. Recent typefaces include Avenir, Gotham, etc.typeface-geometric

3) Decorative

Fonts that are decorative in nature and are eye-catching fonts. Avengeance Mightiest Avenger, Badaboom, etc. are decorative fonts.

Usage:
Mostly used in large headings in posters, sign boards, etc. to attract the attention of the user.

typeface-decorative

4) Script

Fonts that imitate historical or modern handwriting are script fonts. Playlist Script, Carolina Mountains, etc. are script fonts

Usage:
Mostly used in invitations and greeting cards.

typeface-script

Pairing

1) Concordance or similarity:

The design is concordant when you use single typeface over the entire project. If your design is simple you can opt for this pairing. As these fonts belong to the same family they share same characteristics which go well together. For e.g you use bold font for heading, medium font for sub-heading and regular font for normal text. Some of the typefaces are Futura, Corporative, etc.

A superfamily can contain both serif and sans serif typefaces. For e.g Droid contains Droid Sans, Droid Serif, and Droid Sans Mono.

typeface-concordance

2) Contrast:

A contrasting design is when you pair two different typefaces that are different from each other .i.e. combining serif and sans serif typeface. A simple trick for this is to use serif for heading and sans serif for body text or vice versa. Good usage of contrast makes your design eye-appealing.

Below are some points to look upon

  1. Styles: Using fonts with different styles makes your design looks good. for e.g. using a condensed style for heading and italic for text.
  2. x-height and width: x-height is the height of lowercase x and width is the wideness of a character.
  3. Weight: Using different weights of a typeface is used to establish visual hierarchy.
  4. Form or shape of a character: Look at ‘o’ in more than one font. Some ‘o’ are of geometric shape, some are rounded, some are condensed, etc.
  5. Color: Some colors suit well in contrast while some don’t.

typeface-contrast

3) Conflict

Conflict design arises when two different fonts have almost same similarities.To avoid conflict use different typefaces that match with each other and maintain the hierarchy.
In the below image you can identify it by looking at character ‘e’ as both the fonts are Geometric sans serif type.

typeface-conflict

Conclusion

I hope this blog has given you some idea about how to pair right typefaces for your design. It all depends on your concept. There are many typefaces available on the web and are increasing too, just try to pair typefaces that matches with your design. General suggestion is not to go with more than 3 typefaces in your design.

What’s gonna be Android’s next dessert –‘Oreo’ or ‘Oatmeal Cookie’?

$
0
0

Overview

Android Nougat is still struggling to increase its presence on Android distribution chart, but developers at Google are now starting to think about the next version of Android after Nougat. As we all know, Google is following an alphabetical dessert naming order for its Android versions. After Android Nougat, the next version is Android O and as per a new tweet by one of Google’s employee, it could be named as Android Oreo.

A tweet by Hiroshi Lockheimer, SVP of Android, Chrome OS and Play contains a GIF of Oreo cake, which is being treated as a hint. Every year, Google unleashed the name of the Android version in March, and for Android 8.0 too, we will know the final name in the beginning of next month. It is worth pointing out that nothing has been confirmed by Google yet, and there could be a fair chance that Lockheimer tweet could just be a tease with no solid backing.

android8-image1

android8-image2

Expected features

Integrated Google launcher and Assistant

Android O will probably integrate the Google launcher and Assistant directly into the core code. This will enable users to experience the power of both launcher and assistance. Moreover, the handsets shipped with Android O will be able to compete directly with Apple because iPhone has Siri voice assistant.

Improved desktop management tools

You can expect Google to provide improved tools for desktop management. If you look at Samsung or LG, they have their own tools for the management of files and backup. Google needs to reinvent the wheel and develop a tool for customers.

Monthly patches for added security

With the arrival of Android O, you can expect monthly patches, which will most likely address security exploits. Google needs to identify the mechanism by which the phone boots including the possible changes which will occur when critical system files are changed.

How to use filter property of CSS3?

$
0
0

Overview

The filter property is used to add visual effect to any element. Its default value is none. You can use multiple filters for any element separated by space.

Browser Support: It is fully supported in first version mentioned in the below table:

filter-browsersupport

Blur

It is used to apply blur effect to any element.

For example:
HTML:

<div class="block">
     <h3>Blur</h3>
     <img alt="" src="image.jpg" width="400">
</div>

CSS:

.block       { margin: 60px; padding: 20px; background: #fff; box-shadow: 0 0 5px #000; display: inline-block; }
h3           { margin: 0 0 15px; padding-bottom: 5px; font-size: 22px; border-bottom: 1px solid #000; }
.block img   { filter: blur(5px); -webkit-filter: blur(5px); }

filter1

Brightness

It is used to apply brightness to any element. When we set it to 0 then whole element will turn out to be black and default value is 1 or 100% which is the original element.

For Example:
CSS:

.block img { filter: brightness(50%); -webkit-filter: brightness(50%); }

filter2

Contrast

It is used to adjust the contrast level of the element. When we set it to 0 then whole element will turn out to be gray and default value is 1 or 100% which is the original element.

For example:
CSS:

.block img { filter: contrast(150%); -webkit-filter: contrast(150%); }

filter3

Drop Shadow

It applies drop shadow effect to the element similar to box-shadow property. Unlike box-shadow property, it is applied to actual outline of the object. Syntax for drop-shadow as below:
Drop shadow: h-shadow v-shadow blur spread color

Here,
h-shadow(required): It represents the value of horizontal shadow. Negative value can be used and if it is used as shadow, it will be shown to the left of the element.

v-shadow(required): It represents the value of vertical shadow. Similarly to h-shadow, negative values can be used here too but it will display shadow on the top of the element.

blur(optional): This adds blur effect to the shadow.

spread(optional): It is generally used to expand the shadow but as many browser does not support so it is better to avoid its usage.

color(optional): It is used to specify the color of the shadow. If it is not specified it will render the default color based on the browser but mostly it is black.

For example:
CSS:

.block img { filter: drop-shadow(-8px 12px 2px #ddd); -webkit-filter: drop-shadow(-8px 12px 2px #ddd); }

filter4

Gray Scale

This is used to convert the element into grayscale. When it is set to 0, it displays the original element and when it is set to 100% then it will display element with gray effect. Negative values are not allowed.

For example:
CSS:

.block img { filter: grayscale(100%); -webkit-filter: grayscale(100%); }

filter5

Hue Rotate

It is used to apply hue rotation on the image. The value is specified in deg and maximum value is 360deg. When value is set to 0, the image remains unchanged.

For example:
CSS:

.block img { filter: hue-rotate(150deg); -webkit-filter: hue-rotate(150deg); }

filter6

Invert

It inverts the sample in the image. When it is set to 100% then image will be completely inverted and when it is set to 0 then image will remain unchanged.
Negative values are not allowed.

For example:
CSS:

.block img { filter: invert(100%); -webkit-filter: invert(100%); }

filter7

Opacity

It applies opacity level to the element and it is similar to opacity css property. It also does not accept negative value. When set to 0, then it changes to completely transparent.

For example:
CSS:

.block img { filter: opacity(50%); -webkit-filter: opacity(50%);}

filter8

Saturate

This property saturates the image. Negative values are not allowed. When set to 0, then image is completely saturated.

For example:
CSS:

.block img { filter: saturate(60%); -webkit-filter: saturate(60%); }

filter9

Sepia

It converts the element into sepia. Negative values are not allowed. Default value is 0 which represents the original image and 100% will change the image completely to sepia.

For example:
CSS:

.block img { filter: sepia(80%); -webkit-filter: sepia(80%); }

filter10

Url

This takes the location of the xml file that specifies the svg filter and may include the anchor to specific filter.

For example:
HTML:
Add the below code to body of above HTML

<svg>
    <filter id="blur">
        <feGaussianBlur stdDeviation="2" />
    </filter>
</svg>

CSS:

.block img { filter: url(#blur); -webkit-filter: url(#blur);  }

filter11

Conclusion

I hope this blog might help you in having clear idea about the filter property of CSS3.

Encoding and Decoding Custom Types with Swift 4

$
0
0

Overview

Swift 4 comes with the new ideas for encoding and decoding custom types using the new protocol named Codable. Yes, one word for two Protocols Encodable and Decodable.

Using codable we can generate and parse JSON or any other external representations. Codable protocol use to perform both encoding and decoding from and to – JSON by declaring conformance to Codable. Codable have mainly two protocols Encodable and Decodable, which are used to encode and decode our data. This process is known as making our types codable.

Let’s take an example of Company JSON as follows:

{
  "id": "1",
   "name": "Yudiz Solutions Pvt. Ltd",
   "contactNo": “0123456789”,
   "address": "Ahmedabad"
}

So our Swift structure for above JSON should look like this:

class CompanyModel: Codable {

   var id: String
   var name: String
   var address: String
   var contactNo: String

   init(id: String, name: String, address: String, contactNo: String) {
       self.id = id
       self.name = name
       self.address = address
       self.contactNo = contactNo
  }
}

As discussed above, now we would know that Codable is union type including Encodable and Decodable and satisfied all requirements. So now we don’t have to worry about the bidirectional process of conversion by choosing suitable protocol as per requirements. Swift 4 makes conversion very simple by this feature.

Codable comes with a default implementation, and by using this we get useful default behaviour.

Now, Create one object of above class and encode as follow:

let company = CompanyModel(id: "1", name: "Yudiz Solutions Pvt. Ltd.", address: "Ahmedabad, Gujarat", contactNo: "+917965130111")

       // Encoding
       let jsonEncoder = JSONEncoder()
       if let encodedData = try? jsonEncoder.encode(company) {
           if let json = String(data: encodedData, encoding: .utf8) {
               print("Encoded Json: \(json)")
           }

           // Decoding
           let decoder = JSONDecoder()
           if let decodedData = try? decoder.decode(CompanyModel.self, from: encodedData) {
               print("Decoded Data")
               print("Name - \(decodedData.name)")
               print("Address - \(decodedData.address)")
               print("contactNo - \(decodedData.contactNo)")
           }
       }

Output should be look like this:

Encoded Json:

{"id":"1","contactNo":"+917965130111","name":"Yudiz Solutions Pvt. Ltd.","address":"Ahmedabad, Gujarat"}

Decoded Data:
Name – Yudiz Solutions Pvt. Ltd.
Address – Ahmedabad, Gujarat
contactNo – +917965130111

Done!!
For decoding JSON and encoding JSON, this code works great if key names and types are same in both, because there is no need for customization. But what about if keys and types are not same??

Now we take a scenario in which key names and types are different. For that, we will do Customization and Customise key names using CodingKeys protocol.

Customise Key Names using CodingKey protocol:

If the API’s uses different naming keys, and that style not matched with our swift naming guideline, provide alternate keys by adding a nested enumeration named CodingKeys that conforms to the CodingKey protocol, which is used to connect a property to a value in the encoded format.This lets you to name your data structures according to the Swift API Design Guidelines rather than having to match the names, punctuation, and capitalization of the serialisation format that you are modelling.

class CompanyModel : Codable {
     // ...
    enum CodingKeys: String, CodingKey {
       case id
       case name = "company_name"
       case address = "company_address"
       case contactNo = "phone_number"
   }
}

Now our json output as follow:
Encoded Json:

{"company_name":"Yudiz Solutions Pvt. Ltd.","id":"1","phone_number":"+917965130111","company_address":"Ahmedabad, Gujarat"}

We can also format output of JSON by customising output formatting of the JSONEncoder to make it a better human readable form using outputFormatting property. The default value of this property is .compact, we can change it as per our requirement.

jsonEncoder.outputFormatting = .prettyPrinted

Now output looks like this:
Encoded JSON:

{
 "company_name" : "Yudiz Solutions Pvt. Ltd.",
 "id" : "1",
 "phone_number" : "+917965130111",
 "company_address" : "Ahmedabad, Gujarat"
}

Custom encoding and decoding:

If the class structure of your swift file different from its encoded form, we can do custom encoding and decoding by providing a custom implementation of the Encodable and Decodable protocol. In other words, If you want more control over encoding and decoding, you can customise by using inbuilt methods of the Encodable and Decodable protocol.

Let’s take one example of JSON which we want to encode and decode from:

{
   "id": "1",
   "name": "Yudiz Solutions Pvt. Ltd",
   "contactNo": "0123456789",
   "address": {
       "street": "Corporate Road",
       "area": "Prahladnagar",
       "city": "Ahmedabad",
       "zipcode": "380015"
   }
}

For this we can create a simple class which extends Codabale protocol as follow:

class CompanyModel: Codable {

   var id: String
   var name: String
   var contactNo: String
   var street: String
   var area: String
   var city: String
   var zipcode: String

   // Coding Keys
   enum CodingKeys: String, CodingKey {
       case id
       case name = "company_name"
       case address
       case contactNo = "phone_number"
   }

   enum AddressKeys: String, CodingKey {
       case street
       case area
       case city
       case zipcode
   }
}

For a custom implementation of encoding, we implement encode(to encoder:) and for decoding init(from decoder:) methods of Codable protocol to have more control over how the JSON maps to our basic types.

For custom encoding, we need to take the encoder, get a container and encode our JSON values to it. A container has some types as per requirement of our JSON. Following are the types of container:
Keyed Container – It provides the actual values for keys which comes in JSON.
Unkeyed Container – Unkeyed Container gives you ordered values without keys. In the JSONEncoder, this means an array.
Single Value Container – this outputs the raw value without any kind of containing the element.
In order to encode any of our properties, we’ll first need to get a container. Looking at the JSON structure we started with at the top of this post, it’s clear we need a keyed container.

Follow how we encode our JSON into container:

func encode(to encoder: Encoder) throws {
       var container = encoder.container(keyedBy: CodingKeys.self)
       try container.encode(id, forKey: .id)
       try container.encode(name, forKey: .name)
       try container.encode(contactNo, forKey: .contactNo)

       var addressInfo = container.nestedContainer(keyedBy: AddressKeys.self, forKey: .address)
       try addressInfo.encode(street, forKey: .street)
       try addressInfo.encode(area, forKey: .area)
       try addressInfo.encode(city, forKey: .city)
       try addressInfo.encode(zipcode, forKey: .zipcode)
   }

Now we need to decode encoded values for that we use the decoder. We can decode all basic types of swift but we need to specify the type while decoding any object otherwise it throws DecodingError.TypeMismatch error and we can handle it.

required init(from decoder: Decoder) throws {
       let allValues = try decoder.container(keyedBy: CodingKeys.self)
       id = try allValues.decode(String.self, forKey: .id)
       name = try allValues.decode(String.self, forKey: .name)
       contactNo = try allValues.decode(String.self, forKey: .contactNo)

       let addressInfo = try allValues.nestedContainer(keyedBy: AddressKeys.self, forKey: .address)
       street = try addressInfo.decode(String.self, forKey: .street)
       area = try addressInfo.decode(String.self, forKey: .area)
       city = try addressInfo.decode(String.self, forKey: .city)
       zipcode = try addressInfo.decode(String.self, forKey: .zipcode)
   }

We can use these encoding and decoding as follow:

let jsonString = """
       {
           "id": "1",
           "company_name": "Yudiz Solutions Pvt. Ltd",
           "phone_number": "0123456789",
           "address": {
               "street": "Corporate Road",
               "area": "Prahladnagar",
               "city": "Ahmedabad",
               "zipcode": "380015"
           }
       }
       """

if let jsonData = jsonString.data(using: .utf8) {
           do {
               let decodedData = try JSONDecoder().decode(CompanyModel.self, from: jsonData)
               print(decodedData.name)
               print(decodedData.contactNo)
               print(decodedData.street)
               print(decodedData.area)
               print(decodedData.city)
               print(decodedData.zipcode)


              let jsonEncoder = JSONEncoder()
               jsonEncoder.outputFormatting = .prettyPrinted
               let encodedJson = try jsonEncoder.encode(decodedData)
               if let json = String(data: encodedJson, encoding: .utf8) {
                   print("Encoded json: \(json)")
               }
           } catch {
               print(error.localizedDescription)
           }
       }

Since the JSON parsing depends on the names of its properties, so you cannot rename them otherwise you have to change the JSON also. You can test that by changing any property and you can see that through breaking JSON encoding/decoding.

That’s all for now! But in future posts, we’ll be looking at Codable again, including handling exceptions generated by encoding/decoding, Dynamic coding keys, handling dates and float values.

For more references:
API Collection Encoding, Decoding, and Serialization
WWDC 2017 – Session 212

Viewing all 595 articles
Browse latest View live