code-rag-bench/online-tutorials huggingface dataset:
HashMap remove() Method in Java

03 May, 2021
The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.Syntax:  
Hash_Map.remove(Object key)
Parameters: The method takes one parameter key whose mapping is to be removed from the Map.Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL.Below programs illustrates the working of java.util.HashMap.remove() method: Program 1: When passing an existing key.  
Java
// Java code to illustrate the remove() methodimport java.util.*; public class Hash_Map_Demo {public static void main(String[] args) {             // Creating an empty HashMap    HashMap<Integer, String> hash_map = new HashMap<Integer, String>();     // Mapping string values to int keys    hash_map.put(10, "Geeks");    hash_map.put(15, "4");    hash_map.put(20, "Geeks");    hash_map.put(25, "Welcomes");    hash_map.put(30, "You");     // Displaying the HashMap    System.out.println("Initial Mappings are: " + hash_map);     // Removing the existing key mapping    String returned_value = (String)hash_map.remove(20);     // Verifying the returned value    System.out.println("Returned value is: "+ returned_value);     // Displaying the new map    System.out.println("New map is: "+ hash_map);}}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: Geeks
New map is: {25=Welcomes, 10=Geeks, 30=You, 15=4}
 
Program 2: When passing a new key.  
Java
// Java code to illustrate the remove() methodimport java.util.*;   public class Hash_Map_Demo {   public static void main(String[] args) {               // Creating an empty HashMap      HashMap<Integer, String> hash_map = new HashMap<Integer, String>();         // Mapping string values to int keys      hash_map.put(10, "Geeks");      hash_map.put(15, "4");      hash_map.put(20, "Geeks");      hash_map.put(25, "Welcomes");      hash_map.put(30, "You");        // Displaying the HashMap      System.out.println("Initial Mappings are: " + hash_map);        // Removing the new key mapping      String returned_value = (String)hash_map.remove(50);        // Verifying the returned value      System.out.println("Returned value is: "+ returned_value);        // Displaying the new map      System.out.println("New map is: "+ hash_map);   }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: null
New map is: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
 
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. 
simranarora5sos
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Sympy Polygon.distance() method

01 Aug, 2020
In Sympy, the function Polygon.distance() is used to return the shortest distance between the given polygon and o. If o is a point, then given polygon does not need to be convex. But If o is another polygon then, the given polygon and o must be convex.
Syntax: Polygon.distance(o)

Parameters:
 o:Point or Polygon

Returns: the shortest distance between the given polygon and o.
Example #1:
Python3
# import sympy import Point, Polygonfrom sympy import Point, Polygon  # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 2), (0, 0), (1, 0), (1, 2)])  # creating polygon using Polygon()poly = Polygon(p1, p2, p3, p4)  # using distance()shortestDistance = poly.distance(Point(3, 5))  print(shortestDistance)
Output:
sqrt(13)
Example #2:
Python3
# import sympy import Point, Polygon, RegularPolygonfrom sympy import Point, Polygon, RegularPolygon  # creating points using Point()p1, p2 = map(Point, [(0, 0), (7, 5)])  # creating polygon using Polygon() and RegularPolygon()poly = Polygon(*RegularPolygon(p1, 1, 3).vertices)  # using distance()shortestDistance = poly.distance(p2)  print(shortestDistance)
Output:
sqrt(61)
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to implement Count (*) as variable from MySQL to display the number of records in a table?

