code-rag-bench/online-tutorials huggingface dataset:
Flatten JavaScript objects into a single-depth Object

13 Sep, 2021
Given a nested JavaScript object, the task is to flatten the object and pull out all the values to a single depth. If the values are already at single depth then it returns the result unaltered.
typeof() method: The typeof() method is used in the script to check the type of JavaScript variable.
Syntax:
typeof(variable)
Parameters: This method accept one parameter as mentioned above and described below:
Variable: The input variable.
Return Value: This method returns a string which contains the type of the passed variable.
Approach:
We make a function called flatten object which takes input of an object and returns an object.Loop through the object and check the type of the current property:If it is of type Object and it is not an Array , recursively call the function again.Otherwise, store the value in the result.Return the object.
We make a function called flatten object which takes input of an object and returns an object.
Loop through the object and check the type of the current property:If it is of type Object and it is not an Array , recursively call the function again.Otherwise, store the value in the result.
If it is of type Object and it is not an Array , recursively call the function again.
Otherwise, store the value in the result.
Return the object.
Example:
Javascript
// Declare an objectlet ob = {    Company: "GeeksforGeeks",    Address: "Noida",    contact: +91-999999999,    mentor: {        HTML: "GFG",        CSS: "GFG",        JavaScript: "GFG"    }}; // Declare a flatten function that takes// object as parameter and returns the// flatten objectconst flattenObj = (ob) => {     // The object which contains the    // final result    let result = {};     // loop through the object "ob"    for (const i in ob) {         // We check the type of the i using        // typeof() function and recursively        // call the function again        if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {            const temp = flattenObj(ob[i]);            for (const j in temp) {                 // Store temp in result                result[i + '.' + j] = temp[j];            }        }         // Else store ob[i] in result directly        else {            result[i] = ob[i];        }    }    return result;}; console.log(flattenObj(ob));
Output:
{
  Company: 'GeeksforGeeks',
  Address: 'Noida',
  contact: -999999908,
  'mentor.HTML': 'GFG',
  'mentor.CSS': 'GFG',
  'mentor.JavaScript': 'GFG'
}
authornjnikhil
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL |ImageDraw.Draw.multiline_text()

09 Sep, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.multiline_text() Draws the string at the given position.
Syntax:ImageDraw.Draw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)
Parameters:
xy – Top left corner of the text.text – Text to be drawn.fill – Color to use for the text.font – An ImageFont instance.spacing – The number of pixels between lines.align – If the text is passed on to multiline_text(), “left”, “center” or “right”.
Return Type:–returns an image with text.
Image Used:
Code : Example of ImageDraw.Draw.multiline_text()
   # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw       # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\ROSE.jpg')   draw = ImageDraw.Draw(image)   # specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 15) spacing = 50text = u"""\ALWAYS BE HAPPY(LAUGHING IS THE \n BEST MEDICINE)"""  # drawing text sizedraw.text((6, 8), text, fill ="red", font = font,           spacing = spacing, align ="right")   image.show() 
Output:
Another Example:Here we changing parameter.
Image Used:
Code : Example of ImageDraw.Draw.multiline_text()
     # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw       # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\flower.jpg')   draw = ImageDraw.Draw(image)   # specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 15) spacing = 50text = u"""\ALWAYS BE HAPPY(LAUGHING IS THE \n BEST MEDICINE)"""  # drawing text sizedraw.text((6, 8), text, fill ="black",           font = font, spacing = spacing, align ="right")   image.show() 
Output:
Image-Processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Example of using Text join in SAP HANA

To implement Text join, create a table −
CREATE COLUMN TABLE TEST.P_INFO (PROD_ID BIGINT, P_CAT NVARCHAR(50));
INSERT INTO TEST.P_INFO VALUES (11,’FURNITURE’);
INSERT INTO TEST.P_INFO VALUES (14,’ELECTRONICS’);
INSERT INTO TEST.P_INFO VALUES (25,’FURNITURE’);
INSERT INTO TEST.P_INFO VALUES (76,’ELECTRONICS’);
2nd table −
CREATE COLUMN TABLE TEST.PROD_DESC (PROD_ID BIGINT,LANGUAGE NVARCHAR(10), DESCR NVARCHAR(100));
INSERT INTO TEST.PROD_DESC VALUES (11,’E’,’Table’);
INSERT INTO TEST.PROD_DESC VALUES (11,’D’,’Chair’);
INSERT INTO TEST.PROD_DESC VALUES (14,’E’,’32 LED’);
INSERT INTO TEST.PROD_DESC VALUES (14,’D’,’32 inch LCD’);
INSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Comp Table’);
INSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Mixer’);
Note that it should have LANGUAGE Column which should have values as single letters like ‘E’ for English and ‘D’ German, etc.
Caesar Cipher in Python

