How to perform code optimization

How to perform code optimization

Before directly jump into how to perform code optimization let’s understand what is code optimization.

What is code optimization?

            For understanding code optimization let’s first understand the meaning of optimization, optimization means to make things more usable, more effective. Code optimization is to write a code that uses less memory, less CPU power, and speed up the processing time, but make sure that the output of that program must not change.

Why code optimization is so valuable?

            Whenever we write code or a program for simple things like I used to write in my college time i.e. creating a calculator or creating simple gaming applications, at that time we are not actually worried about the compilation time or processing speed, but when we write a code for an organization or a company it matters a lot.

            If we do proper code optimization, it will help us to improve performance and reduce the consumption of resources, and we can assign unused resources to other things, resources can be memory or CPU power or anything. So it is also useful for load balancing and stuff like that.

What are the prerequisites for code optimization?

            For performing code optimization for your source code, you need a thorough knowledge of your technology. And you are good to go with it.

How to do code optimization?

After understanding what is code optimization and why we use it now, the main question how we can do it. So let’s understand how we can do code optimization in our own code with its different types:

            1) Machine-independent:

              In machine-independent code optimization, we remove the variables or part of the code which do not require any CPU power or memory.

                        Let’s understand this with an example,

                        Code without optimization:

                       for x in range(6):
                           i = 9
                           print(x + i)

                         In this code, variable ‘i’ will initializes 6 times, which is inappropriate.

                         Code with optimization:

                        i = 9
                        for x in range(6)
                            print(x + i)

                        In this code, we initialize the variable ‘i’ outside of the loop so now it will initialize only for a single time, so this is how we can perform machine-independent code optimization.

            2) Machine dependent:

              In machine dependent optimization the optimization done after the target code has been produced. Machine dependent optimization can further be divided into different types.

i) Dead-code Elimination:

                          Dead-code Elimination is, removes the part of the code which is no longer in use for our program or the part of the code which is not executable or the code whose output is not usable.

                        ii) Partially dead code:

                                   Partially dead code is the code which is going to run on certain conditions, and we know that the part of that code is never going to come on that condition, so in that case, we should remove that part of the code.

                                   Let’s understand this concept with a simple example,

                           a = 9
                           b = 9
                           if a == b:
                               print("yes")
                           else
                               print("no")

                                  In the above example, we have already defim=ne the value of a and b, which are the same. so it will always be going into if condition and ignores the else condition.

                                  So for these type of codes, we can write the code like this,

                           a = 9
                           b = 9
                           if a == b:
                               print("yes")

                            iii) Partial Redundant code:

The code which is partially redundant and of not use, we should remove that. for example,

                          if a == b:
			     c = a  + b
			  else:
		             c = a - b
			  c = a +  b

here, if the value of a and b are going to remain the same for the whole program. After condition executes we are going to assign c = a + b, so in that case, we can remove this part of the code. So first we have to make sure that the value of a and b will be unchanged.

Conclusion

Code optimization can be done for different conditions in different types and with the help of code optimization we can increase performance, load balancing, memory wastage and decrease CPU power consumption. Hence, performing code optimization in your program or code is highly recommended!

Thank you for reading !

Happy coding 😊

Want to learn AI!

Hello people…

Hope you guyz are doing amazing work in your field. I am here with another blog and it’s about AI. Which is the trending buzz word in today’s era. So let’s begin with the blog.

Ok tell me are you new developer or just completed your studies and wanted to work in Artificial Intelligence or Machine Learning ?
So here is content what you need to go through to get into that field.

First lets understand how Artificial Intelligence is divided further.

AI can be divided into seven parts:
   1) Machine Learning
   2) Natural Language Processing (NLP)
   3) Speech
   4) Expert System
   5) Planning, Scheduling and Optimizing
   6) Robotics
   7) Vision

Machine Learning can further divided into two parts:
   i)  Deep Learning
   ii) Predictive Analysis

NLP can further divided into three parts:
   i)   Classification & clustering
   ii)  Translation
   iii) Information Extraction

Speech can further divided into two parts:
   i)  Text to Speech
   ii) Speech to Text

Vision can further divided into two parts:
   i)  Image Recognition
   ii) Machine Vision