The alias name can be used as a variable name in MySQL as shown in the below syntax −
select count(*) AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable695 (
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable695 values('Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable695 values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('Mike');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable695;
This will produce the following output -
+-----------+
| FirstName |
+-----------+
| Chris     |
| Robert    |
| David     |
| Mike      |
+-----------+
4 rows in set (0.00 sec)
Following is the query to consider count(*) as variable in MySQL −
mysql> select count(*) AS TOTAL_NO_OF_RECORDS from DemoTable695 ;
This will produce the following output -
+---------------------+
| TOTAL_NO_OF_RECORDS |
+---------------------+
| 4                   |
+---------------------+
1 row in set (0.02 sec)
How to create dynamic HTML pages ?

18 May, 2021
In this article, we will know How to create a dynamic HTML page using HTML, CSS, and JavaScript. Let us first know what actually is a dynamic HTML page.
Dynamic HTML page, as the name suggests refers to an HTML page that is dynamic in such a way that it is customizable and changeable according to user input. For example:-
Using CSS we can change the background color of the web page each time the user clicks a button on the webpage.
Using JavaScript we can ask the user to enter his/her name and then display it dynamically on the webpage.
If you want to get to know more about Dynamic HTML pages, you can have a look at this article  DHTML JavaScript.
Let us take some examples to know how to create a dynamic HTML page using HTML and CSS.
Example 1: Taking username as input and dynamically changing the text content of web page
HTML
<!DOCTYPE HTML><html>  <body style="text-align:center;">    <h1>Enter Your Name</h1>          <input id="name" type="text">    <button type="button" onclick="EnterName()">Submit</button>    <p style="color:green"id="demo"></p>        <script>        function EnterName()        {            var x= document.getElementById("name").value;              document.getElementById("demo").innerHTML =                 "Welcome to Geeks For Geeks "+ x ;        }    </script></body>    </html>
Output:
Example 2: Dynamically changing the background color of a webpage on each click 
HTML
<!DOCTYPE HTML><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script></head>  <body style="text-align:center;" id="body">    <h1>Enter Your Color Choice</h1>          <button type="button" onclick="changecolor()">        Color    </button>             <script>        function changecolor()        {            // Generating random color each time            var color = "#"+(Math.random()*16777215|0).toString(16);                          $("body").css("background-color",color);        }    </script></body>    </html>
Output:
HTML-Questions
javascript-basics
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to add string values to a C# list?

To add string values to a list in C#, use the Add() method.
Firstly, declare a string list in C# −
List<string> list1 = new List<string>();
Now add string items −
myList.Add("Jack");
myList.Add("Ben");
myList.Add("Eon");
myList.Add("Tim");
Let us see the complete code −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Demo {
   public class Program {
      public static void Main(String[] args) {
         List<string> myList = new List<string>();
         myList.Add("Jack");
         myList.Add("Ben");
         myList.Add("Eon");
         myList.Add("Tim");

         Console.WriteLine(myList.Count);
      }
   }
}
Rendering elements in React.js

The smallest building blocks of React applications are the elements. Example of an element is −
const message = <h1>Welcome, Steve</h1>;
React DOM updates the actual DOM with the converted react elements. React components are made up of elements.
We will have a parent div element in the main html file . This div can be called as root.
<div id=”app”> </div>
ReactDOM manages everything which is inside the app div. We can add multiple such an isolated div in applications if required.
To render the element it will be passed to the ReactDOM render method −
const message = <h1>Welcome, Steve</h1>;
ReactDOM.render(message, document.getElementById('app'));
This will display a message − Welcome, Steve on browser
React elements are immutable that means once created it cannot be changed. Change will create a new element and update the UI.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
function getCurrentTime() {
   const currentTime = (
      <div>
         <h1>Welcome !</h1>
         <h2>It is {new Date().toLocaleTimeString()}.</h2>
      </div>
   );
   ReactDOM.render(currentTime, document.getElementById('root'));
}
setInterval(getCurrentTime, 1000);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
Make first letter of a string uppercase in JavaScript?

To make first letter of a string uppercase, use toUpperCase() in JavaScript. With that, we will
use charAt(0) since we need to only capitalize the 1st letter.
function replaceWithTheCapitalLetter(values){
   return values.charAt(0).toUpperCase() + values.slice(1);
}
var word="javascript"
console.log(replaceWithTheCapitalLetter(word));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo167.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo167.js
Javascript
RequireJS - Module Loading

Modules are loaded using the define() function in js file. The syntax for loading the module in html file is as shown below −
<script data-main = "main" src = "require.js"></script>
In the script tag given above, main is used to set up packages that are relative to require.js, which in this example are the source packages team1 and team2 −
The following example describe how to define and load the module in RequireJS. Create an html file with the name index.html, and place the following code in it.
<!DOCTYPE html>
<html>
   <head>
      <script data-main = "main" src = "require.js"></script>
   </head>
   
   <body>
      <h2>RequireJS Example</h2>
   </body>
</html>
Create a js file with the name main.js, and place the following code in it.
define(function (require) {
   var team1 = require("./team1");
   var team2 = require("./team2");

   alert("Welcome to Tutorialpoint");
   document.write("<h4>Hyderabad Team: </h4>" + "<br>" + " Team:"+team1.team +"<br>
      "+"Captain:" +team1.captain +"<br>");
   
   document.write("<h4>Bangalore Team: </h4>" + "<br>" + " Team:"+team2.team +"<br>
      "+"Captain:"+team2.captain +"<br>");   
});
Create two more js files with the names team1.js and team2.js, and place the following codes respectively.
For team1 −
define({
   team: "Sunrisers Hyderabad",
   captain : " David Warner"
});
For team2 −
define({
   team: "RCB",
   captain : "Virat Kohli"
});
Open the HTML file in a browser; you will receive an output as in the following screenshot −
Next, click on the "OK" button, you will get another output from modules as in the following screenshot −
 Print
 Add Notes
 Bookmark this page
How to get Python exception text?

If a python code throws an exception, we can catch it and print the type, the error message, traceback and get information like file name and line number in python script where the exception occurred.
We can find the type, value, traceback parameters of the error
Type gives the type of exception that has occurred; value contains error message; traceback contains stack snapshot and many other information details about the error message.
The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts.
Getting exception type, file number and line number in sample code
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno
Explain the Union to pointer in C language

A union is called as a memory location, which is shared by several variables of different data types.
The syntax is as follows −
union uniontag{
   datatype member 1;
   datatype member 2;
   ----
   ----
   datatype member n;
};
For example,
union sample{
   int a;
   float b;
   char c;
};
Given below are the respective declarations of union variable −
Union sample
{
   int a;
   float b;
   char c;
}s;
Union
{
   int a;
   float b;
   char c;
}s;
Union sample
{
   int a;
   float b;
   char c;
};
union sample s;
When union is declared, the compiler automatically creates a variable which hold the largest variable type in the union.
At any time, only one variable can be referred.
Accessing union member is same as the structure.
Generally, the dot operator is used for accessing members.
The arrow operator ( ->) is used for accessing the members
There is no restriction while using data type in a union.
Following is the C program for union to pointer −
 Live Demo
#include<stdio.h>
union abc{
   int a;
   char b;
};
int main(){
   union abc var;
   var.a=90;
   union abc *p=&var;
   printf("%d%c",p->a,p->b);
}
When the above program is executed, it produces the following result −
90Z
How to Find Linux File Creation Time using Debugfs? - GeeksforGeeks

09 Apr, 2021
Everything is treated as a file in Linux, and all the information about a file is stored in inodes, which includes the crucial metadata about a file such as creation time, last modification, etc. Every file in Linux is identified by its inode number.
In this article, we will be using debugf command to find Linux File Creation Time with the help of stat(utility to find file or file system status) command that is used to get  Last Modified Date of File in Linux. Both stat command and Debugfs command together will be used to find actual file creation time in Linux.
Step 1: To find the inode number of the file which we need to know for finding the file creation time and the date we have to use the following command :
$ stat <file name>
Alternatively, ls -i command can also be used that will only show the inode number and skip all the other information.
$ ls -i  <file name>
So now we have got the inode number that is “7342019 ” for the file “tithi.jpeg”, copy that to your clipboard because we are going to need this inode number in our further steps.
Step 2: Find out the root filesystem in which the file resides using the following command:
$ df -h
So here, system the root partition is /dev/sda1, that might be different on your system, so make sure to check it properly and note it down.
Step 3: Now lastly, use the debugfs command for finding the creation time of the file called “tithi.jpeg” by using the following command :-
sudo debugfs -R 'stat <inode number>' /dev/sda1 
In the above result you can see different prefix such as ctime, atime, mtime, crtime, each of these has its own meaning that is:
ctime: file change time Displayed.
atime: file access time Displayed.
mtime: Shows file modification time.
crtime: Shows file creation time. (This is what we needed)
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
Python | sympy.is_odd() method - GeeksforGeeks

12 Oct, 2021
In simpy module, we can test whether a given number n is odd or not using sympy.is_odd() function.
Syntax:  sympy.is_odd(n)
Parameter:  n; number to be tested
Return:  bool value result 

Code #1:
# Python program to check odd number# using sympy.is_odd() method  # importing sympy modulefrom sympy import *  # calling is_odd function on different numbersgeek1 = simplify(30).is_oddgeek2 = simplify(13).is_odd  print(geek1)print(geek2)
Output:
False
True

Code #2:
# Python program to check odd number# using sympy.is_odd() method  # importing sympy modulefrom sympy import *  # calling is_odd function on different numbersgeek = simplify(2).is_odd  print(geek)
Output:
False
sumitgumber28
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Explain division operation in relational algebra (DBMS)?

Query is a question or requesting information. Query language is a language which is used to retrieve information from a database.
Query language is divided into two types −
Procedural language
Procedural language
Non-procedural language
Non-procedural language
Information is retrieved from the database by specifying the sequence of operations to be performed.
For Example: Relational algebra.
Structure Query language (SQL) is based on relational algebra.
Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output.
The different types of relational algebra operations are as follows −
Select operation
Select operation
Project operation
Project operation
Rename operation
Rename operation
Union operation
Union operation
Intersection operation
Intersection operation
Difference operation
Difference operation
Cartesian product operation
Cartesian product operation
Join operation
Join operation
Division operation
Division operation
Union, intersection, difference, cartesian, join, division comes under binary operation (operate on two table).
The division operator is used for queries which involve the ‘all’.
R1 ÷ R2 = tuples of R1 associated with all tuples of R2.
Retrieve the name of the subject that is taught in all courses.
÷
=
The resulting operation must have all combinations of tuples of relation S that are present in the first relation or R.
Retrieve name of employees who work on all the projects that John Smith works on.
Consider the Employee table given below −
÷
Works on the following −
=
The result is as follows
The expression is as follows
Smith <- ΠPno(σEname = ‘john smith’ (employee * works on Pno=Eno))
UInt16.ToString Method in C# with Examples

The UInt16.ToString() method in C# is used to convert the numeric value of the current UInt16 instance to its equivalent string representation.
Following is the syntax −
public override string ToString();
Let us now see an example to implement the UInt16.ToString() method −
using System;
public class Demo {
   public static void Main(){
      ushort val1 = 100;
      ushort val2 = 80;
      Console.WriteLine("Value1 (String representation) = "+val1.ToString());
      Console.WriteLine("Value2 (String representation) = "+val2.ToString());
      bool res = val1.Equals(val2);
      Console.WriteLine("Return value (comparison) = "+res);
      if (res)
         Console.WriteLine("val1 = val2");
      else
         Console.WriteLine("val1 != val2");
   }
}
This will produce the following output −
Value1 (String representation) = 100
Value2 (String representation) = 80
Return value (comparison) = False
val1 != val2
Let us now see another example to implement the UInt16.ToString() method −
using System;
public class Demo {
   public static void Main(){
      ushort val1 = 0;
      ushort val2 = UInt16.MaxValue;
      Console.WriteLine("Value1 (String representation) = "+val1.ToString());
      Console.WriteLine("Value2 (String representation) = "+val2.ToString());
      bool res = val1.Equals(val2);
      Console.WriteLine("Return value (comparison) = "+res);
      if (res)
         Console.WriteLine("val1 = val2");
      else
         Console.WriteLine("val1 != val2");
   }
}
This will produce the following output −
Value1 (String representation) = 0
Value2 (String representation) = 65535
Return value (comparison) = False
val1 != val2
How to get the IP address of android device programmatically?

This example demonstrates how do I get the IP address of android device programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp"
   android:orientation="vertical">
   <TextView
      android:id="@+id/getIPAddress"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="IP address of your Device"
      android:textStyle="bold"
      android:textSize="25sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.getIPAddress);
      WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
      String ipAddress = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
      textView.setText("Your Device IP Address: " + ipAddress);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Check if list contains consecutive numbers in Python

Depending on the needs of our data analysis we may need to check for presence of sequential numbers in a python data container. In the below programs we find out if among the elements of Alist, there are any consecutive numbers.
The sorted function will rearrange the elements of the list in a sorted order. We then apply the range function taking the lowest and highest numbers form the list using min and max functions. We store the results of above operations in two lists and compare them for equality.
 Live Demo
listA = [23,20,22,21,24]
sorted_list = sorted(listA)
#sorted(l) ==
range_list=list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list = sorted(listB)
#sorted(l) ==
range_list=list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")
Running the above code gives us the following result −
listA has consecutive numbers
ListB has no consecutive numbers
The diff function in numpy can find the difference between each of the numbers after they are sorted. We take a sum of this differences. That will match the length of the list if all numbers are consecutive.
 Live Demo
import numpy as np
listA = [23,20,22,21,24]

sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")
Running the above code gives us the following result −
listA has consecutive numbers
ListB has no consecutive numbers
What are the different types of keywords in C language?

Keywords are generally called as pre-defined or reserved words in a programming language. Every keyword in C language performs a specific function in a program.
Keywords cannot be used as variable names.
Keywords cannot be used as variable names.
Keywords have fixed meanings, and that meaning cannot be changed.
Keywords have fixed meanings, and that meaning cannot be changed.
They are the building block of a 'C' program.
They are the building block of a 'C' program.
C supports 32 keywords.
C supports 32 keywords.
All the keywords are written in lowercase letters.
All the keywords are written in lowercase letters.
The different types of keywords are as follows −
Given below is the C program for the Simple Calculator by using the Switch Case −
 Live Demo
#include <stdio.h>
int main(){
   char Operator;
   float num1, num2, result = 0;
   printf("\n Try to Enter an Operator (+, -, *, /) : ");
   scanf("%c", &Operator);
   printf("\n Enter the Values for two Operands: ");
   scanf("%f%f", &num1, &num2);
   switch(Operator){
      case '+': result = num1 + num2;
      break;
      case '-': result = num1 - num2;
      break;
      case '*': result = num1 * num2;
      break;
      case '/': result = num1 / num2;
      break;
      default: printf("\n entered operator is invalid ");
   }
   printf("\n The result of %.2f %c %.2f = %.2f", num1, Operator, num2, result);
   return 0;
}
When the above program is executed, it produces the following result −
Enter an Operator (+, -, *, /) : *
Enter the Values for two Operands: 34 12
The result of 34.00 * 12.00 = 408.00
In the above example, the keywords that are used to perform a simple calculator program are as follows −
Int, char, switch, case, break, float, default, return
These words cannot be used as variables while writing the program.
How to use wildcard in Python regular expression?

The following code uses the Python regex .()dot character for wildcard which stands for any character other than newline.
import re
rex = re.compile('th.s')
l = "this, thus, just, then"
print rex.findall(l)
This gives the output
['this', 'thus']
Java program to count total bits in a number

The total bits in a number can be counted by using its binary representation. An example of this is given as follows −
Number = 9
Binary representation = 1001
Total bits = 4

A program that demonstrates this is given as follows.
 Live Demo
public class Example {
   public static void main(String[] arg) {
      int num = 10;
      int n = num;
      int count = 0;
      while (num != 0) {
         count++;
         num >>= 1;
      } 
      System.out.print("The total bits in " + n + " are " + count);
   }
}
The total bits in 10 are 4

Now let us understand the above program.
First, the number is defined. Then the total bits in the number are stored in count. This is done by using the right shift operator in a while loop. Finally, the total bits are displayed. The code snippet that demonstrates this is given as follows −
int num = 10;
int n = num;
int count = 0;
while (num != 0) {
   count++;
   num >>= 1;
}
System.out.print("The total bits in " + n + " are " + count);
Clojure - Maps

A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator.
A map can be created in two ways, the first is via the hash-map method.
HashMaps have a typical key value relationship and is created by using hash-map function.
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def demokeys (hash-map "z" "1" "b" "2" "a" "3"))
   (println demokeys))
(example)
The above code produces the following output.
{z 1, b 2, a 3}

SortedMaps have the unique characteristic of sorting their elements based on the key element. Following is an example that shows how the sorted map can be created using the sorted-map function.
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def demokeys (sorted-map "z" "1" "b" "2" "a" "3"))
   (println demokeys))
(example)
The above code produces the following output.
{a 3, b 2, z 1}

From the above program you can clearly see that elements in the maps are sorted as per the key value. Following are the methods available for maps.
Returns the value mapped to key, not-found or nil if key is not present.
See whether the map contains a required key.
Returns the map entry for the key.
Returns the list of keys in the map.
Returns the list of values in the map.
Dissociates a key value entry from the map.
Merges two maps entries into one single map entry.
Returns a map that consists of the rest of the maps conj-ed onto the first.
Returns a map containing only those entries in map whose key is in keys.
Renames keys in the current HashMap to the newly defined ones.
Inverts the maps so that the values become the keys and vice versa.
 Print
 Add Notes
 Bookmark this page
How to export class with static methods in Node.js ?

26 May, 2021
We know JS static keyword defines static properties and methods for a class. Static method or properties can not be called from instances of the class. Instead, they’re calling from the class itself.
class Car {
    static run() { console.log('Car running...') }
}

// Error: (intermediate value).run
// is not a function
( new Car() ).run()

// Car running...
Car.run()
Relation between require() and module.exports: By default, module.exports point to an object. The value of module.exports can be literal, function, object, etc. When we export a module, it means we export the value of module.exports. 
The task of require() function is to import the value of module.exports in the module from where it was called. The value returned by the require() function in moduleB is equal to the module.exports object in the moduleA. So, the Relation is shown below.
require() == module.exports
Export class with static method: If you want to export a class with a static method from NodeJS module then the idea is as simple as exporting a class itself. Let’s see some examples. 
 
Step 1: Create a NodeJS project using the following command.
mkdir Project && cd Project
npm init -y
Step 2: Create two JS files in the root directory of your project and name them App.js and myModule.js
Project Structure: It will look like this.
Step 3: Edit myModule.js with the following code. 
myModule.js
// myModule moduleclass Car{    static run() { console.log('Car running...') }}  // Export this modulemodule.exports = Car
We have created a class called Car with static method run() in the myModule.js and export it by assigning the class itself to module.exports
Step 4: Next, edit your App.js with the following code.
App.js
// Import myModuleconst mercedes = require('./myModule')  // Printing dataconsole.log(mercedes)  // Invoke static functionmercedes.run()
In the App.js file, we import the myModule using require() function and assign the return value to the variable name mercedes. So, the class Car directly assigns to mercedes, and now we can invoke the static method run() from mercedes from App.js module. 
Step 5: Run the server using the following command.
node App.js
Output:
[Function: Car]
Car running...
If, you want to export a module in a form of an object then, add class Car as a property of module.exports as shown below:
myModule.js
// myModule moduleclass Car{    static run() { console.log('Car running...') }}  // Export this module// add class Car as a property // of module.exportsmodule.exports = { Car }
App.js
// Importing our moduleconst mercedes = require('./myModule').Car  // Executing run functionmercedes.run()
Run the server using the following command.
node App.js
Output:
Car running...
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Merging nested lists

18 Dec, 2021
Given two nested lists, ‘lst1’ and ‘lst2’, write a Python program to create a new nested list ‘lst3’ out of the two given nested lists, so that the new nested list consist common intersections of both lists as well as the non-intersecting elements.
Examples: 
Input : lst1 = [[5, 9], [8, 2, 6], [3, 4]]
        lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]
