code-rag-bench/online-tutorials huggingface dataset:
What are the differences between npm and npx ?

31 May, 2022
NPM: The npm stands for Node Package Manager and it is the default package manager for Node.js. It is written entirely in JavaScript, developed by  Isaac Z. Schlueter, it was initially released on January 12, 2010. The npm manages all the packages and modules for node.js and consists of command-line client npm. It gets installed into the system with the installation of node.js. The required packages and modules in the Node project are installed using npm. A package contains all the files needed for a module and modules are the JavaScript libraries that can be included in the Node project according to the requirement of the project.
Execute package with npm: 
By typing the local path: You have to write down the local path of your package like below:
./node_modules/.bin/your-package-name
Locally installed: You have to open the package.json file and write down the below scripts:
{
    "name": "Your app",
    "version":  "1.0.0",
    "scripts":  {
            "your-package":  "your-package-name"
     }
}
To run package: After that, you can run your package by running the below command: 
npm run your-package-name
NPX: The npx stands for Node Package Execute and it comes with the npm, when you installed npm above 5.2.0 version then automatically npx will installed. It is an npm package runner that can execute any package that you want from the npm registry without even installing that package. The npx is useful during a single time use package. If you have installed npm below 5.2.0 then npx is not installed in your system. You can check npx is installed or not by running the following command:
npx -v
If npx is not installed you can install that separately by running the below command.
npm install -g npx
Execute package with npx: 
Directly runnable: You can execute your package without installation, to do so run the following command.
npx your-package-name
Differences between npm and npx:
 npm 
npx
 
simranarora5sos
robinmckenzie2
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Node.js forEach() function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
How to update a Python/tkinter label widget?

Tkinter comes with a handy built-in functionality to handle common text and images related objects. A label widget annotates the user interface with text and images. We can provide any text or images to the label widget so that it displays in the application window.
Let us suppose that for a particular application, we need to update the label widget. A label widget is a container that can have either text of image. In the following example, we will update the label image by configuring a button.
#Import the required library
from tkinter import *
from PIL import Image,ImageTk
from tkinter import ttk

#Create an instance of tkinter frame
win= Tk()

#Define geometry of the window
win.geometry("750x450")

#Define a Function to update to Image
def update_img():
   img2=ImageTk.PhotoImage(Image.open("logo.png"))
   label.configure(image=img2)
   label.image=img2

#Load the Image
img1= ImageTk.PhotoImage(Image.open("logo1.png"))

#Create a Label widget
label= Label(win,image= img1)
label.pack()

#Create a Button to handle the update Image event
button= ttk.Button(win, text= "Update", command= update_img)
button.pack(pady=15)
win.bind("<Return>", update_img)

win.mainloop()
Running the above code will display a window that contains a label with an image. The Label image will get updated when we click on the “update” button.
Now, click the "Update" button to update the label widget and its object.
Python – Extract Keys with specific Value Type

11 Oct, 2020
Given a dictionary, extract all the keys, whose values are of given type.
Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = int Output : [‘gfg’, ‘geeks’] Explanation : gfg and geeks have integer values.
Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = str Output : [‘is’] Explanation : is has string value. 
Method #1 : Using loop + isinstance() 
In this, we check for data type using isinstance(), and iterate for all the values using loop.
Python3
# Python3 code to demonstrate working of# Extract Keys with specific Value Type# Using loop + isinstance()  # initializing dictionarytest_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing typetarg_type = int  res = []for key, val in test_dict.items():      # checking for values datatype    if isinstance(val, targ_type):        res.append(key)  # printing resultprint("The extracted keys : " + str(res))
Output:
The original dictionary is : {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4}The extracted keys : [‘gfg’, ‘best’, ‘geeks’]
Method #2 : Using list comprehension + isinstance()
Similar to above method, one-liner shorthand to solve this problem using list comprehension.
Python3
# Python3 code to demonstrate working of# Extract Keys with specific Value Type# Using list comprehension + isinstance()  # initializing dictionarytest_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing typetarg_type = int  # one-liner to solve the problemres = [key for key, val in test_dict.items() if isinstance(val, targ_type)]  # printing resultprint("The extracted keys : " + str(res))
Output:
The original dictionary is : {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4}The extracted keys : [‘gfg’, ‘best’, ‘geeks’]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL | DROP USER