These are are parts of AI and different areas you can choose from.

Okay so now you need to go through with these different areas and pick one area of your choice. You will say I am new to this and I don’t have any knowledge about it how can I learn it..?

So there are many MOOCs available for beginners. There are very great platforms like Coursera, edx, Udemy, Udacity, IBM Watson, Cognitive AI and many more. Pick a suitable course and start learning. But first make a promise to yourself that you will finish that course because what happens in many cases we start with one course then we can not give it priority and we just leave it in between, please don’t do this, ya unless it is not that much horrible… 😀

Now let’s talk about languages which are used in these fields. And you must know the first and very popular language which is use in AI and it is Python. Other languages are AIML, STRIPS, Haskel, Lisp, Prolog, R, Java and there are some more. You can choose your favorite language and start learning from MOOCs.

I hope you guyz now understand what you are going to do next. Just do research in these areas and languages and try to go into the depth.

Thank you for reading !

Happy coding 🙂

Let’s do some testing!

Hello people,

Hope you are doing awesome stuff in your area. I am back with another cool blog…! I know it’s only cool for me but its ok, Right…! I am learning anyway…

So today’s blog as the title suggest, its about the testing…
Hey developer, where are you going? Wait and read it, It will helpful for you.

When we create CRUD operations on any feature we sometimes miss many things and then we need to make changes again and again after it comes from QA. So today I am going to share few checkpoints which you must check before submitting it to your QA.

Let’s see checkpoints for all for all feature one by one:

CREATE FEATURE:
Check Validation
Check for duplicate records
Take only needed information

Here is an example in laravel framework of a create function

    public function createArticleCategory(Request $request)
    {
        $data = $request->all();
        // Create a new validator instance.
        $request->validate([
            'name' => 'required',
        ]);
        $isCtegory = ArticleCategory::select('name')->where('name', '=', $request->input('name'))->first();
        if ($isCtegory != null) {
            return response()->json(['message' => 'Category already exist', 'success' => false]);
        } else {
            $category = ArticleCategory::create($data);
            $content = array(
                'success' => true,
                'data' => $category,
                'message' => 'Category Added successfully'
            );
            
            return response($content)->setStatusCode(200);
        }
    }

UPDATE FEATURE:
Check Validation
Check for duplicate records
Take only needed information

Here is an example in laravel framework of a create function

public function editArticleCategory(Request $request)
    {
        $data = $request->all();

        // Create a new validator instance.
        $request->validate([
            'id' => 'required',
            'name' => 'required',
        ]);

        $category = ArticleCategory::find($data['id']);

        if ($category != null) {
            $isCtegory = ArticleCategory::select('name')
                ->where([['name', '=', $request->input('name')], ['id', '<>', $request->input('id')]])
                ->first();
            if ($isCtegory != null) {
                return response()->json(['message' => 'Category already exist', 'success' => false]);
            } else {
                $category->name = $data['name'];
                $category->save();
                $content = array(
                    'success' => true,
                    'data' => $category,
                    'message' => 'Category updated successfully'
                );

                return response($content)->setStatusCode(200);
            }
        }
        return response()->json(['success' => false, "message" => 'Data not found'], 422);
    }

DELETE FEATURE:
Check Validation
Take only needed information
Check for dependency