Output : [[9, 5], [8], [2, 6], [3, 4], [1]]

Input : lst1 = [['a', 'b', 'c'], ['x']]
        lst2 = [['b', 'c', 'y'], ['x', 'y']]
Output : [['b', 'c'], ['x'], ['y'], ['a']]
Approach #1 : By set intersection using functools.reduce()This method uses the set intersection to compute each intersection, then add any item which is leftover (that is, items appearing on only one of the two lists). We will first use functools.reduce() to yield unique elements of ‘lst1’ and ‘lst2’ and save them to ‘temp1’ and ‘temp2’ respectively. After this, find the set intersection of both the list in ‘lst3’. At last, find the symmetric difference of ‘lst1’ and ‘lst2’, which yields the items which appear in only one of the 2 sets and append it to ‘lst3’.
Python3
# Python3 program to find Greatest common# intersection of two nested listsimport itertoolsimport functools def GCI(lst1, lst2):         temp1 = functools.reduce(lambda a, b: set(a).union(set(b)), lst1)    temp2 = functools.reduce(lambda a, b: set(a).union(set(b)), lst2)         lst3 = [list(set(a).intersection(set(b)))           for a, b in itertools.product(lst1, lst2)           if len(set(a).intersection(set(b))) != 0]         lst3.extend([x] for x in temp1.symmetric_difference(temp2))         return lst3         # Driver codelst1 = [[5, 9], [8, 2, 6], [3, 4]]lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]print(GCI(lst1, lst2))
[[9, 5], [8], [2, 6], [3, 4], [1]]
 
 Approach #2 : By set intersection using filterThis is an efficient approach over approach #1 as it simplifies the intersection. First, flatten the nested lists. Take Intersection using filter() and save it to ‘lst3’. Now find elements either not in lst1 or in lst2, and save them to ‘temp’. Finally, append ‘temp’ to ‘lst3’. 