Suppose we have a lowercase alphabet string s, and an offset number say k. We have to replace every letter in s with a letter k positions further along the alphabet. We have to keep in mind that when the letter overflows past a or z, it gets wrapped around the other side.
So, if the input is like "hello", k = 3, then the output will be "khoor"
To solve this, we will follow these steps −
Define a function shift(). This will take c
Define a function shift(). This will take c
i := ASCII of (c) - ASCII of ('a')
i := ASCII of (c) - ASCII of ('a')
i := i + k
i := i + k
i := i mod 26
i := i mod 26
return character from ASCII (ASCII of ('a') + i)
return character from ASCII (ASCII of ('a') + i)
From the main method, do the following −
From the main method, do the following −
ret := for each character c in s, make a list of elements by calling shift(c)
ret := for each character c in s, make a list of elements by calling shift(c)
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s, k):
      def shift(c):
         i = ord(c) - ord('a')
         i += k
         i %= 26
         return chr(ord('a') + i)

      return "".join(map(shift, s))

ob = Solution()
print(ob.solve("hello", 3))
"hello", 3
khoor
Modify the value associated with a given key in Java HashMap

First, create a HashMap and add elements to it −
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Now, to modify the value associated with a given key, use the put() method. Here, we are modifying the value for the key “Frames” −
hm.put("Frames", "900");
The following is an example to modify the value associated with a given key −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      System.out.println(set);
      hm.put("Frames", "900");
      System.out.println("\nUpdated HashMap Elements...");
      System.out.println(hm);
   }
}
Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]

Updated HashMap Elements...
{Frames=900, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000}
Python – tensorflow.math.equal()

28 Jul, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 
equal() is used to perform element by equality comparison.  It performs argument broadcasting before applying the comparison.
Syntax: tensorflow.math.equal( x, y, name)
Parameters:
x: It can be a tensor or sparse tensor or indexed slices.
y: It can be a tensor or sparse tensor or indexed slices.
name(optional): It defines the name for the operation.
Returns: It returns a bool tensor.
Example 1: In this example broadcasting is performed.
Python3
# importing the libraryimport tensorflow as tf  # Initializing the input tensora = tf.constant([6, 8, 12, 2], dtype = tf.float64)b = (2)  # Printing the input tensorprint('a: ', a)print('b: ', b)  # Performing equality comparisonres = tf.math.equal(x = a, y = b)  # Printing the resultprint('Result: ', res)
Output:
a:  tf.Tensor([ 6.  8. 12.  2.], shape=(4, ), dtype=float64)
b:  2
Result:  tf.Tensor([False False False  True], shape=(4, ), dtype=bool)
Example 2:
Python3
# importing the libraryimport tensorflow as tf  # Initializing the input tensora = tf.constant([6, 8, 12, 4], dtype = tf.float64)b = tf.constant([2, 8, 12, 7],  dtype = tf.float64)  # Printing the input tensorprint('a: ', a)print('b: ', b)  # Performing equality comparisonres = tf.math.equal(x = a, y = b)  # Printing the resultprint('Result: ', res)
Output:
a:  tf.Tensor([ 6.  8. 12.  4.], shape=(4, ), dtype=float64)
b:  tf.Tensor([ 2.  8. 12.  7.], shape=(4, ), dtype=float64)
Result:  tf.Tensor([False  True  True False], shape=(4, ), dtype=bool)
Akanksha_Rai
Python Tensorflow-math-functions
Python-Tensorflow
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
GATE | GATE CS 1996 | Question 40

12 Dec, 2018
Quicksort is run on two inputs shown below to sort in ascending order taking first element as pivot,
(i) 1, 2, 3,......., n
(ii) n, n-1, n-2,......, 2, 1 
Let C1 and C2 be the number of comparisons made for the inputs (i) and (ii) respectively. Then,(A) C1 < C2(B) C1 > C2(C) C1 = C2(D) We cannot say anything for arbitrary nAnswer: (C)Explanation: Quick Sort performs in worst case when input is sorted in either ascending order or descending order. So, quick sort will return equal number of comparisons for both given inputs.
Option (C) is correct.Quiz of this Question
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2014-(Set-1) | Question 51
Python | os.path.getmtime() method