03 Mar, 2018
The DROP USER statement in MySQL can be used to remove a user account along with its privileges from the MySQL completely.But before using the drop user statement, the privileges of the user should be revoked or in other words, if a user has no privileges then the drop user statement can be used to remove a user from the Mysql database server.
Syntax:
DROP USER 'user'@'host';

Parameters:1. User:It is the user name of the user account you want to drop.2. Host:It is the host server name of the user account.The user name should be in the following format‘user_name’@’host_name’.
Suppose there are 4 users in the MySQL database server as listed below:
We can drop a single user account as well as multiple user accounts using a single DROP USER statement as shown below:
Dropping a single user using the DROP USER statement: To drop the user account with the username “gfguser1”, the drop user statement should be executed as follows:Syntax:Output:Table after execution of the drop user statement will be as follows:
Syntax:Output:Table after execution of the drop user statement will be as follows:
Dropping multiple users using the DROP USER statement: The Drop User statement can be used to drop multiple user accounts at once. To drop two user account “gfguser2” and “gfguser1” from the table mentioned above,the drop user statement should be executed as follows:Syntax:Output:Table after execution of the above drop user statement will be as follows:
Syntax:Output:Table after execution of the above drop user statement will be as follows:
Note: In case the DROP USER statement is executed for an user account when the session for this account is active then it will not effect that account until it’s session gets closed. The user account will be dropped after its session gets closed and will not be able to login any more.
References:
https://dev.mysql.com/doc/refman/5.7/en/drop-user.html
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Window functions in SQL
SQL Correlated Subqueries
Difference between DELETE and TRUNCATE
Placeholder in Tkinter

24 Jan, 2021
Prerequisite: 
Python GUI – tkinter
Bind – Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
What is a placeholder and how can it be implemented using tkinter:
In programming, a placeholder may be a character, word, or string of characters that briefly takes the place of the final data. For instance, an applied scientist might recognize that she desires a precise range of values or variables, however does not however recognize what to input.
The Placeholder attribute is used to give hint that tells what input is expected by input field, or we can say it will give the short hint that is displayed within the input field before the user enters a value.
In Tkinter there is no in-built method or property for placeholder but it can still be executed using the modules’ inbuilt functions.
Approach:
Import module
Create Normal Tkinter Window
Add Entry box
Syntax:
Entry(Object Name, **attr)
Add placeholder, here it is done using insert() and then the same is bonded to the box
Syntax:
insert(index) 
Execute code
Program:
Python3
# Import Modulefrom tkinter import *  # Create Tkinter Objectroot = Tk()  # Set geometryroot.geometry('400x400')  # call function when we click on entry boxdef click(*args):    playlist_url.delete(0, 'end')  # call function when we leave entry boxdef leave(*args):    playlist_url.delete(0, 'end')    playlist_url.insert(0, 'Enter Text:- ')    root.focus()    # Add Entry Boxplaylist_url = Entry(root, width=60)  # Add text in Entry boxplaylist_url.insert(0, 'Enter Text:- ')playlist_url.pack(pady=10)  # Use bind methodplaylist_url.bind("<Button-1>", click)playlist_url.bind("<Leave>", leave)  # Execute Tkinterroot.mainloop()
Output:
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Drop a list of rows from a Pandas DataFrame

30 Nov, 2021
Let us see how to drop a list of rows in a Pandas DataFrame. We can do this using the drop() function. We will also pass inplace = True as it makes sure that the changes we make in the instance are stored in that instance without doing any assignmentOver here is the code implementation of how to drop list of rows from the table :
Example 1 :  
Python3
# import the moduleimport pandas as pd  # creating a DataFramedictionary = {'Names':['Simon', 'Josh', 'Amen', 'Habby',                       'Jonathan', 'Nick'],              'Countries':['AUSTRIA', 'BELGIUM', 'BRAZIL',                           'FRANCE', 'INDIA', 'GERMANY']}table = pd.DataFrame(dictionary, columns = ['Names', 'Countries'],                     index = ['a', 'b', 'c', 'd', 'e', 'f'])  display(table)  # gives the table with the dropped rowsdisplay("Table with the dropped rows")display(table.drop(['a', 'd']))  # gives the table with the dropped rows# shows the reduced table for the given command onlydisplay("Reduced table for the given command only")display(table.drop(table.index[[1, 3]]))  # it gives none but it makes changes in the tabledisplay(table.drop(['a', 'd'], inplace = True))  # final tableprint("Final Table")display(table)  # table after removing range of rows from 0 to 2(not included)table.drop(table.index[:2], inplace = True)  display(table)
Output :  
 