Python3
# Python3 program to find Greatest common# intersection of two nested listsimport itertoolsfrom functools import reduce def GCI(lst1, lst2):         temp1 = reduce(list.__add__, lst1)    temp2 = reduce(list.__add__, lst2)    lst3 = list(filter(None, [list(set(o1) & set(o2))                     for o1 in lst1 for o2 in lst2]))      temp = filter(lambda x : x not in temp1 or x not in temp2,                                      set(temp1) | set(temp2))    lst3.append(list(temp))         return lst3         # Driver codelst1 = [[5, 9], [8, 2, 6], [3, 4]]lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]print(GCI(lst1, lst2))
[[9, 5], [8], [2, 6], [3, 4], [1]]
 
varshagumber28
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LESS - Fade

It is used to set the transparency of a color for selected elements. It has following parameters −
color − It represents color object.
color − It represents color object.
amount − It contains percentage between 0 - 100%.
amount − It contains percentage between 0 - 100%.
The following example demonstrates the use of fade color operation in the LESS file −
<html>
   <head>
      <title>Fade</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css"/>
   </head>

   <body>
      <h2>Example of Fade Color Operation</h2>
      <div class = "myclass1">
         <p>color :<br>#426105</p>
      </div><br>

      <div class = "myclass2">
         <p>result :<br>rgba(66, 97, 5, 0.1)</p>
      </div>
   </body>