10 Oct, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.os.path.getmtime() method in Python is used to get the time of last modification of the specified path. This method returns a floating point value which represents the number of seconds since the epoch. This method raise OSError if the file does not exist or is somehow inaccessible. Note: The epoch represents the point where the time starts. It is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC).  
Syntax: os.path.getmtime(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a floating-point value of class ‘float’ that represents the time (in seconds) of last modification of the specified path.  
Code #1: Use of os.path.getmtime() method 
Python3
# Python program to explain os.path.getmtime() method   # importing os and time moduleimport osimport time # Pathpath = '/home/User/Documents/file.txt' # Get the time of last# modification of the specified# path since the epochmodification_time = os.path.getmtime(path)print("Last modification time since the epoch:", access_time) # convert the time in# seconds since epoch# to local timelocal_time = time.ctime(modification_time)print("Last modification time(Local time):", local_time)
Last modification time since the epoch: 1558447897.0442736
Last modification time (Local time): Tue May 21 19:41:37 2019
 
Code #2: Handling error while using os.path.getmtime() method 
Python3
# Python program to explain os.path.getmtime() method   # importing os, time and sys moduleimport osimport sysimport time # Pathpath = '/home/User/Documents/file2.txt' # Get the time of last# modification of the specified# path since the epochtry:    modification_time = os.path.getmtime(path)    print("Last modification time since the epoch:", modification_time) except OSError:    print("Path '%s' does not exists or is inaccessible" %path)    sys.exit() # convert the time in# seconds since epoch# to local timelocal_time = time.ctime(modification_time)print("Last modification time(Local time):", local_time)  # above code will print# path does not exists or is inaccessible'# if the specified path does not# exists or is inaccessible
Path '/home/User/Documents/file2.txt' does not exists or is inaccessible
 
Reference: https://docs.python.org/3/library/os.path.html
sooda367
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Puzzle 75 | Prisoner’s Hat

08 Feb, 2018
A Police officer caught four criminals. He plays a game with these four men. He lines up three of the prisoners (A, B, C) in one room and the fourth prisoner(D) is placed in a separate room.Each prisoner is given a hat to wear. The officer tells them that there are in total two blue hats and two red hats. If any of them can guess the color of the hat they are wearing right, he promises to set all four of them free. They cannot communicate with each other, the only information is that
The prisoner A can see the colors of hats worn by prisoner B and prisoner C.
Prisoner B can ONLY see the color of hat worn by prisoner C.
After a few minutes of silence, one of the prisoner gets the answer right, who is it?
Solution: Prisoner B gets the answer right.
Explanation: Based on the arrangement made by the officer, the only thing that prisoner B can see is prisoner C wearing a blue hat. Prisoner B has no information about the other two prisoner’s hat colors.Then he calculates,
He can be wearing either a blue hat or a red hat.
If he is wearing a blue hat, prisoner A should be seeing a blue hat on him (prisoner B) and a blue hat on prisoner C and therefore the remaining two are red hats, he must have declared his answer way before without any thinking, but he is silent. This means that he (prisoner B) is not wearing a blue hat. Hence he figures out that he is wearing a red hat.
 This puzzle is contributed by Harika Mulmudi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 21 | (3 Ants and Triangle)
Puzzle 8 | (Find the Jar with contaminated pills)
Puzzle 18 | (Torch and Bridge)
Puzzle 11 | (1000 Coins and 10 Bags)
Puzzle 16 | (100 Doors)
Puzzle 10 | (A Man with Medical Condition and 2 Pills)
Puzzle 13 | (100 Prisoners with Red/Black Hats)
Puzzle 24 | (10 Coins Puzzle)
Combining a one and a two-dimensional NumPy Array

01 Oct, 2020
Sometimes we need to combine 1-D and 2-D arrays and display their elements. Numpy has a function named as numpy.nditer(), which provides this facility.
Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order=’K’, casting=’safe’, op_axes=None, itershape=None, buffersize=0)
Example 1:
Python3
# importing Numpy package import numpy as np  num_1d = np.arange(5)print("One dimensional array:")print(num_1d)  num_2d = np.arange(10).reshape(2,5)print("\nTwo dimensional array:")print(num_2d)  # Combine 1-D and 2-D arrays and display # their elements using numpy.nditer() for a, b in np.nditer([num_1d, num_2d]):    print("%d:%d" % (a, b),)
Output:
One dimensional array:
[0 1 2 3 4]

Two dimensional array:
[[0 1 2 3 4]
 [5 6 7 8 9]]
0:0
1:1
2:2
3:3
4:4
0:5
1:6
2:7
3:8
4:9

