Friday, 11 June 2021

Explained Services in Drupal 8

Drupal 8 services are just a object which is managed by the container. The purpose of managing it via a container is to make the object alterable and plugable.  In simple words, Drupal 8 services are those objects which are registered with the service container in order to decouple reusable functionality. Of course services are registered with the service container for any specific purpose.  It could be used for sending an email to customer, or to generate links or to do checkout using any specific payment gateway plugin. In simple words, it can be used to server anywhere in the Drupal 8 code base.

In order to learn Drupal 8 services, we must first get familiar of some one or two most used Drupal services created in its core itself.

  1. config.factory: In Drupal 8 we now use the Configuration system which provides a central place for modules to store configuration data. This services will allow us to store the configurations or retrieve them wherever we need them. This information is generally created during site development and it is not generally effected by regular users.
  2. current_user:  This service is very useful in order to get some basic information about the current user on site. Note, current_user is not giving you user entity, it is just user proxy which will give certain details to you about the current user like if the username is anonymous or not, or its 'id' using method \Drupal::currentUser()->id(). To load the user entity you must load the user entity manually using User class or using user storage.

So, here we got to know the few details of the few services. Now, time to learn to create new service. But let's do it with the example. 

Creating a Drupal 8 service require two steps
         1.  First it has to be defined in the services.yml of module to register with the service container
         2.  Second the PHP object to perform any specific tasks.

Step 1: Let's define our service in services.yml

    class: Drupal\custom_media\PdfImageManager
    arguments: ['@entity_type.manager', '@file_system', '@config.factory']

Now, let's understand the above code snippet quickly. Let's do it for line by line.

services: This line just tells that all the services of current modules are listed

custom_media.pdf_image_manager: This is the id of the newly created service. This id will be used to fetch the service from the service container anywhere.

class: Here we will write the path of the service i.e the object we are going to write.

arguments: This line contains arguments. This is optional, Here we can send the other services as arguments to this service.

Step 2: Now let's go through the next step i.e creating the object.


namespace Drupal\custom_media;
use Drupal\Core\Config\ConfigFactory; use Drupal\Core\Entity\EntityTypeManager; use Drupal\Core\File\FileSystem; use Drupal\Core\State\State; use Drupal\Core\Logger\LoggerChannel; use Drupal\Core\StreamWrapper\StreamWrapperInterface; use Drupal\Core\Url; use \Imagick; /** * Class PdfImageManager. * * @package Drupal\custom_media */ class PdfImageManager { const IMAGE_EXTENSION = 'jpeg'; /** * EntityTypeManager. * * @var \Drupal\Core\Entity\EntityTypeManager */ protected $entityTypeManager; /** * FileSystem. * * @var \Drupal\Core\File\FileSystem */ protected $fileSystem; /** * @var \Drupal\Core\Config\ConfigFactory */ protected $configFactory; /** * MediaPdfThumbnailImagickManager constructor. * * @param \Drupal\Core\Logger\LoggerChannel $loggerChannel */ protected $logger; /** * MediaPdfThumbnailManager constructor. * * @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager * EntityTypeManager. * @param \Drupal\Core\File\FileSystem $fileSystem * FileSystem. * @param \Drupal\Core\Config\ConfigFactory $configFactory */ public function __construct(EntityTypeManager $entityTypeManager, FileSystem $fileSystem, ConfigFactory $configFactory) { $this->entityTypeManager = $entityTypeManager; $this->fileSystem = $fileSystem; $this->configFactory = $configFactory; $this->logger = $loggerChannel; } /** * Create pdf thumbnail. * * @param $entity * * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException * @throws \Drupal\Core\Entity\EntityStorageException */ public function createThumbnail($fileEntity) { if ($fileEntity && $fileEntity->getMimeType() == 'application/pdf') { $file_id = $this->generatePdfImage($fileEntity); return $file_id; } return false; } /** * @param $fileEntity * * @return bool|string */ protected function generatePdfImage($fileEntity) { $fileInfos = $this->getFileInfos($fileEntity); if (!empty($fileInfos['source']) && !empty($fileInfos['filename'])) { return $this->generateImageFromPDF($fileInfos['source'], $fileInfos['filename']); } return NULL; } /** * @param $fileEntity * * @return array */ protected function getFileInfos($fileEntity) { $filename = $fileEntity->filename->value; $fileUri = $fileEntity->getFileUri(); $sourcePath = file_create_url($fileUri); $destinationPath = $sourcePath .'.jpeg'; return ['source' => $sourcePath, 'filename' => $filename]; } /** * Generate image from PDF file. * * @param string $source * File source. * @param string $filename * File filename. * */ public function generateImageFromPDF($source, $filename) { try { $im = new imagick(); $im->readimage($source); $im->setIteratorIndex(0); $im->setImageFormat(self::IMAGE_EXTENSION); $target_filename = $filename . '.' . self::IMAGE_EXTENSION; $file_data = file_put_contents("public://pdf_to_image/$target_filename", $im); $file_data = file_get_contents("public://pdf_to_image/$target_filename"); $file = file_save_data($file_data, "public://pdf_to_image/$target_filename"); return $file->id(); } catch (\Exception $e) { \Drupal::logger('ch_media')->error($e->getMessage()); return FALSE; } return TRUE; } }