</html>
Next, create the style.less file.
.myclass1 {
   height:100px;
   width:100px;
   padding: 30px 0px 0px 25px;
   background-color: hsl(80, 90%, 20%);
   color:white;
}

.myclass2 {
   height:100px;
   width:100px;
   padding: 30px 0px 0px 25px;
   background-color: fade(hsl(80, 90%, 20%), 10%);
   color:black;
}
You can compile the style.less to style.css by using the following command −
lessc style.less style.css

Execute the above command; it will create the style.css file automatically with the following code −
.myclass1 {
   height: 100px;
   width: 100px;
   padding: 30px 0px 0px 25px;
   background-color: #426105;
   color: white;
}

.myclass2 {
   height: 100px;
   width: 100px;
   padding: 30px 0px 0px 25px;
   background-color: rgba(66, 97, 5, 0.1);
   color: black;
}
Follow these steps to see how the above code works −
Save above code in fade.html file.
Save above code in fade.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Custom ArrayList in Java

A custom ArrayList can have multiple types of data and its attributes in general are based on the user requirements.
A program that demonstrates a custom ArrayList is given as follows −
 Live Demo
import java.util.ArrayList;
public class CustomArrayList {
   int n = 5;
   class Employee {
      int eno;
      String name;
      Employee(int eno, String name) {
         this.eno = eno;
         this.name = name;
      }
   }
   public static void main(String args[]) {
      int eno[] = {101, 102, 103, 104, 105};
      String name[] = {"Jane", "Mary", "Adam", "Harry", "John"};
      CustomArrayList caList = new CustomArrayList();
      caList.add(eno, name);
   }
   public void add(int eno[], String name[]) {
      ArrayList<Employee> aList = new ArrayList<>();
      for (int i = 0; i < n; i++) {
         aList.add(new Employee(eno[i], name[i]));
      }
      print(aList);
   }
   public void print(ArrayList<Employee> aList) {
      for (int i = 0; i < n; i++) {
         Employee e = aList.get(i);
         System.out.println("\nEmployee Number: " + e.eno);
         System.out.println("Employee Name: " + e.name);
      }
   }
}
The output of the above program is as follows −
Employee Number: 101
Employee Name: Jane