Example 2 : 
Python3
# creating a DataFrame   data = {'Name' : ['Jai', 'Princi', 'Gaurav', 'Anuj'],        'Age' : [27, 24, 22, 32],        'Address' : ['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],        'Qualification' : ['Msc', 'MA', 'MCA', 'Phd']}table = pd.DataFrame(data) # original DataFramedisplay("Original DataFrame")display(table) # drop 2nd rowdisplay("Dropped 2nd row")display(table.drop(1))
Output :  
 
saurabh1990aror
singghakshay
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
SWING - ActionListener Interface

The class which processes the ActionEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object's actionPerformed method is invoked.
Following is the declaration for java.awt.event.ActionListener interface −
public interface ActionListener
   extends EventListener

void actionPerformed(ActionEvent e)
Invoked when an action occurs.
This interface inherits methods from the following interfaces −
java.awt.EventListener
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showActionListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      
      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            
      JButton okButton = new JButton("OK");

      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);
      mainFrame.setVisible(true); 
   }
   class CustomActionListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }	
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output.
How to concatenate two JavaScript objects with plain JavaScript ?

Suppose we have two objects defined like this −
const obj1 = {
   id1: 21,
   name1: "Kailash"
};
const obj2 = {
   id2: 20,
   name2: "Shankar"
};
We are required to write a JavaScript function that takes in two such objects and merges into a single object.
In other words, we are required to more or less implement the functionality of Object.assign() function.
The code for this will be −
const obj1 = {
   id1: 21,
   name1: "Kailash"
};
const obj2 = {
   id2: 20,
   name2: "Shankar"
};
const concatObjects = (...sources) => {
   const target = {};
   sources.forEach(el => {
      Object.keys(el).forEach(key => {
         target[key] = el[key];
      });
   });
   return target;
}
console.log(concatObjects(obj1, obj2));
And the output in the console will be −
{ id1: 21, name1: 'Kailash', id2: 20, name2: 'Shankar' }
List equals() Method in Java with Examples

02 Jan, 2019
This method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal.
Syntax:
boolean equals(Object o)
Parameters: This function has a single parameter which is object to be compared for equality.
Returns: This method returns True if lists are equal.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(10);        l.add(15);        l.add(20);        System.out.println(l);          // Initializing another list        List<Integer> l2 = new ArrayList<Integer>();        l2.add(100);        l2.add(200);        l2.add(300);        System.out.println(l2);          if (l.equals(l2))            System.out.println("Equal");        else            System.out.println("Not equal");    }}
[10, 15, 20]
[100, 200, 300]
Not equal

Program 2: Below is the code to show implementation of list.addAll() using Linkedlist.
// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(10);        l.add(15);        l.add(20);        System.out.println(l);          // Initializing another list        List<Integer> l2 = new ArrayList<Integer>();        l2.add(10);        l2.add(15);        l2.add(20);        System.out.println(l2);          if (l.equals(l2))            System.out.println("Equal");        else            System.out.println("Not equal");    }}
[10, 15, 20]
[10, 15, 20]
Equal

Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
info command in Linux with Examples

