Program to print Factorial of any number

During our college days, we used to run various programs, some of them we used to understand and some of them we used to mug up. Once again i have thought to recall those programs and try to explain as simple as possible so that I can brainstorm myself and any students who go through it can easily get the logic behind it.

First of all, let us understand what is factorial of a number,

The factorial of a non-negative integer n is denoted by n! is the product of all positive integers less than or equal to n. example
Factorial of 4! = 1 * 2 * 3 *4 = 24
Factorial of 5! = 1 * 2 *3 * 4 * 5 = 120
n! = n*(n-1)*(n-2)*(n-3)…3.2.1

<?php 
$num=4;
$fact=1;

for($i=1;$i<=$num; $i++){
$fact=$i*$fact;
}

echo "factorial of a number ".$num is $fact;

In the above code, i am trying to find the factorial of a number 4, whereas I have initialized $fact variable with 1 as shown above, as we start our product of a number with 1.
Factorial of 4! = 1 * 2 * 3 *4 = 24

we are going to start from 1 and continue multiplying the number we have, ie. 4 so we are going to make use of for loop.
Now let us consider our looping. here we initialize variable $i with 1 and compare if it is less or equal to the number, so the first condition is correct (1<=4), so we go inside loop and execute the statement.

$fact= 1* 1 ($fact value that has been initialized)
$fact=1

now variable $i is incremented with one as we have $i++ in our loop so the new value of $i is $i=1+1=2;
now we will check the condition (2<=4), even this condition is correct so we execute the statement
$fact= $i*$fact
$fact= 2*1;($fact=1 which is previous value of $fact that we obtained after executing the statement)
$fact=2

Again $i is incremented by 1 and has become 2+1 =3, and we check condition (3<=4) which is again correct, so our statement becomes
$fact= $i*$fact
$fact= 3*2;($fact=2 which is previous value of $fact that we obtained after executing the statement)
$fact=6

Again $i is incremented by 1 and has become 3+1 =4, and we check condition (4<=4) which is again correct, so our statment becomes
$fact= $i*$fact
$fact= 4*6;($fact=6 which is previous value of $fact that we obtained after executing the statement)
$fact=24

Again $i is incremented by 1 and has become 4+1 =5, and we check condition (5<=4) which is false, so we come out of the loop and print the final factorial value.

So the final factorial value of 4 is 24

Advertisements

View Composers in laravel

When you start working on laravel, you will come into the situation where you require same data in multiple views. ie, sidebars or side widget. so it’s not a good idea to fetch same data again and again for every views. so for this we can use view composer which will help you to get same data multiple views without calling multiple times.

For this we are going to consider AppServiceProvider.php which lies inside Providers folder. There are two functions inside AppServiceProvider.php, one is boot(), another is register(). But here we are going to make use of boot() function. In boot function you can perform any action assuming that framework is fully loaded. Now make use of view helper function as shown below:

<?php
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        view()->composer('layouts.sidemenu',function($view){
            $notificationinfo=new NotificationAlertController();
            $view->with('notificationCount',$notificationinfo->showNotificationCount());
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Here we can hook into when any view is loaded. It’s just like a callback. Now let me go to my view which makes use of sidemenu all the time. This sidemenu is called from all other views. In my sidebar I have notification count, so I have decided which ever views call sidebar, it should show notification count.

Now let us explain in brief about the code that we have written inside the boot(). When a layout.sidemenu is loaded in any views, we call a callback function where we can bind anything to that view. Within a callback function, i have created an object for NotificationAlertController.

Then I have called a function with that controller named as showNotificationCount(), from this function we are getting a value of notificationcount, which in turn we are binding that returned value to the view.

Now let enclose function showNotificationCount() of NotificationAlertController too.

<?php
class NotificationAlertController extends Controller
{
 public  function showNotificationCount(){

        $notificationCount=DB::table('current_device_profile_infos')
            ->select('current_device_profile_infos.vin_number', 'battery_level', 'fuel_level', 'mileage', 'id')
            ->where('battery_level', '<', 12.5)
            ->orWhere('fuel_level', '<', 20)
            ->orWhere('mileage', '>', 11000)->count();

        return $notificationCount;
    }

}

Now which ever view you click into, but the notification count is displayed everywhere. This is a short and easy explanation on view composer.

If you have any query, feel free to contact me.

Color odd and even div alternatively with different color

I had a situation where I need to have an alternate background color for the rows inside a parent div. Sample code is shown below

<div class="content-body-notification content-body  ">
<div class="user-row">
1
</div>
<div class="user-row">
2
</div>
<div class="user-row">
3
</div>
<div class="user-row">
4
</div>
</div>

So now we are going to give different background color to odd and even user-row rows as shown below


.content-body .user-row:nth-child(odd) {
    background: #eeeff2;
}
.content-body .user-row:nth-child(even) {
    background: #f8f8fa;
}

and we get output same as diagram shown below:

Laravel Pagination links not including other GET parameters

When there are some GET parameters in the URL,
eg: http://yoursiteurl.com/search-vehicle-profile?startdate=07%2F28%2F2017&enddate=08%2F01%2F2017&vin_number=2HGFC2F89GH033029, the pagination links produced only contain the page parameter and nothing else as http://yoursiteurl.com/search-vehicle-profile?page=2

This happens when you use link in your blade as {{ $vehicleHistoryDetail->link() }}

so rather than just using that, you need to you appends function as shown below

{{ $vehicleHistoryDetail->appends(request()->input())->links() }}

Raw Query in Laravel

We can write raw query in laravel as shown below. Here we have made use of where, where in, with ‘and’ and ‘or’ condition. The most important thing you need to consider while writing raw query is DB::select( DB::raw())


  $vehicleHistoryDetail =
            DB::select( DB::raw("SELECT mdi_ext_batt_voltage,mdi_dashboard_fuel_level,mdi_obd_mileage FROM vehicle_info_devices WHERE profile_id IN (1,2)and(
        mdi_dashboard_fuel_level <> 0 or mdi_ext_batt_voltage <> 0 or mdi_obd_mileage <> 0) ") );

Fun with Array

I have a locationlist class which has geographical latitude and longitude as shown below


<?php 
namespace App\LocationProviders; 
class LocationList 
{ 
public function getLocations() 
{ 
       $locationCoords = []; $locationCoords[0] = [ ["lat" => 43.75812569798546, "lng" => -79.79318417608738],
            ["lat" => 43.758138774543475, "lng" => -79.7931607067585],
            ["lat" => 43.75810390371577, "lng" => -79.7931244969368],
            ["lat" => 43.75809034283284, "lng" => -79.79314729571342]
        ];

        $locationCoords[1] = [
            ["lat" => 43.7581397431773, "lng" => -79.79315668344498],
            ["lat" => 43.758152819732246, "lng" => -79.7931332141161],
            ["lat" => 43.75811843322978, "lng" => -79.7930970042944],
            ["lat" => 43.758105356667315, "lng" => -79.79311980307102]
        ];
        $locationCoords[2] = [
            ["lat" => 43.7581547569994, "lng" => -79.79312919080257],
            ["lat" => 43.7581673492344, "lng" => -79.7931070625782],
            ["lat" => 43.758132962740284, "lng" => -79.79307018220425],
            ["lat" => 43.75812037049805, "lng" => -79.79309231042862]
        ];

    return $locationCoords;
     }

}

Now what I intend to do is, I want to have array of latitude and array of longitude for the array $locationCoords[0],$locationCoords[1],$locationCoords[2] and so on.For this i have written below code


public function vehicle_map_with_info()
    {

      $locationListInfo = new LocationList();

        $locationinfo = $locationListInfo->getLocations();

        $newCoordinateArr = [];
        foreach ($locationinfo as $key => $value) {
            $latitudeArr = [];
            $longitudeArr = [];
            foreach ($value as $keyanother => $anothervalue) {

                $latitudeArr[] = $anothervalue['lat'];
                $longitudeArr[] = $anothervalue['lng'];
            }
            $newCoordinateArr[$key]['lat'] = $latitudeArr;
            $newCoordinateArr[$key]['lng'] = $longitudeArr;


        }

        echo "<pre>";
        //print_r($latitudeArr);
        return $newCoordinateArr;

}

Here it is, now you can get array in the form as shown below:


[
{
"lat": [43.75812569798546,43.758138774543475,43.75810390371577,43.75809034283284],
"lng": [-79.79318417608738,-79.7931607067585,-79.7931244969368,-79.79314729571342]
},
{
"lat": [43.7581397431773,43.758152819732246,43.75811843322978,43.758105356667315],
"lng": [-79.79315668344498,-79.7931332141161,-79.7930970042944,-79.79311980307102]
}
]

Fun with Array -2

Now i have another requirement too, that is i want array of latitude and longitude in the form of

$finalcoordinates=array("lat1 lng1","lat2 lng2","lat3 lng3"); ie

$finalcoordinates = array("43.7592439755264 -79.79324888437986","43.759231383517985 -79.79323044419289","43.759203535797674 -79.79327369481325","43.759215643503765 -79.7932904586196","43.7592439755264 -79.79324888437986");

In order to get this output i have written a code as shown below:


public function vehicle_map_with_info($vin_id)
    {
        $locationObj = new FindLocation();
        $locationinfo = $locationObj->showLocations();

        foreach ($locationinfo as $key => $value) {
            $newCoordinateArr = [];
            foreach ($value as $seckey => $finalvalue) {
                $newCoordinateArr[$seckey] = $finalvalue['lat'] . " " . $finalvalue['lng'];

            }
          
          
        }

        return $newCoordinateArr;
}

Now you get your output as


[
"43.758909802097 -79.794197380543",
"43.758935954868 -79.794150441885",
"43.758917551068 -79.794130325317",
"43.758891398289 -79.794177263975",
"43.758909802097 -79.794197380543"
]

Hope it gives solution to your problem.

Background image and providing padding to it

I have a select input and i want to put small image icon at the right of it with some padding on it. For this the easy solution is

My input

 <select placeholder="Filter By" class="searchuser userddl">
                    <option>Filter By</option>
                    <option>Recently Updated</option>
                    <option>Recently Deleted</option>
                </select>

And the css to give background image along with some padding is:


select.searchuser.userddl {
    background: #000 url('/images/down-arrow.png');
    background-position: right 7px top 6px;
    background-repeat: no-repeat;
}

And the output appears as

Preview Image before it is uploaded

Today we are going to learn about Image preview before it is uploaded.

In your php file, you have code as shown below:

<form id="form1" runat="server">
        <input type='file' id="uploadFile" />
        <img id="imagePreview" src="#" alt="your image" />

<script type="text/javascript" src="js/imagePreview.js"></script>
</form>

Include your script file in your header or footer, and you have js file with the name imagePreview as shown below:

$(function() {
    $("#uploadFile").on("change", function()
    {


        $( "#imagePreview" ).addClass( "giveImgStyle" );
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){ // set image data as background of div
                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
        }
        else{
            alert('Please Select Image');
        }
    });
});


Then in your style sheet, add the style for giveImgStyle


.giveImgStyle{
    width: 180px;
    height: 180px;
    background-position: center center;
    background-size: cover;
    display: inline-block;
}

Then you are done. you get imagepreview as shown below

imagepreview

Enable user register even after login laravel 5

In order to enable user register even after logging in laravel, you can do following simple step:

1. Go to your RegisterController.php which is inside controllers followed by Auth.

There you get code as shown below

   public function __construct()
    {
        $this->middleware('guest');
       
    }

You can remove the $this->middleware() line entirely to prevent the middleware being applied to all your login and register routes.

This will enable you to register user even after login.

Laravel 5 Class ‘form’ not found

When i was trying to run my laravel application with form tags like:

{!! Form::label('featured_image','Select Featured Image',array('id'=>'','class'=>'')) !!}
{!! Form::file('image',array('class'=>'imageUpload','id'=>'uploadFile')) !!}

I got an error with Laravel 5 Class ‘form’ not found
With some research, i found a solution for it. Here are some steps to solve it.

1. Go to your composer.json file
2. Include “laravelcollective/html”: “^5.2.0” within require
3. then update your composer using a command in your terminal :\> composer update

Once the composer is updated

4. Now go to your app.php file within config folder
5. In providers add following code

  Collective\Html\HtmlServiceProvider::class,

6. then go to alias section and add below code

   'Form' => Collective\Html\FormFacade::class,
   'Html' => Collective\Html\HtmlFacade::class,

Now run your application and you are free of error.

Implement Font Awesome icon inside submit button

If you want to place font awesome icon inside a submit button, first of all you cannot use

 <input type="submit" value="Submit">

but instead, you need to use as shown below:

  <button type="submit" class="btn btn-danger">
                <i class="fa fa-search" aria-hidden="true"></i>
 </button>

List of mostly used media queries

Last time we had discussed most appropriate and easy media queries for your site.I feel those media query itself is enough to make your site responsive. But If you want more detailed media queries that fit almost all varieties of mobiles, desktops, iPads, tablets, and laptops, you can use following media queries.

/* Smartphones (portrait and landscape) */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4. Comma can be used to apply same rules to multiple media queries. */
@media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
/*iPhone 6 Portrait*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait) {
}
/*iPhone 6 landscape*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : landscape) {
}
/*iPhone 6+ Portrait*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : portrait) {
}
/*iPhone 6+ landscape*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : landscape) {
}
/*iPhone 6 and iPhone 6+ portrait and landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px){ 
}
/*iPhone 6 and iPhone 6+ portrait*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : portrait){
}
/*iPhone 6 and iPhone 6+ landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : landscape){
}

Implement Google and other fonts in your site style sheet

Provided you have downloaded fonts which need to get implemented in the site, do following stuff

Method 1

1. Create a separate folder fonts parallel to your other folder,
2. if you have all the formats of font, then paste all of them inside folder,
3. if you dont have all formats, go to the font generator eg: https://www.web-font-generator.com/
4. upload any of the format you have and generate all other formats like .eot, .woff, .svg, .ttf, .otf
5. Then as told earlier, copy those files inside your fonts folder,
6. then paste below code in the style sheet. please make sure your font path is correct along with correct font name.


@font-face {
	font-family: 'Oswald-Bold';
	src: url('fonts/Oswald-Bold.eot');
	src: url('fonts/Oswald-Bold.otf');
	src: url('fonts/Oswald-Bold.woff') format('woff'), url('fonts/Oswald-Bold.ttf') format('truetype'), url('fonts/Oswald-Bold.svg') format('svg');	
}

then in your css you can use as:


.h4{
font-family:Oswald-Bold;
}

Method 2

Before taking all these tensions to implement your font, you first check if the font is available in google fonts

1. First go to google fonts if the font you require is available or not.ie : https://fonts.google.com/

2. search your required font
3. Click plus icon to add font in your list as shown below

4. then you place your link inside tag of your site header as

<head>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

then use font as


.h4{
font-family:Roboto;
}

Complete Media query to make your site responsive

The code below helps your site to fit in different screen sizes. we can find various media queries when we google it, among all those codes i feel these to be the most appropriate and easy to use.


//for larger screen ie large desktops
@media only screen and (min-width: 1200px) and (max-width: 1440px) { 

}

//for medium screen 15inch laptops
@media only screen and ( min-width: 992px) and (max-width: 1024px) { 

}

//for small size laptops ie 13inch laptops
@media only screen and ( max-width: 960px ) { 

}
//for ipad and tablets
@media only screen and ( min-width: 768px ) and ( max-width: 960px ) { 

}

//for mobiles either horizontal orientation or large size mobiles
@media only screen and ( max-width: 767px ) { 

}

 //for mobiles or vertical orientation
@media only screen and ( max-width: 479px ) { 
}


How to change color of placeholder

Here is the code to change the color of placeholder for you inputs

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  color: pink;
}
::-moz-placeholder { /* Firefox 19+ */
  color: pink;
}
:-ms-input-placeholder { /* IE 10+ */
  color: pink;
}
:-moz-placeholder { /* Firefox 18- */
  color: pink;
}

Hello World! First iphone App

From today we will begin learning ios. We will begin with hello world application and will keep learning through out. with each learning you can find sample application for downloading.

In the xcode 5 and above, we do not get xib or interface builder, but instead we get storyboard where we do all designing stuffs. Let us start our hello world program now.

1. First of all open xcode. create a new project as shown below:

Screen Shot 2014-11-16 at 7.43.16 PM

2. Within Application , Choose Application , then select single view application:
Screen Shot 2014-11-16 at 7.46.12 PM

3: then enter the product name as helloworld.

Screen Shot 2014-11-16 at 7.47.17 PM

syntax highlighting in wordpress

To accomplish the syntax highlighting, just wrap your code in these tags:

33

Where Your_used_langauge can be

  • actionscript3
  • bash
  • clojure
  • coldfusion
  • cpp
  • csharp
  • css
  • delphi
  • erlang
  • fsharp
  • diff
  • groovy
  • html
  • javascript
  • java
  • javafx
  • matlab (keywords only)
  • objc
  • perl
  • php
  • text
  • python
  • ruby
  • scala
  • sql
  • vb
  • xml