Employee Number: 102
Employee Name: Mary

Employee Number: 103
Employee Name: Adam

Employee Number: 104
Employee Name: Harry

Employee Number: 105
Employee Name: John
MongoDB $arrayElemAt Operator

09 Dec, 2021
MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $arrayElemAt operator is one of them. This operator is used to return the element present on the specified index of the given array. 
Syntax: 
{ $arrayElemAt: [ <array>, <index> ] }
Here, the array must be a valid expression until it resolves to an array and index must be a valid expression until it resolves to an integer.
If the value of index is positive, then this operator will return the element at the index position, from the start of the array.
If the value of index is negative, then this operator will return the element at the index position, from the end of the array.
If the index exceeds the array bounds, then this operator does not return any result.
 Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.
Using $arrayElemAt Operator:
In this example, we are going to find the elements of the array(i.e., the value of fruits field) on the specified index using $arrayElemAt operator. 
db.arrayExample.aggregate([
... {$match: {name: "Bongo"}},
... {$project: {
... firstItem: {$arrayElemAt: ["$fruits", 0]},
... lastItem: {$arrayElemAt: ["$fruits", -1]}}}])
Using $arrayElemAt Operator in the Embedded Document:
In this example, we are going to find the elements of the array(i.e., the value of favGame.outdoorGames field) on the specified index using $arrayElemAt operator. 
db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {
... firstItem: {$arrayElemAt: ["$favGame.outdoorGames", 0]},
... item: {$arrayElemAt: ["$favGame.outdoorGames", 2]}}}])
as5853535
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Mongoose | update() Function
PyQt5 QDateTimeEdit – Setting QDateTime to it