Here we have created a service which will take the pdf as file and will generate the screenshot of its first page using Imagick library. So, we now created a service successfully. In order to use it anywhere you must first register it with the service container, So do the cache rebuild and this Drupal 8 service itself will be registered with the service container. 

Now come to the use case where u need to use this service i.e you wanted to get the screenshot of the first page of the pdf. What you have to do is fetch this service from the service container using \Drupal::service("custom_media.pdf_image_manager") and call generatePdfImage($fileEntity) method. Services can also have other properties such as tags which will categorise them into different categories.

Sunday, 24 March 2019

Deletion and Updating in Python String

In python you cannot delete or update any particular character or a sequence of characters. In simple words, deletion and updating of characters is not possible in a defined string of Python. As python strings are immutable. Hence they can't be changed once defined. But you can assign the same identifier to a new string. But what if you want to delete that previous defined string. In that case you can use the 'del' keyword. This keyword will delete the previously defined string and will throw a not defined error if you try to print or access the deleted string. Let's take some examples to see the deletion and updating operations on a python string.

Updating a single character:

#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")

#updating a single character
print("\n\nPrinting the updated string:\n")



Updating an entire string:

#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")

#updating a single character
string = 'hello'
print("\n\nPrinting the updated string:\n")



Deletion of a single character:

#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")

#deleting the single character
del string[1]
print("\n\nPrinting the updated string:\n")



Deleting an entire String:

#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")

#deleting the single character
del string
print("\n\nPrinting the updated string:\n")



Strings In Python

Though Python doesn't have the character data type, even a single character in Python is also considered as string of length 1. Some important and basic things to know about the Strings in Python along with the examples are following:

1. Strings in Python can be created using the single, double as well as with triple quotes quotes. In Python, you can create a string with a double quoted character or word in it.

2. String in single quotes cannot hold any other single quoted character inside it. If you try to create the same the it will throw an error of Invalid Syntax. But to achieve that you can use the double quotes.

3. If you want to put a double quoted character or word in a python string. Then you can use triple quotes suggested.

4. You can also create the multi line string with the use of triple quotes

Some examples of the strings in Python are given below:


#creating a single quoted string
string = 'This is the string'
print("\n\nPrinting a single quoted string:")

#creating a string with the double quotes
string = "This is a double quoted string"
print("\n\nPrinting a double quoted string:")

#creating a string with a single quoted word or character in it
string =  "This is a geek's computer"
print("\n\nPrinting a string with single quoted character:")

#creating a string with a double quoted string
string = '''This is a double quoted "word", you can see it'''
print("\n\nPrinting a string with double quoted string:")

#creating a multi line string