22 May, 2019
infocommand reads documentation in the info format. It will give detailed information for a command when compared with the man page. The pages are made using the texinfo tools because of which it can link with other pages, create menus and easy navigation.
Syntax:
info [OPTION]... [MENU-ITEM...]
Options:
-a, –all: It use all matching manuals.
-k, –apropos=STRING: It look up STRING in all indices of all manuals.
-d, –directory=DIR: It add DIR to INFOPATH.
-f, –file=MANUAL: It specify Info manual to visit.
-h, –help: It display this help and exit.
-n, –node=NODENAME: It specify nodes in first visited Info file.
-o, –output=FILE: It output selected nodes to FILE.
-O, –show-options, –usage: It go to command-line options node.
-v, –variable VAR=VALUE: It assign VALUE to Info variable VAR.
–version: It display version information and exit.
-w, –where, –location: It print physical location of Info file.
Examples:
-a : It use all matching manuals and display them for a particular command. info -a cvs 
 info -a cvs 
-k : It look up STRING in all indices of all manuals and then display the same. info -k cvs 
 info -k cvs 
-d : It adds DIR to INFOPATH and also display the same. info -d cvs 
 info -d cvs 
-O : It go to command-line options node for a particular command and display the same. info -O cvs 
 info -O cvs 
-w Command : It print physical location of Info file. info -w cvs 
 info -w cvs 
Note:
To check for the manual page of info command, use the following command:man info
man info
To check the help page of info command, use the following command:info --help 
info --help 
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Array of multiples - JavaScript

We are required to write a JavaScript function that takes in two numbers, say m and n, and it returns an array of first n multiples of m.
For example − If the numbers are 4 and 6
Then the output should be −
const output = [4, 8, 12, 16, 20, 24]
Following is the code −
const num1 = 4;
const num2 = 6;
const multiples = (num1, num2) => {
   const res = [];
   for(let i = num1; i <= num1 * num2; i += num1){
      res.push(i);
   };
   return res;
};
console.log(multiples(num1, num2));
Following is the output in the console −
[ 4, 8, 12, 16, 20, 24 ]
Font Awesome - File Type Icons

This chapter explains the usage of Font Awesome File Type icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">

      <style>
         i.custom {font-size: 2em; color: gray;}
      </style>
		
   </head>
	
   <body>
      <i class = "fa fa-adjust custom"></i>
   </body>
	
</html>
The following table shows the usage and the results of Font Awesome File Type icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Float and Double in C

Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.
Here is the syntax of float in C language,
float variable_name;
Here is an example of float in C language,
 Live Demo
#include<stdio.h>
#include<string.h>
int main() {
   float x = 10.327;
   int y = 28;
   printf("The float value : %f\n", x);
   printf("The sum of float and int variable : %f\n", (x+y));
   return 0;
}
The float value : 10.327000
The sum of float and int variable : 38.327000
Double is also a datatype which is used to represent the floating point numbers. It is a 64-bit IEEE 754 double precision floating point number for the value. It has 15 decimal digits of precision.
Here is the syntax of double in C language,
double variable_name;
Here is an example of double in C language,
 Live Demo