10 Jul, 2020
In this article we will see how we can set QDateTime object to the QDateTimeEdit widget. QDateTime is basically a combination of QDate and QTime i.e it has both date and time. And QDateTimeEdit widget is used to show or receive the QDateTime.
In order to do this we will use setDateTime method with the QDateTimeEdit object.
Syntax : datetimeedit.setDateTime(dt)
Argument : It takes QDateTime object as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating a QDateTimeEdit widget        datetimeedit = QDateTimeEdit(self)          # setting geometry        datetimeedit.setGeometry(100, 100, 150, 35)          # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry to the label        label.setGeometry(100, 160, 200, 60)          # making label multi line        label.setWordWrap(True)          # QDateTime        dt = QDateTime(2020, 10, 10, 21, 30)          # setting date time to datetimeedit        datetimeedit.setDateTime(dt)      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateTimeEdit
Python-gui
Python-PyQt
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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Python Program for Find largest prime factor of a number

17 Feb, 2018
Given a positive integer \’n\'( 1 <= n <= 1015). Find the largest prime factor of a number.
Input: 6
Output: 3
Explanation
Prime factor of 6 are- 2, 3
Largest of them is \'3\'

Input: 15
Output: 5

Python3
# Python3 code to find largest prime# factor of numberimport math  # A function to find largest prime factordef maxPrimeFactors (n):          # Initialize the maximum prime factor    # variable with the lowest one    maxPrime = -1          # Print the number of 2s that divide n    while n % 2 == 0:        maxPrime = 2        n >>= 1     # equivalent to n /= 2              # n must be odd at this point,     # thus skip the even numbers and     # iterate only for odd integers    for i in range(3, int(math.sqrt(n)) + 1, 2):        while n % i == 0:            maxPrime = i            n = n / i          # This condition is to handle the     # case when n is a prime number     # greater than 2    if n > 2:        maxPrime = n          return int(maxPrime)  # Driver code to test above functionn = 15print(maxPrimeFactors(n))  n = 25698751364526print(maxPrimeFactors(n))  # This code is contributed by "Sharad_Bhardwaj".
5
328513

Time complexity: Auxiliary space: 
Please refer complete article on Find largest prime factor of a number for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Python Program for Bubble Sort