Example 2:
Python3
# importing Numpy package import numpy as np  num_1d = np.arange(7)print("One dimensional array:")print(num_1d)  num_2d = np.arange(21).reshape(3,7)print("\nTwo dimensional array:")print(num_2d)  # Combine 1-D and 2-D arrays and display # their elements using numpy.nditer() for a, b in np.nditer([num_1d, num_2d]):    print("%d:%d" % (a, b),)
Output:
One dimensional array:
[0 1 2 3 4 5 6]

Two dimensional array:
[[ 0  1  2  3  4  5  6]
[ 7  8  9 10 11 12 13]
[14 15 16 17 18 19 20]]
0:0
1:1
2:2
3:3
4:4
5:5
6:6
0:7
1:8
2:9
3:10
4:11
5:12
6:13
0:14
1:15
2:16
3:17
4:18
5:19
6:20

Example 3:
Python3
# importing Numpy package import numpy as np  num_1d = np.arange(2)print("One dimensional array:")print(num_1d)  num_2d = np.arange(12).reshape(6,2)print("\nTwo dimensional array:")print(num_2d)  # Combine 1-D and 2-D arrays and display# their elements using numpy.nditer() for a, b in np.nditer([num_1d, num_2d]):    print("%d:%d" % (a, b),)
Output:
One dimensional array:
[0 1]

Two dimensional array:
[[ 0  1]
[ 2  3]
[ 4  5]
[ 6  7]
[ 8  9]
[10 11]]
0:0
1:1
0:2
1:3
0:4
1:5
0:6
1:7
0:8
1:9
0:10
1:11

Python numpy-arrayManipulation
Python-numpy
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
How to crop an image using canvas ?

21 Jun, 2020
The HTML canvas element allows the user to draw graphics on any web page. It is like a container for graphics to draw the graphics, JavaScript is used in the code.
<canvas id="Canvas1" width="100" height="100"></canvas>
Following are the attributes to create a canvas. More optional attributes can also be added. The canvas is referred in JavaScript by its id.
drawImage() method: This method can be used to draw an image or video on the web page. It can also be used to draw parts of an image. Another useful function is to increase or decrease the size of the image.
Cropping an image using drawImage() method: In order to crop a source image to its destination image. the following parameters of drawImage() need to be specified.
image: The image to be cropped.
sourceX: The x-coordinate of the source image
sourceY: The y-coordinate of the source image.
sourceW: The width of the source image.
sourceH: The height of the source image.
destinationX: The x-coordinate of the destination image.
destinationY: The y-coordinate of the destination image.
destinationW: The width of the destination image.
destinationH: The height of the destination image.
Syntax:
drawImage(image, sourceX, sourceY, sourceW, sourceH, 
    destinationX,destinationY, destinationW, destinationH)

Example:
javascript
<!DOCTYPE html><html>  <head>    <title>        How to crop image        using canvas?    </title></head>  <body>      <h2>Source Image</h2>    <img id="myImage" src="https://media.geeksforgeeks.org/wp-content/uploads/20200615165012/double_quotes.jpg"        alt="GeeksForGeeks">      <h2>Cropped Image</h2>      <canvas id="myCanvas" width="500" height="200"         style="border:3px solid">        HTML5 canvas tag is not         supported by your browser.    </canvas>      <script>        window.onload = function () {            var canvas = document.getElementById("myCanvas");            var contex = canvas.getContext("2d");            var img = document.getElementById("myImage");                          contex.drawImage(img, 10, 10,                 300, 175, 0, 0, 100, 175);        }    </script></body>  </html>
HTML-Canvas
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sys.stdout.write in Python

01 Oct, 2020
This is a built-in Python module that contains parameters specific to the system i.e. it contains variables and methods that interact with the interpreter and are also governed by it. 
A built-in file object that is analogous to the interpreter’s standard output stream in Python. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input. By default, streams are in text mode. In fact, wherever a print function is called within the code, it is first written to sys.stdout and then finally on to the screen. 
sys.stdout.write() serves the same purpose as the object stands for except it prints the number of letters within the text too when used in interactive mode. Unlike print, sys.stdout.write doesn’t switch to a new line after one text is displayed. To achieve this one can employ a new line escape character(\n).
Syntax:
sys.stdout.write(<some string text here>)

Example 1:
Python3
import sys    sys.stdout.write('gfg')
gfg
Example 2:
Python3
# script modeimport sys    sys.stdout.write('gfg')sys.stdout.write('geeks')sys.stdout.write('\n')sys.stdout.write('for geeks')
gfggeeks
for geeks
stdout can be also be used to print multiple elements. Not just this stdout can be assigned to another variable as long as it supports write().
Example 3:
Python3
import sys  # stdout assigned to a variablevar = sys.stdoutarr = ['geeks', 'for', 'geeks']  # printing everything in the same linefor i in arr:    var.write(i)  # printing everything in a new linefor j in arr:    var.write('\n'+j)
Output:
geeksforgeeks
geeks
for
geeks

