Wednesday 22 August 2018

CircularProgressBar - Android

Custom Circular Progress Bar

package com.example.macbook.spinner;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int pStatus = 0;
    private Handler handler = new Handler();
    TextView tv;
    CircularProgressBar circularProgressBar;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        circularProgressBar = (CircularProgressBar) findViewById(R.id.circularProgress);
        circularProgressBar.setProgressColor(Color.BLUE);

        tv = (TextView) findViewById(R.id.tv);
        new Thread(new Runnable() {

            @Override            public void run() {
                // TODO Auto-generated method stub                while (pStatus < 100) {
                    pStatus += 1;

                    handler.post(new Runnable() {

                        @Override                        public void run() {
                            // TODO Auto-generated method stub                            circularProgressBar.setProgress(pStatus);
                            if(pStatus>70){
                                circularProgressBar.setProgressColor(Color.RED);
                            }else{
                                circularProgressBar.setProgressColor(Color.BLUE);
                            }
                            tv.setText(pStatus + "%");

                        }
                    });
                    try {
                        // Sleep for 200 milliseconds.                        // Just to display the progress slowly                        Thread.sleep(30); //thread will take approx 1.5 seconds to finish                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:tools="http://schemas.android.com/tools"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#FFFFFF"        tools:context="com.example.parsaniahardik.progressanimation.MainActivity">

        <com.example.macbook.spinner.CircularProgressBar            android:id="@+id/circularProgress"            android:layout_width="180dp"            android:layout_marginLeft="10dp"            android:layout_centerInParent="true"            android:layout_height="180dp"            />

        <TextView            android:visibility="visible"            android:id="@+id/tv"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:gravity="center"            android:text="25%"            android:layout_centerInParent="true"            android:textColor="@color/colorPrimaryDark"            android:textSize="20sp" />

    </RelativeLayout>



</android.support.constraint.ConstraintLayout>

CircularProgressBar.java

package com.example.macbook.spinner;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;


public class CircularProgressBar extends View {

    private int mViewWidth;
    private int mViewHeight;

    private final float mStartAngle = -90;      // Always start from top (default is: "3 o'clock on a watch.")    private float mSweepAngle = 0;              // How long to sweep from mStartAngle    private float mSweepFinisher = 0;
    private float mMaxSweepAngle = 360;         // Max degrees to sweep = full circle    private int mStrokeWidth = 40;              // Width of outline    private int mAnimationDuration = 400;       // Animation duration for progress change    private int mMaxProgress = 100;             // Max progress to use    private boolean mDrawText = true;           // Set to true if progress text should be drawn    private boolean mRoundedCorners = true;     // Set to true if rounded corners should be applied to outline ends    private int mProgressColor = Color.BLACK;   // Outline color    private int mTextColor = Color.BLACK;       // Progress text color
    private final Paint mPaint;                 // Allocate paint outside onDraw to avoid unnecessary object creation
    public CircularProgressBar(Context context) {
        this(context, null);
    }

    public CircularProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircularProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        initMeasurments();
        drawOutlineArc(canvas);

//        if (mDrawText) {//            drawText(canvas);//        }    }

    private void initMeasurments() {
        mViewWidth = getWidth();
        mViewHeight = getHeight();
    }

    private void drawOutlineArc(Canvas canvas) {

        final int diameter = Math.min(mViewWidth, mViewHeight) - (mStrokeWidth);

        //Draw background        mPaint.setColor(Color.GRAY);
        final RectF outerOval = new RectF(mStrokeWidth, mStrokeWidth, diameter, diameter);
        canvas.drawArc(outerOval, -90, 360, false, mPaint);

        mPaint.setColor(mProgressColor);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeCap(Paint.Cap.BUTT);
        mPaint.setStyle(Paint.Style.STROKE);
        if(mSweepAngle!=360) {
            canvas.drawArc(outerOval, mStartAngle, mSweepAngle - 5, false, mPaint);
        }else{
            canvas.drawArc(outerOval, mStartAngle, mSweepAngle, false, mPaint);
        }
            mPaint.setColor(mProgressColor);
            mPaint.setStrokeWidth(mStrokeWidth);
            mPaint.setAntiAlias(true);
            mPaint.setStrokeCap(mRoundedCorners ? Paint.Cap.ROUND : Paint.Cap.BUTT);
            mPaint.setStyle(Paint.Style.STROKE);
            canvas.drawArc(outerOval, mStartAngle+5, mSweepAngle-8, false, mPaint);

    }

//    private void drawText(Canvas canvas) {//        mPaint.setTextSize(Math.min(mViewWidth, mViewHeight) / 5f);//        mPaint.setTextAlign(Paint.Align.CENTER);//        mPaint.setStrokeWidth(0);//        mPaint.setColor(mTextColor);////        // Center text//        int xPos = (canvas.getWidth() / 2);//        int yPos = (int) ((canvas.getHeight() / 2) - ((mPaint.descent() + mPaint.ascent()) / 2)) ;////        canvas.drawText(calcProgressFromSweepAngle(mSweepAngle) + "%", xPos, yPos, mPaint);//    }
    private float calcSweepAngleFromProgress(int progress) {
        return (mMaxSweepAngle / mMaxProgress) * progress;
    }

    private int calcProgressFromSweepAngle(float sweepAngle) {
        return (int) ((sweepAngle * mMaxProgress) / mMaxSweepAngle);
    }

    /**     * Set progress of the circular progress bar.     * @param progress progress between 0 and 100.     */    public void setProgress(int progress) {
        ValueAnimator animator = ValueAnimator.ofFloat(mSweepAngle, calcSweepAngleFromProgress(progress));
        animator.setInterpolator(new DecelerateInterpolator());
        animator.setDuration(mAnimationDuration);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mSweepAngle = (float) valueAnimator.getAnimatedValue();
                invalidate();
            }
        });
        animator.start();
    }

    public void setProgressColor(int color) {
        mProgressColor = color;
        invalidate();
    }

    public void setProgressWidth(int width) {
        mStrokeWidth = width;
        invalidate();
    }

    public void setTextColor(int color) {
        mTextColor = color;
        invalidate();
    }

    public void showProgressText(boolean show) {
        mDrawText = show;
        invalidate();
    }

    /**     * Toggle this if you don't want rounded corners on progress bar.     * Default is true.     * @param roundedCorners true if you want rounded corners of false otherwise.     */    public void useRoundedCorners(boolean roundedCorners) {
        mRoundedCorners = roundedCorners;
        invalidate();
    }
}

OutPut




Monday 1 January 2018

Natural Language Toolkit (NLTK) python setup for Window

How to install/configure NLTK with window system. You can follow below steps :

First of check which Python version has been installed



If you couldn't configured yet, then you can download (https://www.python.org/downloads) & install first from given path.

Let's start installation process. Let install dumpy using following command



Then, install NLTK using following command



Now, download NLTK packages using below command

>>> import nltk



Once you fire download command then it will open a installer dialog from where you have to select your packages to install. You can select all to download all package.




Once download complete. It will show like this



Once installed all packages then you click on close to return to the command prompt.

prompt will show true

Now, you can verify whether it's successfully install or not.



Yeah! It's work great!. You can post your query or installing issue!

Wednesday 27 December 2017

FireChat

The quick answer, YES, Firebase is the best and safest option for the majority of cases users will need it. Is FireChat the best chat API to use for chat? Maybe but I wouldn’t recommend any of those APIs.
I work for a bespoke app development company which specialises in instant chat, we use Firebase for many of our projects. Below I will put some of the advantages and disadvantages of FireChat, then I will add some additional points of the best implementation I see when using chat.
NOTE: Other services will include many of the same advantages and disadvantages, this answer will be trying to show that Firebase is better overall based on its strengths. I disagree that the other services you have mentioned are useless. In my experience they have all been excellent (great developers, documentation etc) but Firebase is exceptional.
Advantages of FireChat
  • Cost: As you mention in your question Firebase is great for starting developers. You can get a good level of users on your app before needing to start paying for the service. This level has been set well to mean that once you start paying you have enough users to be monetising your app.
  • Support: Firebase offer great support and also have a huge community to offer support for them. Due to the size and scale of their company Firebase is widely used. This means if you have problems there is a good chance others have found and solved it already, if not then there are lots of people willing to help on StackOverflow and other forums.
  • Documentation: Firebase has a huge and excellently written documentation base. Their documentation is also extremely complete spreading across almost every feature or function you might want to implement.
  • Security: Security is on both lists. Security is easy to set up and understand on your Firebase database. The fact they give you the freedom to set and modify is a real strength. This enables you to customise your functionality very well to your specific app.
  • Speed: Firebase is super quick which is a very important feature for a real time chat.
  • Quality: The Firebase code is extremely well written and excellently tested. In the 4 years I have been working with Firebase I have yet to find a bug with their provided code.
Disadvantages of FireChat:
  • Searching: Firebase is very bad for apps which require an accurate search. Basic search is possible but is not particularly sensitive or quick. If you need to search for characters stored in your database then you either need to write some tricky/slow code or need to use another framework for search (RIP Parse which had excellent search queries)
  • Push notifications: Firebase does have push notifications but these require a custom server. This is a shame as an in house feature would be incredibly convenient.
  • Data storage: Firebase is not the best database for storing large data files. It deals with text great but if you need to be uploading large images/videos regularly then there are probably better services you could use.
  • Security: Firebase is secure but not bullet proof. If your data is highly sensitive then it is worth having a service which specialises in data security.
From the points above you should be able to see that Firebase is a great product with its main disadvantages being in very specific areas. These might affect you depending on your project but can often be fixed with other frameworks.
I would argue that using an API for chat is itself very limiting. In this sense using FireChat is just as bad as using any of those other listed APIs. Below I have listed some of the main disadvantages I see of using any chat API:
Advantages of using Firebase for chat but not FireChat:
  • Flexibility: Firebase is extremely flexible, dumping the API will increase Firebase’s flexibility. Your imagination is the limit of ways in which it can be used.
  • Control: When using an API you are limited by their functions and structure. You are also limited when adding new features. Using FireChat reduces the control you have over the code as the structure is completely fixed.
  • Customisation: Similar to the points above, when using an API you give up a large amount of control in exchange for additional ease of use. In this case I don’t think it is worth it due to the way the Firebase code is currently written. Coding your chat using Firebase, but not through the API, will allow you to add new features and more easily modify current ones.
As you can see Firebase excels when it is being used for the majority of projects. Where it falls down is when a specific project has some very specific requirements which don’t quiet fit the Firebase model. This is why I would recommend it to 95% of developers - the other 5% will need to research what will be best for them.
The problem is not with SendBird, Layer or Sinch but the inherent problem with Chat APIs themselves. Although FireChat falls into all these pitfalls, Firebase provides code to enable you to code it yourself.
Our company has recently released an open source chat component, using Firebase, on Github. These are fully complete and compatible IOS and ANDROID chats which we have released on an MIT license. This means you can release and modify the code with no obligation to us. Both of these project use Firebase for message and data storage but use Backendless for push notifications. I would recommend these over the other chat APIs as it gives you the source code to modify instead of being reliant on a companies frameworks.
What else could we use?
One final disadvantage of Firebase (and all the frameworks you mentioned) is the fact that you are using someone else’s service meaning you are reliant on them. Obviously this is a problem with every chat solution as it requires you to use their API for your project. The solution to this could be XMPP which is what many professional chats have switched to using. The advantage is that you build your service and configure it directly to the service you offer. Our company also specialises in XMPP solutions.

Monday 20 November 2017

Difference between an interface and abstract class



ABSTRACT 



A class has common behavior which repeatedly use for subclass then you should go with abstract class. You can override the method of parent class & if you want apply some extra modification as per your code needs.

Abstract classes may contain abstract declarations, concrete implementations, or both.

Abstract classes are best choice for re-implementation in future that to add more functionality without affecting of end user.


  • Abstract class can have abstract and non-abstract methods.
  • Abstract class doesn't support multiple inheritance.
  • Abstract class can have final, non-final, static and non-static variables.
  • Abstract class can provide the implementation of interface.
  • The abstract keyword is used to declare abstract class.
  • Comparatively fast.
  • We can't not create object of Abstract class.
  • We can create reference variable.

We choose an abstract class when there are some features for which we know what to do, and other features that we know how to perform.

Consider the following example:

public abstract class Burger{
   
    public void packing(){
        //some logic for packing a burger
    }
   
    public abstract void price(); //price is different for different categories of burgers

}

public class VegBerger extends Burger{
    public void price(){
         //set price for a veg burger.
    }
}

public class NonVegBerger extends Burger{
     public void price(){
         //set price for a non-veg burger.
     }
}

If we add methods (concrete/abstract) in the future to a given abstract class, then the implementation class will not need a change its code. However, if we add methods in an interface in the future, we must add implementations to all classes that implemented that interface, otherwise compile time errors occur.
            


INTERFACE

Interfaces are rules. That’s because rules you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules which common understanding among the developers.

In other words, Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules.

  • Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
  • Interface supports multiple inheritance.
  • Interface has only static and final variables.
  • Interface can't provide the implementation of abstract class.
  • The interface keyword is used to declare interface.
  • Interface are slow as it requires extra indirection.

If user want to write different functionality that would be different functionality on objects. Interfaces are best choice that if not need to modify the requirements once interface has been published.

Consider a Payment class. Payment can be made in many ways, such as PayPal, credit card etc. So we normally take Payment as our interface which contains a makePayment() method and CreditCard and PayPal are the two implementation classes.

public interface Payment{
     void makePayment();//by default it is a abstract method
}

public class PayPal implements Payment{
     public void makePayment(){
         //some logic for PayPal payment
         //e.g. Paypal uses username and password for payment
     }
}

public class CreditCard implements Payment{
    public void makePayment(){
         //some logic for CreditCard payment
         //e.g. CreditCard uses card number, date of expiry etc...
     }
}

In the above example CreditCard and PayPal are two implementation classes /strategies. An Interface also allows us the concept of multiple inheritance in Java which cannot be accomplished by an abstract class.

I hope this will help!