string = '''This

print("\n\nPrinting a multi line  string:")


Read also: Deletion and Updating in Python String 
Read also: List of the keywords in Python

Wednesday, 21 November 2018

Python Program to Reverse a Singly Linked List

Python program to reverse a singly linked list is given below along with the output.


class Node:
        #defining a Node constructor
        def __init__(self,data):
   = data
   = None

class LinkedList:
        #defining a LinkedList constructor
        def __init__(self):
            self.head = None
        def insert_node(self,data):
            #checking of head node is still None
            if self.head == None:
                newnode = Node(data)
                self.head = newnode
                #we will traverse till the last node to append the new node
                current = self.head
                while != None:
                    current =
       = Node(data)

        def print_linkedlist(self):
            current = self.head
            while current != None:
                print(," -> ",end="")
                current =

        def reverse(self):
            prevnode = None
            current = self.head
            nextnode = None
            #here we are reversing the Linked List
            while current != None:
                nextnode =
       = prevnode
                prevnode = current
                current = nextnode
            self.head = prevnode

linkedList = LinkedList()

#let's first print the created linked list
print("\nThe created Linked List is: \n\n")

#Now reverse the linkedList

#Now print the reverse Linked List
print("\n\nTher reversed linked list is: \n\n")



Sunday, 9 September 2018

JavaScript Arrow Functions - Concise Syntax

The arrow functions in JavaScript is one of the most discussed topic of JavaScript since the release of ES6. Arrow functions are very short and concise to use. Therefore, usage of these function is quite popular among the JavaScript developers..


(parameters) => { statements }

Basically there are two benefits of the arrow functions in JavaScript..
1. Shorter Syntax: Hence reduces the syntax overhead and involves less typing.
2. No Binding of this operator: To understand this, you must have good understanding of this keyword in JavaScript. Well we will discuss this benefit of arrow functions in separate post..

In this post we will discuss about the first benefit of the arrow functions.

1. Shorter Syntax:
First take an example of the regular function.

Now you can see that above example is one of the reason for creating the arrow functions. With the help of an arrow function we can generate the same function in one line of code.

The above is example is very simple but hope you got the point..Let' take a look at few more syntaxes such as arrow function with only one statement, only with one parameter or the case of returning an expression..

You can see that in the first we removed the bracket from parameters because we just had one parameter. And In the second example we had to return an expression instead of result..Therefore we omitted the curly braces to return the expression x*y.

Let's take one more example. In this example we will use the findIndex() method of JavaScript and return the index of the first Odd number present in the array. We will implement this example in both ES5 and ES6 i.e with regular function and arrow function of JavaScript and then decide ourselves which is syntactically more concise..

 Now, I am pretty sure this example has cleared the picture of the shorter and concise syntax of the arrow funtions in javasScript..

Thursday, 6 September 2018

findIndex Method in JavaScript

The method findIndex() returns the first index of the element that satisfied the given condition. Suppose there is an array of integers and you have to find the index of the first odd number of the array.. This method is very useful in solving many problems in JavaScript. Let's take some examples to clearly understand the findIndex() method of JavaScript. If there is not any element in the array that satisfies the given condition then findIndex() method returns -1.


arr.findIndex(callback[, thisArg])


callback:  Function to execute on the each element of array.

element: The current element that being processed in the array.

index(optional):  The index of the element currently being processed in the array.

array(optional): The array on which findIndex() called upon.

thisArg(optional):  Object to be use as this when executing the callback function.


In first example we will find the index of the first odd number present in the array.



Let's take one more example. In this example we will find the index of the first multiple of 3 in the array..


Tuesday, 4 September 2018

Datatypes in JavaScript

The most fundamental characteristic of any programming language is the data types it supports..Basically data types refers to the types of values which can be represented and manipulated in that programming language.. Every Programming language has its own set of data types...

JavaScript has three primitive data types:

  1. Numbers: It holds the numerical values e.g:  123, 100.50 
  2. Strings: It holds the piece of text...It can be of 1 character or more than it. eg:  "c" , "This is the text" , "    ddd". 
  3. Boolean : this datatype has only two possible value...true or false..i.e 1 or 0.
Besides these three primitive datatypes. JavaScript also has two trivial data types which are null and undefined and each of them defines only a single value....JavaScript also supports composite data types which are known as object.

Variable Initialization:

In JavaScript you can initiate the variables any time. You can initialize them in the beginning of a JavaScript file or you can also create and initialize them anywhere in the document when you need them. Assigning or storing a value to a variable is called variable initialization.

The one of the most amazing thing about JavaScript is that its variable can hold any type of value. Unlike C++, Java or many other programming languages, you don't have to mention the type of value you gonna be store in that variable..JavaScript will take care automatically..

Variable Declaration: 

In JavaScript you can define any type of variable simply using keyword var  and the JavaScript automatically do the rest. To enhance the JavaScript ES2015 has two more keywords to declare a variable. const and let are used to define the constant variable and block scope variable respectively..You can change the value of a const variable once you initialized it and let is used to define the variables in a block scope variable...

Let's See an Example:


Monday, 27 August 2018

PHP Program to reverse an array | array_reverse()

array_reverse() is an inbuilt function of PHP used to reverse the array including the nested arrays. It returns the reversed array. But in the case of associative arrays of if you don't want to change the keys of the array, $key_preserve=true can be passed as a parameter to the array_reverse() function. array_reverse() function is explained below with an example.


array array_reverse($array,$key_preserve);

$array: This parameter is mandatory and it is the array you want to
$key_preserve: This parameter is optional, if you set it to true then it will preserve the keys. Default value of $key_Preserve is taken as false.



echo "Case 1:<br /><br />";

//Let's take an example of a linear array

//Applying array_reverse() on the above array

echo "<br /><br />Case 2:<br /><br />";

//Let's use the key_preserve as true 

//key_preserve=true will preserve the keys of the array

echo "<br /><br />Case 3:<br /><br />";

//Let's take an example of nested array


//After reversing array[0] starts with 6
echo "<br /><br />";

//After reversing array[1] starts with 1



Sunday, 26 August 2018

First Program in PHP

Before writing the first program in PHP there are few things to discuss about this scripting language.


PHP files can contain text, HTML, CSS, JavaScript, and PHP code. And you must need a server to execute a PHP file and the result of the script will be returned to the browser as plain html.

PHP file has .php extensions.


A PHP script starts with the <?php  and ends with ?>.
A PHP script can start anywhere in the document..


Comments are very useful when you develop an application because it helps others to understand your code and it even helps you to remember your own code..

Comments should be written in clear way so that anyone can understand the work done by that commented section of the code. Let's see our first program in PHP to understand it more..


  //this is the single line comment.

  /*This is the multiple line comments..
    This are used when we have to write multiple line
    of comments 


  #this is also the single line comment.


  $z =  $x+$y;

  echo "The value of x is: ";
  echo $x;                     //printing the value of $x
  echo "<br /><br />";   //Using line break

  echo "The value of y is: ";
  echo $y;                     //printing the value of $y

  echo "<br /><br />";   //Using line break

  echo "The value of the z is: "; //printing the value of z
  echo $z;




PHP Introduction - Tutorials for Beginners

Let's divide this section in the two parts.


The first thing is that PHP stands for the Hypertext Preprocessor. Basically, PHP is server side scripting language i.e scripts of the PHP gets executed on the server side. PHP is the most popular server side scripting language. Yes millions of websites are built upon PHP even tech giants like google, yahoo and facebook also heavily use PHP.. Even the world's most popular CMS WordPress and Drupal also built upon PHP..

Before developing the PHP applications you must have the basics understandings of the following language..

1. HTML (Hypertext Markup Language).
2. CSS (Cascading Style Sheets).
3. JavaScript (scripting language like PHP but works on client side i.e on browser side).

Let's take a look at the common thing PHP usually do in a web application:

1.  It can be used to generate the content dynamically..
2.  It can be used to encrypt the data.
3.  It can be used to store the data in the database and fetch the data from the
4.  It can be used the handle the form data.
5.  It can be used to listen the request send to server by browsers.
6.  It can be used to control the user-access.

Basically PHP have all the qualities to built a large web application with huge number of users every day..

2. WHY PHP ?

Now second thing is that why the hell we use PHP when there are other plenty of server side scripting language already available.. So let's take a look on the things which make this scripting language very special...

1. PHP is free to download and use..
2. It is easy to learn.
3. It is easy to install.
4. It supports a wide range of database..
5. It has huge community support..
6. It runs efficiently on the server side..
7. It is compatible with the most widely used servers such as Apache, IIS etc.. 

My first program in PHP

Friday, 17 August 2018

C++ Program to Generate all the Rotations of a String

We will discuss an easy approach to generate all the rotations of a string. Approach is simple we will concatenate the given string with itself and then we will be able to generate all the rotations. C++ Program to generate all the rotations of a given string is given below along with its algorithm.


step 1: Let string s="plex" 
step 2: Let string temp=s  i.e (temp="plex")
step 3: Set temp=temp+temp i.e (temp="plexplex")
step 4: set i=0,j=0
step 5: For i=0 to length(s):
                  declare an empty variable e.g temp1=""
                  For j=0 to length(s):
                            set temp1=temp1+temp[i+j]


#include <bits/stdc++.h>
#include <algorithm>
using namespace std;

int main(){

	  string s;
	  cout<<"\nEnter the string to find out its rotations: \n";

      //a string container to store all the rotations
      std::vector<string> vect; 

      //copying string s into temp
      string temp=s;

	  //now contacenate string 'temp' with itself..
	  //ex: temp="plexinfo" so, after concatenation temp="plexinfoplexinfo"
      // cout<<temp<<"\n";

      //loop from 0 to length(s)-
      for(int i=0;i<s.size();i++){

      	   string temp1=""; //declaring an empty string

      	   for(int j=0;j<s.size();j++){

      cout<<"\nAll the rotations of the given string are:\n\n";
      for(int i=0;i<vect.size();i++){
      return 0;




Friday, 20 July 2018

C++ Program to find the square root of Number in log(n)

The idea is simple. We will use binary search to find the square root of the number. If the given number is not a perfect square then we will simply take the floor value of the root of the number.. Algorithm to find the square root of a number in log time is given below along with its implementation in C++.

For example: if  n = 10 then answer is 3 and if n==25 then answer is 5


1. set start=1
2. set end=n
3. do while (start<=end):
4.           set mid=(start+end)/2
5.           if  (mid*mid=n) return mid
6.           else if (mid*mid<n)
7.                  set ans=mid
8.                  set start=mid+1
9.           else
10.                set end=mid-1
11. return ans


#include <bits/stdc++.h>
using namespace std;

int findFloorRoot(int n){
  int start=1,end=n;
  int ans;

     //calculate middle value
          int mid=(start+end)/2;

          //if nis a perfect square of mid then return mid
          if(mid*mid==n) return mid;

          else if(mid*mid<n){
              ans=mid;  //if n is not a perfect square then take the floor value
  return ans;

int main(){
  int n;
  cout<<"\nEnter the number: ";
  int ans=findFloorRoot(n);
     cout<<"\nThe root of the n is: \n\n";
     return 0;


Sunday, 3 June 2018

C++ Program to find all the Peak Elements in Array

In this program an array is given to you and you have to find the peak elements in the array..  A peak element in the array is the element which is greater than its left and right elements.  Therefore, There can be multiple peak elements in the array. C++ Program to find all the peak elements in the array is given below.

For first and last element of the array we will check for the right and left elements respectively.

Example: Let arr={34,23,67,35,98}
Here peak elements are :  34, 67,98


#include <bits/stdc++.h>
using namespace std;

vector<int> find_peak(int arr[], int n)
     /* Declaring a vector to store the peak elements */
     std::vector<int> vect;

     /*Checking if first element of array is peak or not */
     if(arr[0]>arr[1]) vect.push_back(arr[0]);

     //checking rest of the elements

     for(int i=1;i<n-1;i++){
         if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){

      /*Checking if last element of array is peak or not */
      if(arr[n-1]>arr[n-2]) vect.push_back(arr[n-1]);
      return vect;

int main(){
    int n;
    cout<<"\nEnter the number of elements:\n";

    int arr[n];

    cout<<"\nEnter the elements: \n\n";
    for(int i=0;i<n;i++){

    vector<int> result=find_peak(arr,n);

    cout<<"\nThe peak elements in the array are: \n";
    for(int i=0;i<result.size();i++){
         cout<<result[i]<<" ";

    return 0;



Thursday, 26 April 2018

Reverse a linked list - JavaScript

linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null. The entry point into a linked list is called the head of the list.

If Linked List is :  22->45->67
Then, reverse Linked List is: 67->45->22


class Node{
class LinkedList{
var newnode=new Node(data);
var tempnode=this.root;
var tempnode=this.root;
console.log("\nThe linked list is: \n\n");
var currentnode=this.root;
var prevnode=null;
var nextnode;
var ll=new LinkedList();


Array.prototype.indexOf() - JavaScript

This method is used to find the first index at which the given element occurs. The indexOf() method returns the first index or -1 if element does not exist.



1. The first parameter is the element to locate in the array.

2. fromIndex is an optional paramter, It an be used to find the multiple indexes at which the given element is present. If the value of this paramter is greater or equal than the length of the array then -1 will be returned. If the value of the fromIndex is negative, then it is taken as the offset from the end of the array but still the array will be searched from front to back.


var array=['game','of','thrones'];
var result=array.indexOf('of');
console.log(result) //It will give 1

//let's put the value of fromIndex parameter
var result=array.indexOf('of',2);
console.log(result) //it will return -1

//lets give the negative value to fromIndex
var result=array.indexOf('of',-2);
console.log(result);//it will return 1