#include<stdio.h>
#include<string.h>
int main() {
   float x = 10.327;
   double y = 4244.546;
   int z = 28;
   printf("The float value : %f\n", x);
   printf("The double value : %f\n", y);
   printf("The sum of float,
   double and int variable : %f\n", (x+y+z));
   return 0;
}


The float value : 10.327000
The double value : 4244.546000
The sum of float, double and int variable : 4282.873000
How to compile 32-bit program on 64- bit gcc in C and C++

Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use this feature.
At first, we have to check the current target version of the gcc compiler. To check this, we have to type this command.
gcc –v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
...........
...........
...........
Here it is showing that Target is x86_64. So we are using the 64-bit version of gcc. Now to use the 32-bit system, we have to write the following command.
gcc –m32 program_name.c
Sometimes this command may generate some error like below. This indicates that the standard library of gcc is missing. In that situation we have to install them.
In file included from test_c.c:1:0:
/usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file
or directory
#include <bits/libc-header-start.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
Now, to install the standard library for gcc, we have to write the following commands.
sudo apt-get install gcc-multilib
sudo apt-get install g++-multilib
Now by using this code we will see the differences of executing in 32-bit system and the 64-bit system.
#include<stdio.h>
main(){
   printf("The Size is: %lu\n", sizeof(long));
}
$ gcc test_c.c
test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main(){
^~~~
$ ./a.out
The Size is: 8
$ gcc -m32 test_c.c
test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main(){
^~~~
test_c.c: In function ‘main’:
test_c.c:4:28: warning: format ‘%lu’ expects argument of type ‘long unsigned
int’, but argument 2 has type ‘unsigned int’ [-Wformat=]
printf("The Size is: %lu\n", sizeof(long));
~~^
%u
$ ./a.out
The Size is: 4
Explain Asynchronous vs Deferred JavaScript - GeeksforGeeks

26 Mar, 2020
Generally, when we use a script tag to load any JavaScript code, the HTML parsing is paused by the browser when it encounters the script tag and it starts to download the JavaScript file first. The HTML elements script tag will not be executed until the browser is done with downloading the script and executing it. The browser waits till the script gets downloaded, executed and after this, it processes the rest of the page.
In modern browsers, the script tends to be larger than HTML file, hence their download size is large and processing time will be longer. This increases the load time of the page and restricts the user to navigate through the website. To solve this problem, async and defer attributes come into play.
Syntax: A normal script is included in the page in the following way.
<script src = "script.js"></script>
When HTML parser finds this element, a request is sent to the server to get the script.
Asynchronous: When we use the async attribute the script is downloaded asynchronously with the rest of the page without pausing the HTML parsing and the contents of the page are processed and displayed. Once the script is downloaded, the HTML parsing will be paused and the script’s execution will happen. Once the execution is done, HTML parsing will then resume. The page and other scripts don’t wait for async scripts and async scripts also don’t wait for them. It is great for independent scripts and externally located scripts.
Syntax:<script async src = "script.js"></script>
<script async src = "script.js"></script>
Deferred: The defer attribute tells the browser not to interfere with the HTML parsing and only to execute the script file once the HTML document has been fully parsed. Whenever a script with this attribute is encountered, the downloading of the script starts asynchronously in the background and when the scripts get downloaded, it is executed only after the HTML parsing is finished.
Syntax:<script defer src = "script.js"></script>
<script defer src = "script.js"></script>
Asynchronous vs Deferred:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create an AWS session using Boto3 library in Python?

When a user wants to use AWS services using lambda or programming code, a session needs to set up first to access AWS services.
An AWS session could be default as well as customized based on needs.
Problem Statement − Use Boto3 library in Python to create an AWS session.
Step 1 − To create an AWS session, first set up authentication credentials. Users can find it in IAM console or alternatively, create the credential file manually. By default, its location is at ~/.aws/credentials
Example
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
aws_session_token = YOUR_SESSION_TOKEN
region = REGION_NAME
Step 2 − Install Boto3 using the command - pip install boto3
Step 3 − Import the Boto3 library.
Step 4 − If creating the session with default credential, use Session() with no parameter.
Step 5 − If session is customized, pass the following parameters −
aws_access_key_id (string) -- AWS access key ID
aws_access_key_id (string) -- AWS access key ID
aws_secret_access_key (string) -- AWS secret access key
aws_secret_access_key (string) -- AWS secret access key
aws_session_token (string) -- AWS temporary session token
aws_session_token (string) -- AWS temporary session token
region_name (string) -- Default region when creating new connections
region_name (string) -- Default region when creating new connections
profile_name (string) -- The name of a profile to use. If not given, then the default profile is used.
profile_name (string) -- The name of a profile to use. If not given, then the default profile is used.
The following code creates an AWS session for default as well as customized credentials −
import boto3
# To create default session:
def create_aws_session():
session = boto3.session.Session()
#it creates the default session and can use to connect with any AWS service
   return session
print(create_aws_session())

# To Create customized session:
def create_customized_session(aws_access_key, aws_secret_key, aws_token,
region_name=None,profile_name=None):
   session = boto3.session.Session(aws_access_key_id=aws_access_key,
                                   aws_secret_access_key=aws_secret_key,
                                   aws_session_token = aws_token,
                                   region_name=region_name,
                                   profile_name = profile_name)
   # Here, region_name and profile_name are optional parameters and default value is None
   Print(session)
return session
#if default region_name is not present or NONE and region_name is not
passed in #credential file/calling parameter
Session(region_name=None)
Session(region_name=None)
#if default region_name is present and region_name is passed in
credential file/calling #parameter
Session(region_name=YOUR_REGION_NAME)
Session(region_name= YOUR_REGION_NAME)
PySpark - SparkConf

To run a Spark application on the local/cluster, you need to set a few configurations and parameters, this is what SparkConf helps with. It provides configurations to run a Spark application. The following code block has the details of a SparkConf class for PySpark.
class pyspark.SparkConf (
   loadDefaults = True, 
   _jvm = None, 
   _jconf = None
)

Initially, we will create a SparkConf object with SparkConf(), which will load the values from spark.* Java system properties as well. Now you can set different parameters using the SparkConf object and their parameters will take priority over the system properties.
In a SparkConf class, there are setter methods, which support chaining. For example, you can write conf.setAppName(“PySpark App”).setMaster(“local”). Once we pass a SparkConf object to Apache Spark, it cannot be modified by any user.
Following are some of the most commonly used attributes of SparkConf −
set(key, value) − To set a configuration property.
set(key, value) − To set a configuration property.
setMaster(value) − To set the master URL.
setMaster(value) − To set the master URL.
setAppName(value) − To set an application name.
setAppName(value) − To set an application name.
get(key, defaultValue=None) − To get a configuration value of a key.
get(key, defaultValue=None) − To get a configuration value of a key.
setSparkHome(value) − To set Spark installation path on worker nodes.
setSparkHome(value) − To set Spark installation path on worker nodes.
Let us consider the following example of using SparkConf in a PySpark program. In this example, we are setting the spark application name as PySpark App and setting the master URL for a spark application to → spark://master:7077.
The following code block has the lines, when they get added in the Python file, it sets the basic configurations for running a PySpark application.
---------------------------------------------------------------------------------------
from pyspark import SparkConf, SparkContext
conf = SparkConf().setAppName("PySpark App").setMaster("spark://master:7077")
sc = SparkContext(conf=conf)
---------------------------------------------------------------------------------------

 Print
 Add Notes
 Bookmark this page
How to convert Number to Boolean in JavaScript ? - GeeksforGeeks

08 Jan, 2021
We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”. 
Syntax:  
Boolean(variable/expression)
Example:  
HTML
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">            GeeksforGeeks        </h1>          <h4>            Click the button to change the            number value into boolean.        </h4>          <button onclick="myFunction()">Change</button>          <p>The number value of the variable is :</p>          <p id="result"></p>          <script>              // Initializing boolvalue as true             var numvalue = 1;              // JavaScript program to illustrate boolean             // conversion using ternary operator             function myFunction() {                  document.getElementById("result")                    .innerHTML = Boolean(numvalue);            }         </script>    </center></body>  </html>
Note: If the above Boolean() method is called as Boolean(!numvalue), it shows the result as “false“. Similarly if it is called as Boolean(!!numvalue), it gives the result as “true“.
Output:
Before clicking on button:
After clicking on button:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
How to create footer to stay at the bottom of a Web page?
Making a div vertically scrollable using CSS
How to Upload Image into Database and Display it using PHP ?
Build a Survey Form using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
Display the Operating System name in Java

Use the System.getProperty() method in Java to get the Operating System name.
It’s syntax is −
String getProperty(String key)
Above, the key is the name of the system property. Since, we want the OS name, therefore we will add the key as −
os.name
 Live Demo
public class Demo {
    public static void main(String[] args) {
       System.out.print("Operating System: ");
       System.out.println(System.getProperty("os.name"));
    }
}
Operating System: Linux
Find the Second Largest Element in a Linked List in C++

Here we will see the second largest element in the linked list. Suppose there are n different nodes with numerical values. So if the list is like [12, 35, 1, 10, 34, 1], then second largest element will be 34.
This process is similar to the finding of second largest element in an array, we will traverse through the list and find second largest element by comparing.
#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node *next;
};
void prepend(Node** start, int new_data) {
   Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = NULL;
   if ((*start) != NULL){
      new_node->next = (*start);
      *start = new_node;
   }
   (*start) = new_node;
}
int secondLargestElement(Node *start) {
   int first_max = INT_MIN, second_max = INT_MIN;
   Node *p = start;
   while(p != NULL){
      if (p->data > first_max) {
         second_max = first_max;
         first_max = p->data;
      }else if (p->data > second_max)
         second_max = p->data;
         p = p->next;
   }
   return second_max;
}
int main() {
   Node* start = NULL;
   prepend(&start, 15);
   prepend(&start, 16);
   prepend(&start, 10);
   prepend(&start, 9);
   prepend(&start, 7);
   prepend(&start, 17);
   cout << "Second largest element is: " << secondLargestElement(start);
}
Second largest element is: 16
Enum Methods in Java

Let us learn about some of the methods in Java.
Get the ordinal of an enumeration constant in Java using ordinal() method in Java.
The following is an example −
 Live Demo
public class Demo {
   enum Devices {
      LAPTOP, MOBILE, TABLET, DESKTOP;
   }
   public static void main(String[] args) {
      Devices d1, d2, d3, d4;
      d1 = Devices.LAPTOP;
      d2 = Devices.LAPTOP;
      d3 = Devices.TABLET;
      d4 = Devices.DESKTOP;
      System.out.println("Ordinal Values...");
      for(Devices d : Devices.values()) {
         System.out.print(d+" = ");
         System.out.println(d.ordinal());
      }
   }
}
Ordinal Values...
LAPTOP = 0
MOBILE = 1
TABLET = 2
DESKTOP = 3
It returns true if the specified object is equal to this enum constant.
Let us see an example −
 Live Demo
public class Demo {
   enum Devices {
   LAPTOP, MOBILE, TABLET;
}
public static void main(String[] args) {
   Devices d1, d2, d3;
   d1 = Devices.LAPTOP;
   d2 = Devices.LAPTOP;
   d3 = Devices.TABLET;
   if(d1.equals(d2))
   System.out.println("Devices are same.");
   else
      System.out.println("Devices are different.");
   }
}
Devices are same.
CSS - Pseudo-class :link

The :link pseudo-class is used to add special effect to an unvisited link.
While defining pseudo-classes in a <style>...</style> block, following points should be taken care −
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
Pseudo-class names are not case-sensitive.
Pseudo-class names are not case-sensitive.
Pseudo-class are different from CSS classes but they can be combined.
Pseudo-class are different from CSS classes but they can be combined.
color − Any valid color value.
color − Any valid color value.
Anchor / Link element.
Following is the example which demonstrates how to use :link class to set the link color.
<html>
   <head>
      <style type = "text/css">
         a:link {color:#000000}
      </style>
   </head>

   <body>
      <a href = "/html/index.htm">Black Link</a>
   </body>
</html> 
This will produce following black link −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
SciPy - Environment Setup

Standard Python distribution does not come bundled with any SciPy module. A lightweight alternative is to install SciPy using the popular Python package installer,
pip install pandas

If we install the Anaconda Python package, Pandas will be installed by default. Following are the packages and links to install them in different operating systems.
Anaconda (from  https://www.continuum.io) is a free Python distribution for the SciPy stack. It is also available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available free, as well as for commercial distribution with a full SciPy stack for Windows, Linux and Mac.
Python (x,y) − It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from https://python-xy.github.io/)
Package managers of respective Linux distributions are used to install one or more packages in the SciPy stack.
We can use the following path to install Python in Ubuntu.
sudo apt-get install python-numpy python-scipy 
python-matplotlibipythonipython-notebook python-pandas python-sympy python-nose

We can use the following path to install Python in Fedora.
sudo yum install numpyscipy python-matplotlibipython python-pandas 
sympy python-nose atlas-devel

 Print
 Add Notes
 Bookmark this page
Even Number With Prime Sum

All even numbers from 4, can be expressed as a sum of two prime numbers. Sometimes a number can have more than one sum of the prime number combination.
For an example the number 10 = (5 + 5) and (7 + 3)
This algorithm will find all of the combinations of prime sums for a given number.  When one number x is prime, then only we will check whether (number - x) is prime or not, if yes, the sum of x and (number – x) represents the even number.
Input:
Even number: 70
Output:
Prime sums
70 = 3 + 67
70 = 11 + 59
70 = 17 + 53
70 = 23 + 47
70 = 29 + 41
dispPrimeSum(num)
Input − The even number.
Output: Display the number using the sum of some prime numbers.
Begin
   if num is odd, then
      exit
   for i := 3 to num/2, do
      if i is prime, then
         if (num - i) is prime, then
            display ‘’num = i + (num – i)”
   done
End
#include<iostream>
using namespace std;

int isPrime(int number) {        //check whether number is prime or not
   int lim;
      lim = number/2;

   for(int i = 2; i<=lim; i++) {
      if(number % i == 0)
         return 0;            //The number is not prime
   }
   return 1;                 //The number is prime
}

void displayPrimeSum(int num) {
   string res;
   if(num%2 != 0) {         //when number is an odd number
      cout << "Invalid Number";
      exit(1);
   }

   for(int i = 3; i <= num/2; i++) {
      if(isPrime(i)) {         //if i is a prime number
         if(isPrime(num-i)) {  //num - i is also prime, then
            cout << num <<"= "<<i << " + "<<(num-i)<<endl;
         }
      }
   }
}

main() {
   int num;
   cout << "Enter an even number: "; cin >> num;
   displayPrimeSum(num);
}
Enter an even number: 70
70 = 3 + 67
70 = 11 + 59
70 = 17 + 53
70 = 23 + 47
70 = 29 + 41
Apex - Invoking

Apex invoking refers to the process of executing the Apex class. Apex class can only be executed when it is invoked via one of the ways listed below −
Triggers and Anonymous block
Triggers and Anonymous block
A trigger invoked for specified events
A trigger invoked for specified events
Asynchronous Apex
Asynchronous Apex
Scheduling an Apex class to run at specified intervals, or running a batch job
Scheduling an Apex class to run at specified intervals, or running a batch job
Web Services class
Web Services class
Apex Email Service class
Apex Email Service class
Apex Web Services, which allow exposing your methods via SOAP and REST Web services
Apex Web Services, which allow exposing your methods via SOAP and REST Web services
Visualforce Controllers
Visualforce Controllers
Apex Email Service to process inbound email
Apex Email Service to process inbound email
Invoking Apex Using JavaScript
Invoking Apex Using JavaScript
The Ajax toolkit to invoke Web service methods implemented in Apex
The Ajax toolkit to invoke Web service methods implemented in Apex
We will now understand a few common ways to invoke Apex.
You can invoke the Apex class via execute anonymous in the Developer Console as shown below −
Step 1 − Open the Developer Console.
Step 2 − Click on Debug.
Step 3 − Execute anonymous window will open as shown below. Now, click on the Execute
button −
Step 4 − Open the Debug Log when it will appear in the Logs pane.
You can call an Apex class from Trigger as well. Triggers are called when a specified event occurs and triggers can call the Apex class when executing.
Following is the sample code that shows how a class gets executed when a Trigger is called.
// Class which will gets called from trigger
public without sharing class MyClassWithSharingTrigger {

   public static Integer executeQuery (List<apex_customer__c> CustomerList) {
      // perform some logic and operations here
      Integer ListSize = CustomerList.size();
      return ListSize;
   }
}

// Trigger Code
trigger Customer_After_Insert_Example on APEX_Customer__c (after insert) {
   System.debug('Trigger is Called and it will call Apex Class');
   MyClassWithSharingTrigger.executeQuery(Trigger.new);  // Calling Apex class and 
                                                         // method of an Apex class
}

// This example is for reference, no need to execute and will have detail look on 
// triggers later chapters.
Apex class can be called from the Visualforce page as well. We can specify the controller or the controller extension and the specified Apex class gets called.
VF Page Code
Apex Class Code (Controller Extension)

    14 Lectures 
     2 hours 

 Vijay Thapa

    7 Lectures 
     2 hours 

 Uplatz

    29 Lectures 
     6 hours 

 Ramnarayan Ramakrishnan

    49 Lectures 
     3 hours 

 Ali Saleh Ali

    10 Lectures 
     4 hours 

 Soham Ghosh

    48 Lectures 
     4.5 hours 

 GUHARAJANM
 Print
 Add Notes
 Bookmark this page