Python-sys
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set creation and modification date/time of a file using Python?

To get the creation time of a file, you can use the os.path.getctime(file_path) on windows. On UNIX systems, you cant use the same function as it returns the last time that the file's attributes or content were changed. To get the creation time on UNIX based systems, use the st_birthtime attribute of the stat tuple.
On Windows:
>>> import os
>>> print os.path.getctime('my_file')
1505928271.0689342
It gives the time in the number of seconds since the epoch. For UNIX systems,
import os
stat = os.stat(path_to_file)
try:
    print(stat.st_birthtime)
except AttributeError:
    # Probably on Linux. No easy way to get creation dates here,
    # so we'll settle for when its content was last modified.
    print(stat.st_mtime)
This will give the output:
1505928271.0689342
For getting the modification time for a file, you can use the os.path.getmtime(path). It is supported cross-platform.
>>> import os
>>> print os.path.getmtime('my_file')
1505928275.3081832
TreeMap size() Method in Java with Examples

29 Nov, 2021
size() method of TreeMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.
--> java.util package
    --> TreeMap class
        --> size() Method   
Syntax: 
Tree_Map.size()
Return Value: The size of the map which also means the number of key-value pairs present in the map. 
Example 1: Mapping String Values to Integer Keys
Java
// Java Program to Illustrate size() Method// of TreeMap class // Importing required classesimport java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty TreeMap by        // declaring object of Integer, string pairs        TreeMap<Integer, String> tree_map            = new TreeMap<Integer, String>();         // Mapping string values to int keys        // using put() method        tree_map.put(10, "Geeks");        tree_map.put(15, "4");        tree_map.put(20, "Geeks");        tree_map.put(25, "Welcomes");        tree_map.put(30, "You");         // Displaying the elements of TreeMap        System.out.println("Initial Mappings are: "                           + tree_map);         // Now displaying the size of this map        // using size() method        System.out.println("The size of the map is "                           + tree_map.size());    }}
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The size of the map is 5
 
Example 2: Mapping Integer Values to String Keys
Java
// Java Program to Illustrate the size() method// of TreeMap class // Importing required classesimport java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty TreeMap by        // declaring object of string, integer pairs        TreeMap<String, Integer> tree_map            = new TreeMap<String, Integer>();         // Mapping int values to string keys        // using put() method        tree_map.put("Geeks", 10);        tree_map.put("4", 15);        tree_map.put("Geeks", 20);        tree_map.put("Welcomes", 25);        tree_map.put("You", 30);         // Printing the elements of TreeMap        System.out.println("Initial Mappings are: "                           + tree_map);         // Printing the size of the map        // using size() method        System.out.println("The size of the map is "                           + tree_map.size());    }}
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
The size of the map is 4
 
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
solankimayank
varshagumber28
Java - util package
Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
Scala List map() method with example

13 Aug, 2019
The map() method is utilized to apply the stated function to all the elements of the list.
Method Definition: def map[B](f: (A) => B): List[B]
Return Type: It returns a new list after applying the stated function to all the elements of the list.
Example #1:
// Scala program of map()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(2, 3, 5, 7, 8)                  // Applying map method        val result = m1.map(x => x*3)                  // Displays output        println(result)          }} 
List(6, 9, 15, 21, 24)

Example #2:
// Scala program of map()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(2, 3, 5, 7, 8)                  // Applying map method        val result = m1.map(x => x*x)                  // Displays output        println(result)          }} 
List(4, 9, 25, 49, 64)

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
How to Install Scala with VSCode?
Inheritance in Scala
Set clear() method in Java with Examples