Here is an example in laravel framework of a create function

    public function deleteArticleCategory(Request $request, $id)
    {
        if (!$request->user()->id) {
            return response()->json(["message" => "unauthorised", 'success' => false], 422);
        }

        $category = ArticleCategory::where('id', $id)->first();

        if ($category != null) {
            $blogs = Blog::select('blogs.id')
                ->leftJoin('blog_categories as b', 'blogs.id', '=', 'b.blog_id', 'left')
                ->where('b.article_category_id', $id)
                ->where('blogs.deleted_at', null)->first();

            if ($blogs != null) {
                return response()->json(['message' => 'You can't delete this category as its already assigned with blog', 'success' => false]);
            } else {
                ArticleCategory::find($id)->delete();
                return response()->json(['message' => 'Category deleted successfully', 'success' => true]);
            }
            return response()->json(['success' => false, "message" => trans('messages.no_data_found')], 422);
        }
    }

some common tips:

Always put try … catch block in your functionality to handling the error

Check as many combination you can add on a particular function according to your feature.

So I hope you got my point.

Thank you for reading…!

Happy Coding… 🙂

laravel ckeditor update

Today I want to use laravle-ckeditor for my project so as usual I have fired the command –
composer require unisharp/laravel-ckeditor, and it installs "unisharp/laravel-filemanager": "~1.8".

I was amazed that what it is dude…! Why it installs filemanager rather then ckeditor…

Then I done some research and got to know about another amazing command which I am going to share with you all, so next time when you want to install ckeditor for your project you do not have to suffer with that.

So here is the command:
composer require ckeditor/ckeditor

And it will install ckeditor and you can see that it will modify your composer.json file and create folder name “ckeditor” in your vendor folder.

I hope this will help you for your project…

Happy Coding 🙂
Thank you for reading 🙂

Laravel : Country – State – City Dropdown with AJAX

Many people have struggle with this topic and they can not get the output and some also complains that they get empty dropdown, so here I am writing my second post on medium and sharing my self tried code snippet with html-javascript file, controller file and route file. So let’s begin…

First we need a blade.php file:

        <select class="form-control" name="country" id="country">
            <option value="">Select Country</option>
            @foreach ($countries as $country) 
                <option value="{{$country->country_id}}">
                 {{$country->country_name}}
                </option>
            @endforeach
        </select>

        <select class="form-control" name="state" id="state">
        </select>

        <select class="form-control" name="city" id="city">
        </select>

Then we need a JavaScript file:

        $('#country').change(function(){
        var cid = $(this).val();
        if(cid){
        $.ajax({
           type:"get",
           url:"{{url('/state')}}/"+cid,
           success:function(res)
           {       
                if(res)
                {
                    $("#state").empty();
                    $("#city").empty();
                    $("#state").append('<option>Select State</option>');
                    $.each(res,function(key,value){
                        $("#state").append('<option value="'+key+'">'+value+'</option>');
                    });
                }
           }

        });
        }
    });
    $('#state').change(function(){
        var sid = $(this).val();
        if(sid){
        $.ajax({
           type:"get",
           url:"{{url('/city')}}/"+sid, 
           success:function(res)
           {       
                if(res)
                {
                    $("#city").empty();
                    $("#city").append('<option>Select City</option>');
                    $.each(res,function(key,value){
                        $("#city").append('<option value="'+key+'">'+value+'</option>');
                    });
                }
           }

        });
        }
    }); 

After that we need to create a controller which fetch all data we need from the database. So here is a code of Controller file:

//For fetching all countries
public function getCounties()
{
    $countries= DB::table("countries")->get();
    return view('index')->with('countries',$countries);
}

//For fetching states
public function getStates($id)
{
    $states = DB::table("states")
                ->where("country_id",$id)
                ->pluck("state_name","id");
    return response()->json($states);
}

//For fetching cities
public function getCities($id)
{
    $cities= DB::table("cities")
                ->where("state_id",$id)
                ->pluck("city_name","id");
    return response()->json($cities);
}

and now last but not the least the route file, which is use to reach to the functions we have created. So let’s see the code of rote file:

Route::get('/getCountries','YourController@getCountries');
Route::get('/getStates/{id}','YourController@geStates');
Route::get('/getCities/{id}','YourController@geCities');

Happy Codding…
Thank you for reading…

The Journey Begins

Thanks for joining me!

Good company in a journey makes the way seem shorter. — Izaak Walton

post

I am writing my very first blog. I don’t know what to say. OK So let’s start with my introduction, I am a Developer by profession. I really love building websites and stuff. I have one year of experience of developing. And now if I talk about my hobbies, they are totally different from my profession. My hobbies are acting, dancing and singing. I have participate many dramas, dancing and singing competition during my school and college time.

So now I guess that is enough introduction of mine. If you wish to connect with me, check out my personnel website http://sonichandni.github.io. 

I have created this page to share my knowledge with all of you. I am going to write about the code snippets which are very useful for developers. So Stay connect and feel free to reach out.

Happy Coding….!

Thank you for reading….😊