31 Dec, 2018
The Java.util.Set.clear() method is used to remove all the elements from a Set. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing Set.
Syntax:
void clear()
Parameters: The method does not take any parameter
Return Value: The method does not returns any value.
Below program illustrate the Java.util.method.clear() method:
// Java code to illustrate clear()import java.io.*;import java.util.*;  public class SetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<String> st = new HashSet<String>();          // Use add() method to add elements into the Set        st.add("Welcome");        st.add("To");        st.add("Geeks");        st.add("4");        st.add("Geeks");          // Displaying the Set        System.out.println("Initial Set: " + st);          // Clearing the Set using clear() method        st.clear();          // Displaying the final Set after clearing;        System.out.println("The final set: " + st);    }}
Initial Set: [4, Geeks, Welcome, To]
The final set: []

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#clear()
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas DatetimeIndex.date

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.date attribute outputs an Index object containing the date values present in each of the entries of the DatetimeIndex object.
Syntax: DatetimeIndex.date
Return: numpy array of python datetime.date
Example #1: Use DatetimeIndex.date attribute to find the date part of the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'W' represents Weekly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='W',                             periods = 3, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find all the date values present in the DatetimeIndex object.
# find all the date values present in the objectdidx.date
Output :As we can see in the output, the function has returned an Index object containing the date values present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.date attribute to find the date part of the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'D' represents Daily frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='D',                               periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find all the date values present in the DatetimeIndex object.
# find all the date values present in the objectdidx.date
Output :As we can see in the output, the function has returned an Index object containing the date values present in each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
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
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
DAX Statistical - STDEV.S function

Returns the standard deviation of a sample population.
STDEV.S (<ColumnName>)

ColumnName
The name of a column, usually fully qualified.
It cannot be an expression.
A real number.
DAX STDEV.S function assumes that the column refers to a sample of the population. If your data represents the entire population, then use DAX STDEV.P function.
STDEV.S uses the following formula −
$$\sqrt{\sum\frac{(x\:-\:\bar{x})^{2}}{(n-1)}}$$
Where, $\bar{x}$  the average value of $x$ for the entire population, and
n is the sample size
Blank rows are filtered out from columnName and not considered in the calculation.
An error is returned if columnName contains less than 2 non-blank rows.
= STDEV.S (West_Sales[Amount]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How we can use Python Tuple within a Tuple?

Tuple is defined as an ordered collection of any Python objects enclosed in parentheses. Hence, a tuple can very well be one of the items in the collection.
>>> t1=(1,(4, 5, 6),2,3)
>>> t1
(1, (4, 5, 6), 2, 3)
In this example, item at index number 1 in t1 is a tuple itself. Hence it can be retrieved using the index as −
>>> t1[1]
(4, 5, 6)
Further items of enclosed tuples can also be retrieved using their internal index
>>> t1[1][1]
5
JavaScript function that generates all possible combinations of a string

We are required to write a JavaScript function that takes in a string as the only argument. The function should generate an array of strings that contains all possible contiguous substrings that exist in the array.
Following is the code −
const str = 'Delhi';
const allCombinations = (str1 = '') => {
   const arr = [];
   for (let x = 0, y=1; x < str1.length; x++,y++) {
      arr[x]=str1.substring(x, y);
   };
   const combination = [];
   let temp= "";
   let len = Math.pow(2, arr.length);
   for (let i = 0; i < len ; i++){
      temp= "";
      for (let j=0;j<arr.length;j++) {
         if ((i & Math.pow(2,j))){
            temp += arr[j];
         }
      };
      if (temp !== ""){
         combination.push(temp);
      }
   }
   return combination;
};
console.log(allCombinations(str));
Following is the output on console −
[
   'D', 'e', 'De', 'l',
   'Dl', 'el', 'Del', 'h',
   'Dh', 'eh', 'Deh', 'lh',
   'Dlh', 'elh', 'Delh', 'i',
   'Di', 'ei', 'Dei', 'li',
   'Dli', 'eli', 'Deli', 'hi',
   'Dhi', 'ehi', 'Dehi', 'lhi',
   'Dlhi', 'elhi', 'Delhi'
]
CSS rgba() Function

The rgba() defines the RGBA color value for Red, Green, Blue and Alpha. The alpha is the color opacity i.e. a number between 0.0 and 1.0. Here, 1.0 would be for full opaque.
Let us now see an example to implement the rgba() function −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#demo1 {background-color: hsla(140, 100%, 50%, 0.8);}
#demo2 {background-color: hsla(130, 100%, 50%, 0.6);}
#demo3 {background-color: hsla(190, 100%, 50%, 0.4);}
#demo4 {background-color: hsla(170, 100%, 50%, 0.3);}
#demo5 {background-color: hsl(150, 100%, 60%);}
#demo6 {
   background-color:rgba(108,111,35,0.6);
   font-size:30px;
   color:yellow;
   transform: rotate(45deg);
}
</style>
</head>
<body>
<h1>Cricketers</h1>
<p id="demo1">David Warner</p>
<p id="demo2">Steve Smith</p>
<p id="demo3">Mark Waugh</p>
<p id="demo4">Steve Waugh</p>
<p id="demo5">David Johnson</p>
<p id="demo6">Australian Cricketers</p>
</body>
</html>
Let us see another example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
span {
   background-color: rgba(100, 150, 50, 0.6);
   text-decoration: line-through;
   text-decoration-color: blue;
}
.demo2 {
   text-decoration: underline;
   text-decoration-color: yellow;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near <span>XYZ College</span> ABC College.</p>
<p class="demo2">Exam begins at 11AM.</p>
</body>
</html>
Program to multiply two matrices in C++

In this tutorial, we will be discussing a program to multiply two matrices.
For this we will be given with two matrices and our task is to print the product of two those matrices. The only condition is that the number of columns of first matrix should be equal to the number of rows of the second matrix.
 Live Demo
#include <iostream>
using namespace std;
#define N 4
//multiplying the elements of both matrices
void calc_product(int mat1[][N], int mat2[][N], int res[][N]){
   int i, j, k;
   for (i = 0; i < N; i++) {
      for (j = 0; j < N; j++){
         res[i][j] = 0;
         for (k = 0; k < N; k++)
            res[i][j] += mat1[i][k] * mat2[k][j];
      }
   }
}
int main(){
   int i, j;
   int res[N][N];
   int mat1[N][N] = {{1, 1, 1, 1},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {4, 4, 4, 4}};
   int mat2[N][N] = {{1, 1, 1, 1},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {4, 4, 4, 4}};
   calc_product(mat1, mat2, res);
   cout << "Resultant matrix :\n";
   for (i = 0; i < N; i++){
      for (j = 0; j < N; j++)
      cout << res[i][j] << " ";
      cout << "\n";
   }
   return 0;
}
Resultant matrix :
10 10 10 10
20 20 20 20
30 30 30 30
40 40 40 40
static keyword in C++ vs Java

In C++ or Java we can get the static keyword. They are mostly same, but there are some basic differences between these two languages. Let us see the differences between static in C++ and static in Java.
The static data members are basically same in Java and C++. The static data members are the property of the class, and it is shared to all of the objects.
public class Test {
   static int ob_count = 0;
   Test() {
      ob_count++;
   }
   public static void main(String[] args) {
      Test object1 = new Test();
      Test object2 = new Test();
      System.out.println("The number of created objects: " + ob_count);
   }
}
The number of created objects: 2
#include<iostream>
using namespace std;
class Test {
   public:
      static int ob_count;
      Test() {
         ob_count++;
      }
};
int Test::ob_count = 0;
int main() {
   Test object1, object2;
   cout << "The number of created objects: " << Test::ob_count;
}
The number of created objects: 2
The static member functions - In C++ and Java, we can create static member functions. These are also member of that class. There are some restrictions also.
The static methods can only call some other static methods.
They can only access the static member variables
They cannot access the ‘this’ or ‘super’ (for Java only)
In C++ and Java, the static members can be accessed without creating some objects
//This is present in the different file named MyClass.java
public class MyClass {
   static int x = 10;
   public static void myFunction() {
      System.out.println("The static data from static member: " + x);
   }
}
//This is present the different file named Test.Java
public class Test {
   public static void main(String[] args) {
      MyClass.myFunction();
   }
}
The static data from static member: 10
#include<iostream>
using namespace std;
class MyClass {
   public:
      static int x;
      static void myFunction(){
         cout << "The static data from static member: " << x;
      }
};
int MyClass::x = 10;
int main() {
   MyClass::myFunction();
}
The static data from static member: 10
The static block: In Java we can find the static block. This is also known as static clause. These are used for static initialization of a class. The code, which is written inside the static block, will be executed only once. This is not present in C++
In C++ we can declare static local variables, but in Java the static local variables are not supported.
How to set the height and width of background image inline style in react?

16 Oct, 2020
In React, one can create an object with styling information like background image, height, width, etc and refer to the object in the style attribute in the HTML element. Since the inline CSS is written in a JavaScript object, properties with two names, like background-color, must be written with camel case syntax.
Syntax :
class MyHeader extends React.Component {
  render() {
    const mystyle = {
      backgroundColor: "white",
     // CSS CODE
     };
    return (
      <div>
      <h1 style={mystyle}>Hello Style!</h1>
      // All styling define in mystyle 
      // object will applied to h1 element.
      </div>
    );
  }
}


Example 1: Set width and height of background image in div element to 100% and 200px .
Javascript
import React from 'react';import './App.css';  function App() {  const myStyle={    backgroundImage:"url(" +"https://i.pinimg.com/474x/62/69/be/6269be179ab7d610b2a4959387fd77af.jpg"+")",    width:'100%',    height:'200px',    };  return (    <div style={myStyle}>     <h1 style={{color:'green'}}>        Geeks For Geeks      </h1>     <p style={{color:'white'}}>        Set height and width of background       image inline style react.      </p>      </div>  );}export default App;
Output: Here, all style define in myStyle object is applicable to the div element. One can check the width and height of the background image in the div element is 100% and 200px. 
Example 2: Set width and height of background image in div element to 20% and 200px .
Javascript
import React from 'react';import './App.css';  function App() {  const myStyle={    backgroundImage:"url(" +    "https://i.pinimg.com/474x/62/69/be/6269be179ab7d610b2a4959387fd77af.jpg"+")",    width:'20%',    height:'200px',    };  return (    <div style={myStyle}>     <h1 style={{color:'green'}}>        Geeks For Geeks      </h1>     <p style={{color:'white'}}>        Set height and width of background image       inline style react.     </p>      </div>  );}export default App;
Output: Here, all style define in myStyle object is applicable to the div element. One can check the width and height of the background image in the div element is 20% and 200px. 
Note: Similarly, one can define many other CSS styles in an object and call the object in the style attribute of the respective HTML element. All the CSS styles defined in the object will be applied to that particular HTML element as shown in the above example.
Picked
react-js
React-misc
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
REST API (Introduction)
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
ReactJS | Router
Axios in React: A Guide for Beginners
strcspn() function in C/C++

17 Jan, 2022
The strcspn() function in C/C++ takes two string as input, string_1 and string_2 as it’s argument and searches string_1 by traversing for any characters that is present in string_2 . The function will return the length of string_1 if none of the characters of string_2 are found in string_1 . This function is defined in cstring header file .Syntax :  
size_t strcspn ( const char *string_1, const char *string_2 ) 
Parameters : The function accepts two mandatory parameters which are described below:  
string_1: specifies the string to be searched
string_2: specifies the string containing the characters to be matched
Return Value : This function returns the number of character traversed in string_1 before any of the character matched from string_2 .Below programs illustrate the above function: Program 1:  
CPP
// C++ program to illustrate the// strcspn() function#include <bits/stdc++.h>using namespace std; int main(){    // String to be traversed    char string_1[] = "geekforgeeks456";     // Search these characters in string_1    char string_2[] = "123456789";     // function strcspn() traverse the string_1    // and search the characters of string_2    size_t match = strcspn(string_1, string_2);     // if matched return the position number    if (match < strlen(string_1))        cout << "The number of characters before"             << "the matched character are " << match;     else        cout << string_1 <<        " didn't matched any character from string_2 ";    return 0;}
The number of characters beforethe matched character are 12
 
Program 2:  
CPP
// C++ program to illustrate the// strcspn() function When the string// containing the character to be// matched is empty#include <bits/stdc++.h>using namespace std; int main(){    // String to be traversed    char string_1[] = "geekforgeeks456";     // Search these characters in string_1    char string_2[] = ""; // Empty     // function strcspn() traverse the string_1    // and search the characters of string_2    size_t match = strcspn(string_1, string_2);     // if matched return the position number    if (match < strlen(string_1))        cout << "The number of character before"             << "the matched character are " << match;    else        cout << string_1 <<        " didn't matched any character from string_2  ";    return 0;}
geekforgeeks456 didn't matched any character from string_2
 
sweetyty
C-Library
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to sort out words of the sentence in ascending order

In order to sort the words of a sentence in ascending order, we first need to split the sentence into words using space as the splitting point. For simplicity, we'll only be splitting on space and let the punctuation be there. We can use replace or regex to remove that as well.
Once we split the sentence, we can sort the words lexicographically(like in a language dictionary) using either sort or sorted methods depending on whether we want to sort the array in place or sort it, then return a new array.
In place sorting: when we want to sort the array/list in place, ie, changing the order in the current structure itself, we can use the sort method directly. For example,
sent = "mary has a very beautiful dog"
my_arr = sent.split(" ")
print(my_arr)
my_arr.sort()
print(my_arr)
This will give the output −
['mary', 'has', 'a', 'very', 'beautiful', 'dog']
['a', 'beautiful', 'dog', 'has', 'mary', 'very']
As you can see here, the original array, my_arr has been modified. If you want to keep this array as it is and created a new array when sorting, you can use the sorted method. For example,
 Live Demo
sent = "mary has a very beautiful dog"
# Split on space.
my_arr = sent.split(" ")
print(my_arr)

# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)

# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)
This will give the output −
['mary', 'has', 'a', 'very', 'beautiful', 'dog']
['a', 'beautiful', 'dog', 'has', 'mary', 'very']
['mary', 'has', 'a', 'very', 'beautiful', 'dog']
As you can see here, the original array did not change.