code-rag-bench/online-tutorials huggingface dataset:
PARALLELPERIOD function

Returns a table that contains a column of dates that represents a period parallel to the dates in the specified dates column, in the current context, with the dates shifted a number of intervals either forward in time or back in time.
PARALLELPERIOD (<dates>, <number_of_intervals>, <interval>) 

dates
A column that contains dates.
number_of_intervals
An integer that specifies the number of intervals to add to or subtract from the dates.
interval
The interval by which to shift the dates.
The value for interval can be one of the following −
Year
Quarter
Month
Day
A table containing a single column of date values.
DAX PARALLELPERIOD function takes the current set of dates in the column specified by dates, shifts the first date and the last date the specified number of intervals, and then returns all contiguous dates between the two shifted dates.
If the interval is a partial range of month, quarter, or year, then any partial months in the result are also filled out to complete the entire interval.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time.
The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them.
The result table includes only dates that are specified in the dates parameter.
If the dates in the current context do not form a contiguous interval, the function returns an error.
Previous Year Sales:= CALCULATE ( 
   SUM (Sales[Sales Amount]), 
   PARALLELPERIOD (Sales[Date], -1,YEAR)
) 

    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
Java Program to Reverse a String using Stack - GeeksforGeeks

21 Oct, 2020
The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first.
Approach:
Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character array.Convert character array to string.Return reversed string.
Push the character one by one into the Stack of datatype character.
Pop the character one by one from the Stack until the stack becomes empty.
Add a popped element to the character array.
Convert character array to string.
Return reversed string.
Below is the implementation of the above approach.
Java
// Java Program to Reverse a String using Stack  import java.io.*;import java.util.*;  class GFG {      public static String ReverseString(String str)    {        char[] reverseString = new char[str.length()];        // Declare a stack of type Character        Stack<Character> stack = new Stack<Character>();          // Traverse the String and push the character one by        // one into the Stack        for (int i = 0; i < str.length(); i++) {            // push the character into the Stack            stack.push(str.charAt(i));        }          // Now Pop the Characters from the stack until it        // becomes empty          int i = 0;        while (!stack.isEmpty()) { // popping element until                                   // stack become empty            // get the character from the top of the stack            reverseString[i++] = stack.pop();        }        // return string object        return new String(reverseString);    }      // Driver code    public static void main(String[] args)    {        String str1 = "GeeksForGeeks";                // call the function        System.out.println(str1 + " <- Reverse -> "                           + ReverseString(str1));                String str2 = "Hello World";                // call the function        System.out.println(str2 + " <- Reverse -> "                           + ReverseString(str2));    }}
GeeksForGeeks <- Reverse -> skeeGroFskeeG
Hello World <- Reverse -> dlroW olleH

Time Complexity: O(n), where n is a number of characters in the stack.
Auxiliary Space: O(n) for the stack.
Java-String-Programs
Java
Java Programs
Stack
Stack
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
C# | Math.Cos() Method - GeeksforGeeks

11 Jan, 2022
Math.Cos() is an inbuilt Math class method which returns the cosine of a given double value argument(specified angle).Syntax:  
public static double Cos(double num)
Parameter:  
num: It is the angle(measured in radian) whose cosine is to be returned and the type of this parameter is System.Double.
Return Value: Returns the cosine of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN.Below are the programs to illustrate the Math.Cos() method.Program 1: To show the working of Math.Cos() method.
CSharp
// C# program to demonstrate working// Math.Cos() methodusing System;  class Geeks {      // Main Method    public static void Main(String []args)    {        double a = 70;                  // converting value to radians        double b = (a * (Math.PI)) / 180;          // using method and displaying result        Console.WriteLine(Math.Cos(b));        a = 50;                  // converting value to radians        b = (a * (Math.PI)) / 180;          // using method and displaying result        Console.WriteLine(Math.Cos(b));        a = 73;                  // converting value to radians        b = (a * (Math.PI)) / 180;         // using method and displaying result        Console.WriteLine(Math.Cos(b));        a = 77;                  // converting value to radians        b = (a * (Math.PI)) / 180;          // using method and displaying result        Console.WriteLine(Math.Cos(b));    }}
0.342020143325669
0.642787609686539
0.292371704722737
0.224951054343865
 
 Program 2: To show the working of Math.Cos() method when the argument is NaN or infinity.
CSharp
// C# program to demonstrate working// Math.Cos() method in infinity caseusing System; class Geeks {         // Main Method    public static void Main(String []args)    {         double positiveInfinity = Double.PositiveInfinity;            double negativeInfinity = Double.NegativeInfinity;                                        double nan = Double.NaN;        double result;         // Here argument is negative infinity,        // output will be NaN         result = Math.Cos(negativeInfinity);         Console.WriteLine(result);         // Here argument is positive infinity,        // output will also be NaN        result = Math.Cos(positiveInfinity);        Console.WriteLine(result);         // Here argument is NaN, output will be NaN        result = Math.Cos(nan);        Console.WriteLine(result);    }}
NaN
NaN
NaN
 
adnanirshad158
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Python | sympy.Lambda() method - GeeksforGeeks

17 Jul, 2019
With the help of sympy.Lambda() method, we can perform any mathematical operation by just defining the formula and then pass the parameters with reference variable by using sympy.Lambda().
Syntax : sympy.Lambda()Return : Return the result of mathematical formula.
Example #1 :In this example we can see that we are able to perform any mathematical operation by using sympy.Lambda() method.
# import sympyfrom sympy import *  # Use sympy.Lambda() methodx = symbols('x')gfg = Lambda(x, x + 1)  print(gfg(9))
Output :
10
Example #2 :
# import sympyfrom sympy import *  # Use sympy.Lambda() methodx, y = symbols('x y')gfg = Lambda((x, y), x * y)  print(gfg(9, 5))
Output :
45
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Include all existing fields and add new fields to document in MongoDB?

You can achieve this with the help of $addFields operator. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.addFieldDemo.insertOne({"EmployeeId":101,"EmployeeName":"Larry","EmployeeDetails":{
   "EmployeeSalary":65000,"EmployeeCity":"New York","Message":"Hi"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f654d8d10a061296a3c44")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.addFieldDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c7f654d8d10a061296a3c44"),
   "EmployeeId" : 101,
   "EmployeeName" : "Larry",
   "EmployeeDetails" : {
      "EmployeeSalary" : 65000,
      "EmployeeCity" : "New York",
      "Message" : "Hi"
   }
}
Here is the query to include all existing fields and add new fields to document in MongoDB −
> db.addFieldDemo.aggregate([ { "$addFields": { "EmployeeBasicSalary":"$EmployeeDetails.EmployeeSalary" } } ]).pretty();
The following is the output −
{
   "_id" : ObjectId("5c7f654d8d10a061296a3c44"),
   "EmployeeId" : 101,
   "EmployeeName" : "Larry",
   "EmployeeDetails" : {
      "EmployeeSalary" : 65000,
      "EmployeeCity" : "New York",
      "Message" : "Hi"
   },
   "EmployeeBasicSalary" : 65000
}
Look at the sample output, “EmployeeBasicSalary” has been added.
p5.js mouseReleased() Function - GeeksforGeeks

04 Mar, 2021
The mouseReleased() function in p5.js works when mouse button released. The touchEnded() function is used instead of mouseReleased() function when mouseReleased() function is not defined.
Syntax:
mouseReleased(Event)
Below programs illustrate the mouseReleased() function in p5.js:
Example 1: This example uses mouseReleased() function to change the background color.
function setup() {          // Create Canvas    createCanvas(500, 500);}   let value = 0;  function draw() {          // Set the background color    background(200);          // Fill the color    fill(value, value-50, value-100);          // Create rectangle    rect(25, 25, 460, 440);          // Set the filled color    fill('lightgreen');          // Set the font size    textSize(15);          // Display result    text('Keep on Clicking the Mouse Across'        + ' the page \nto change Canvas Color.',        windowHeight/10, windowWidth/4);}  function mouseReleased() {    value = value + 5;          if (value > 255) {        value = 0;    }}
Output:
Example 2: This example uses mouseReleased() function to change the mouse pointer color.
let valueX;let valueY;  function setup() {          // Create Canvas    createCanvas(500, 500);}   function draw() {          // Set background color    background(200);           // Fill the color    fill('green');          // Set font size    textSize(25);          text('Drag mouse to change color', 30, 30);          // Fill color according to mouseMoved()     fill(valueX, 255-valueY, 255-valueX);          // Draw ellipse      ellipse(mouseX, mouseY, 115, 115);}  function mouseReleased() {    valueX = mouseX%255;    valueY = mouseY%255;}
Output:
Reference: https://p5js.org/reference/#/p5/mouseReleased
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Replace Character in a String in Java without using replace() method

To replace a character in a String, without using the replace() method, try the below logic.
Let’s say the following is our string.
String str = "The Haunting of Hill House!";
To replace character at a position with another character, use the substring() method login. Here, we are replacing 7th position with character ‘p’
int pos = 7;
char rep = 'p';
String res = str.substring(0, pos) + rep + str.substring(pos + 1);
The following is the complete example wherein a character at position 7 is replaced.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       String str = "The Haunting of Hill House!";
       System.out.println("String: "+str);
       // replacing character at position 7
       int pos = 7;
       char rep = 'p';
       String res = str.substring(0, pos) + rep + str.substring(pos + 1);
       System.out.println("String after replacing a character: "+res);
    }
}
String: The Haunting of Hill House!
String after replacing a character: The Haupting of Hill House!
Dart - Boolean - GeeksforGeeks

28 Feb, 2021
Dart language provides a pre-defined data type called boolean which can store two possible values, either true or false. To declare a boolean variable in Dart programming language, the keyword bool is used. Most commonly, boolean is used in decision-making statements.
The syntax for declaring a boolean value is as follows:
Syntax: bool variable_name = true/false;
Example 1:
The following example shows how we can assign boolean values in case of comparison of 2 predefined values.
Dart
main() {    bool check;     int val1=12;   int val2=9;       // Assigning variable check   // value depending on condition   check=(val1>val2);   print(check);}
Output:
Example 2:
The following example shows how we can use boolean values to check which of the two arguments passed is greater.
Dart
main(List<String> arguments) {        // Taking values of arguments   // inside variables val1 and val2   int val1=int.parse(arguments[0]);   int val2=int.parse(arguments[1]);   bool check;         // Assigning variable check   // value depending on condition   check=(val1>val2);    if(check){       print('First argument is greater');   }else{        print('Second argument is greater or both are equal');   }   }
Suppose we run this dart program named main.dart using : 
dart main.dart 12 9
Output:
In the above example, as the value inside the first argument (12) is greater than the value of the second argument (9), the value inside the boolean variable check becomes true. Now, as if the condition is true the first statement is printed. 
Example 3:
The following example shows how we can use boolean values to check which of the passed 2 strings is greater.
Dart
main(List<String> arguments) {    //Taking values of lengths inside variables len1 and len2   int len1=arguments[0].length;   int len2=arguments[1].length;   bool check;     //Assigning variable check value depending on condition   check=(len1>len2);    if(check){       print('First length is greater and its length is $len1');   }else{        print('Second length is greater or equal and its value is $len2');   }   }
Suppose we run this dart program named main.dart using :
dart main.dart GeeksforGeeks Dart
Output:
In the above example, as the length of the first string (13) is greater than the length of the second string (4), the value inside the boolean variable check becomes true. Now, as if the condition is true the first statement is printed. 
Dart Data-types
Picked
Technical Scripter 2020
Dart
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Stack Widget
What is widgets in Flutter?
Android Studio Setup for Flutter Development
Flutter - Flexible Widget
Flutter - BorderRadius Widget
Simple Calculator App using Flutter
Format Dates in Flutter
Flutter - Positioned Widget
Counting number of lines in text file using java


We can read lines in a file using BufferedReader class of Java. See the example below −
Consider the following text file in the classpath.
test.txt
This is Line 1
This is Line 2
This is Line 3
This is Line 4
This is Line 5
This is Line 6
This is Line 7
This is Line 8
This is Line 9
This is Line 10
Tester.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Tester {

   private static final String FILE_PATH = "data.txt";
   public static void main(String args[]) throws IOException {
      FileUtil fileUtil = new FileUtil(FILE_PATH);
      System.out.println("No. of lines in file: " + fileUtil.getLineCount());
   }
}

class FileUtil {
   static BufferedReader reader = null;    
   public FileUtil(String filePath) throws FileNotFoundException {
      File file = new File(filePath);
      FileInputStream fileStream = new FileInputStream(file);
      InputStreamReader input = new InputStreamReader(fileStream);
      reader = new BufferedReader(input);
   }

   public static int getLineCount() throws IOException {
      int lineCount = 0;
      String data;        
      while((data = reader.readLine()) != null) {
         lineCount++;                  
      }            
      return lineCount;
   }
}
This will produce the following result −
No. of lines in file: 10
Python - Tkinter grid() Method

This geometry manager organizes widgets in a table-like structure in the parent widget.
widget.grid( grid_options )

Here is the list of possible options −
column − The column to put widget in; default 0 (leftmost column).
column − The column to put widget in; default 0 (leftmost column).
columnspan − How many columns widgetoccupies; default 1.
columnspan − How many columns widgetoccupies; default 1.
ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders.
ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders.
padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders.
padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders.
row − The row to put widget in; default the first row that is still empty.
row − The row to put widget in; default the first row that is still empty.
rowspan − How many rowswidget occupies; default 1.
rowspan − How many rowswidget occupies; default 1.
sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks.
sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks.
Try the following example by moving cursor on different buttons −
import Tkinter
root = Tkinter.Tk(  )
for r in range(3):
   for c in range(4):
      Tkinter.Label(root, text='R%s/C%s'%(r,c),
         borderwidth=1 ).grid(row=r,column=c)
root.mainloop(  )
This would produce the following result displaying 12 labels arrayed in a 3 × 4 grid −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
The Initializer Block in Java

The Initializer block is used to declare constructors’ common parts. Let us see an example −
 Live Demo
import java.io.*;
public class Demo{
   {
      System.out.println("The common constructor has been invoked");
   }
   public Demo(){
      System.out.println("The default constructor has been invoked");
   }
   public Demo(int x){
      System.out.println("The parametrized constructor has been invoked");
   }
   public static void main(String arr[]){
      Demo my_obj_1, my_obj_2;
      System.out.println("The Demo objects have been created.");
      my_obj_1 = new Demo();
      my_obj_2 = new Demo(89);
   }
}
The Demo objects have been created.
The common constructor has been invoked
The default constructor has been invoked
The common constructor has been invoked
The parametrized constructor has been invoked
A class named Demo contains a constructor without a parameter, a parameterized constructor, and
the main function. Inside the main function, an instance of the Demo class is created, one with
parameter, and one without parameter.
HTML | <div> align Attribute - GeeksforGeeks

22 Feb, 2022
The HTML div align Attribute is used to specify the alignment of the <div> element or the content present inside the div Element.
Note : This attribute is not supported by HTML5.
Syntax:
<div align="left | right | center | justify";>
Attribute Values:
left: It sets the content to the left-align.
right: It sets the content to the right-align.
center: I sets the div element to the center. By default, it is set to center.
justify: It sets the content to the justify position.
Example:
<!DOCTYPE html><html>  <head>    <title>gfg</title>    <style type=text/css>        p {            background-color: gray;            margin: 10px;        }                  div {            color: white;            background-color: 009900;            margin: 2px;            font-size: 25px;        }                  body {            text-align: center;        }    </style>  </head>  <body>    <h1>GeeksForGeeks</h1>    <h2><div>align Attribute</h2>    <div align="center">       div align="center"  </div>    <div align="left">      div align="left"   </div>    <div align="right">      div align="right"   </div>    <div align="justify">      div align="justify"   </div>  </body>  </html>
Output :
Supported Browsers: The browsers supported by HTML div align Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
chhabradhanvi
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
HTML Cheat Sheet - A Basic Guide to HTML
Form validation using HTML and JavaScript
Design a web page using HTML and CSS
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Subset Sum Problem | Practice | GeeksforGeeks

Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. 

Example 1:
Input:
N = 6
arr[] = {3, 34, 4, 12, 5, 2}
sum = 9
Output: 1 
Explanation: Here there exists a subset with
sum = 9, 4+3+2 = 9.

Example 2:
Input:
N = 6
arr[] = {3, 34, 4, 12, 5, 2}
sum = 30
Output: 0 
Explanation: There is no subset with sum 30.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function isSubsetSum() which takes the array arr[], its size N and an integer sum as input parameters and returns boolean value true if there exists a subset with given sum and false otherwise.
The driver code itself prints 1, if returned value is true and prints 0 if returned value is false.
 
Expected Time Complexity: O(sum*N)
Expected Auxiliary Space: O(sum*N)
 
Constraints:
1 <= N <= 100
1<= arr[i] <= 100
1<= sum <= 105
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Python | Find the closest Key in dictionary - GeeksforGeeks

19 Jul, 2019
The search of keys in dictionary in python has been discussed many times. But sometimes, we may have a problem in which we require to fetch the key which is the nearest one of the given keys. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + keys() + lambdaThe combination of above functions can be used to perform the particular task of finding the closest key in the dictionary. The keys function can be used to access the keys from the dictionary, lambda function can be used to formulate the logic and list comprehension to apply that all to whole list.
# Python3 code to demonstrate working of# Closest key in dictionary# Using list comprehension + keys() + lambda  # initializing dictionarytest_dict = {13 : 'Hi', 15 : 'Hello',  16 : 'Gfg'}  # initializing nearest keysearch_key = 15.6  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using list comprehension + keys() + lambda# Closest key in dictionaryres = test_dict.get(search_key) or test_dict[      min(test_dict.keys(), key = lambda key: abs(key-search_key))]  # printing result print("The value to the closest key : " + str(res))
The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}
The value to the closest key : Gfg

 
Method #2 : Using bisect_left() + OrderedDict()This method generally uses the binary search method of finding the nearest number. While being fast, it changes the ordering and also returns 2 potential candidates for nearest values, current and the next key’s value in sequence. And just returns position of key.
# Python3 code to demonstrate working of# Closest key in dictionary# Using bisect_left() + OrderedDict()import collectionsimport bisect  # initializing dictionarytest_dict = collections.OrderedDict()test_dict = {13 : 'Hi', 15 : 'Hello',  16 : 'Gfg'}  # initializing nearest keysearch_key = 15.6  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using bisect_left() + OrderedDict()# Closest key in dictionaryres = bisect.bisect_left(list(test_dict.keys()), 15.6)  # printing result print("The position of closest key : " + str(res))
The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}
The position of closest key : 3

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
Python Dictionary
Defaultdict in Python
sum() function in Python
Python String | replace()
Defaultdict in Python
Python program to convert a list to string
Python | Split string into list of characters
Python | Convert a list into a tuple
Python Program for Binary Search (Recursive and Iterative)
System Bus Design - GeeksforGeeks

22 Mar, 2021
Definition: 
The electrically conducting path along which data is transmitted inside any digital electronic device. A Computer bus consists of a set of parallel conductors, which may be conventional wires, copper tracks on a PRINTED CIRCUIT BOARD, or microscopic aluminum trails on the surface of a silicon chip. Each wire carries just one bit, so the number of wires determines the largest data WORD the bus can transmit: a bus with eight wires can carry only 8- bit data words, and hence defines the device as an 8-bit device. 
The bus is a communication channel.
The characteristic of the bus is shared transmission media.
The limitation of a bus is only one transmission at a time.
A bus which is used to provide communication between the major components of a computer is called a System bus.
Computer: 
 
System bus contains 3 categories of lines used to provide the communication between the CPU, memory and IO named as:  
1. Address lines (AL)
2. Data lines (DL)
3. Control lines (CL) 
1. Address Lines:  
Used to carry the address to memory and IO.
Unidirectional.
Based on width of a address bus we can determine the capacity of a main memory
Example: 
 
 
2. Data Lines:  
Used to carry the binary data between the CPU, memory and IO.
Bidirectional.
Based on the width of a data bus we can determine the word length of a CPU.
Based on the word length we can determine the performance of a CPU.
Example: 
 
 
3. Control Lines:  
Used to carry the control signals and timing signals
Control signals indicates type of operation.
Timing Signals used to synchronize the memory and IO operations with a CPU clock.
 
toshnaw2
chauhandeepakdc9
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | RISC and CISC
Direct Access Media (DMA) Controller in Computer Architecture
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Tryit Editor v3.7

Tryit: HTML table cells
Lua - Logical Operators

Following table shows all the logical operators supported by Lua language. Assume variable A holds true and variable B holds false then −
Try the following example to understand all the logical operators available in the Lua programming language −
a = 5
b = 20

if ( a and b )
then
   print("Line 1 - Condition is true" )
end

if ( a or b )
then
   print("Line 2 - Condition is true" )
end

--lets change the value ofa and b
a = 0
b = 10

if ( a and b )
then
   print("Line 3 - Condition is true" )
else
   print("Line 3 - Condition is not true" )
end

if ( not( a and b) )
then
   print("Line 4 - Condition is true" )
else
   print("Line 3 - Condition is not true" )
end
When you build and execute the above program, it produces the following result −
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is true
Line 3 - Condition is not true


    12 Lectures 
     2 hours 

 Manish Gupta

    80 Lectures 
     3 hours 

 Sanjeev Mittal

    54 Lectures 
     3.5 hours 

 Mehmet GOKTEPE
 Print
 Add Notes
 Bookmark this page
Download and install pip Latest Version

23 Mar, 2020
PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). After you have successfully installed Python, you would clearly need pip in order to install packages, such as Numpy, Django and lots more on your operating system.
Windows
Linux
macOS
Verification
pip can be downloaded and installed using command-line by going through the following steps:
Download the get-pip.py file and store it in the same directory as python is installed.
Change the current path of the directory in the command line to the path of the directory where the above file exists.
Run the command given below:python get-pip.pyand wait through the installation process.
python get-pip.py
and wait through the installation process.
Voila! pip is now installed on your system.
For more, visit – How to install PIP on Windows ?
pip can be downloaded and installed using the terminal in Linux by going through the following command:
sudo apt-get install python3-pip python-dev
Beginning the installation:
Getting Started:
Providing Disk Space:
Downloading Libraries:
Unpacking File bundles:
Finishing up the Installation:
For more, visit – How to install PIP in Linux?
pip in macOS can be downloaded and installed using command-line by going through the following steps:
Download the get-pip.py file and store it in the same directory as python is installed.orUse the following command to download pip directly,curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Now execute the downloaded file using below commandpython3 get-pip.pyand wait through the installation process.
python3 get-pip.py
and wait through the installation process.
Voila! pip is now installed on your system.
One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:
pip3 --version
Python-pip
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()
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
CSS :nth-child() Selector

02 Nov, 2021
The :nth-child() CSS pseudo-class selector is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child, regardless of the type, of its parent.
Syntax:
:nth-child(number) {
    // CSS Property
}
Where number is the single argument that represents the pattern for matching elements. It can be odd, even, or in a functional notation.
odd: It represents elements whose position is odd in a series: 1, 3, 5, etc.
even: It represents the elements whose position is even in a series: 2, 4, 6, etc.
functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n. Here, A represents the integer step size, B represents the integer offset.
Example 1: In this example, every odd paragraph is selected. Formula used is 2n+1 i.e 1, 3, 5, etc paragraphs are selected.
HTML
<!DOCTYPE html><html>  <head>    <title>CSS :nth-child Selector</title>    <style>    p:nth-child(2n+1) {        background: green;        color: white;    }    </style></head>  <body style="text-align:center">    <h1 style="color:green;">            GeeksforGeeks        </h1>    <h2>            CSS :nth-child Selector        </h2>    <p>A computer science portal for geeks.</p>      <p>Geeks classes an extensive classroom programme.</p>  </body>  </html>
Output:
Example 2: In this example, every even <li> is selected i.e. 2, 4, 6, etc.
HTML
<!DOCTYPE html><html>  <head>    <title>CSS :nth-child Selector</title>    <style>    li {        width: 30%;    }          li:nth-child(even) {        background: green;        color: white;    }    </style></head>  <body style="text-align:center">    <h2>            CSS :nth-child Selector        </h2>      <p>Sorting Algorithms</p>      <ul>        <li>Quick sort.</li>        <li>Merge sort.</li>        <li>Insertion sort.</li>        <li>Selection sort.</li>    </ul></body>  </html>
Output:
Supported Browsers: The browser supported by :nth-child() selector are listed below:
Google Chrome 4.0
Microsoft Edge 12.0
Firefox 3.5
Opera 9.6
Apple Safari 3.2
Internet Explorer 9.0
bhaskargeeksforgeeks
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use read.delim in R?

19 Dec, 2021
In this article, we will learn how to use the read.delim() in the R Programming Language.
The read.delim() function is used to read delimited text files in the R Language. It doesn’t need any external package to work. This function converts a delimited text file into a data frame and can be used to read a variety of space-separated files for example CSV. 
Syntax:
read.delim( file, header)
where:
file: determines the file name to be read with full path.
header: A Boolean that determines whether the first line represents the header of the table. Default is TRUE.
Under this example, we are reading a data frame from a space-separated text file using the read.delim() function in R language.
Text file in use:
Program:
R
# read the space separated dataframedata_frame <- read.delim('sample.txt')  # view data framedata_frame
Output:
       group  y           x
1  category1 55 -0.15703480
2  category1 63  0.63781188
3  category1 62 -1.59689179
4  category1 59 -0.61527367
5  category1 64  0.80799947
6  category1 73  1.03513951
7  category1 56  0.67577537
8  category1 66 -0.37485984
9  category1 73  0.14448351
10 category1 68 -0.53013492
11 category1 63  0.57979608
12 category1 74 -0.08396805
13 category1 67 -0.63099142
14 category1 50 -0.49751923
To read a text file separated by a manual symbol, we use the sep parameter to determine the symbol that separates the data in the text file. In this way, we can read comma-separated-values, tab-separated values, etc.
Syntax:
read.delim( file, sep)
where:
file: determines the file name to be read with full path.
sep: determines table delimiter. Default is a tab (\t).
In this example, we are reading a data frame from a comma-separated text file using the read.delim() function with the sep parameter in the R language. 
Text file in use:
Program:
R
# read the tab separated dataframe data_frame <- read.delim('my_data.txt', sep=',')  # view data framedata_frame
Output:
       group  y           x
1  category1 63  0.95195245
2  category1 77 -1.68432491
3  category1 72  0.03062164
4  category1 67 -1.56885679
5  category1 69 -0.35835908
6  category1 53 -0.87003090
7  category1 73 -0.88877644
8  category1 64  0.67040206
9  category1 66 -0.20397715
10 category1 58 -0.29472917
11 category1 68 -1.47210730
12 category1 68 -1.40288930
13 category1 65 -0.14653898
14 category1 70  0.76216057
15 category1 71 -0.21718205
16 category1 64  0.72430687
17 category1 70 -0.24907560
18 category1 60 -1.24296149
Picked
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
How to use font-awesome icons from Node.js-modules?

07 Oct, 2021
Font-awesome is a web’s icon library that gives you scalable vector icons that can be customized in terms of color, size, and in many more aspects. Many companies integrate this library icon’s on their websites. It has 600+ icons and every icon is mobile and desktop responsive irrespective of the resolution screen size. It also gives us to use animations without the use of javascript.
Syntax for Installing the library:
npm install font-awesome --save
First, we need to enter the above command in the terminal for installing the package.
Once the installation is fixed you can find the package inside the node-modules folder.
Then you need to import the file in style.css file.
After importing the file you can start using the font-awesome icons.
Implementation of code:
In style.css file, import font-awesome by using the following syntax.
@import url('../node_modules/font-awesome/css/font-awesome.min.css');
app.component.html :
<h1>Font-awesome</h1>Notification :<i class='fas fa-bell' style='font-size:24px'></i><br><br>Message or Inbox :<i class='fas fa-envelope' style='font-size:24px'></i><br><br>Bookmark : <i class='fas fa-bookmark' style='font-size:24px'></i><br><br>Like Button :<i class='fas fa-thumbs-up' style='font-size:24px'></i><br><br>Calendar:<i class='fas fa-calendar-alt' style='font-size:24px'></i>
Output:
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
How to read and write Excel file in Node.js ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
How to Add Key-Value pairs to LinkedHashMap in Java?

22 Dec, 2020
LinkedHashMap is a Hash table and linked list implementation of the Map interface. In LinkedHashMap order of key-value pair depends on the order in which keys were inserted into the map. Insertion order does not affect if a key is reinserted into the map.
Example:
Input: 
     Key: 1
     Value : 1221
     Key: 2
     Value : 2112
Output:
    Keys : [1,2]
    Values : [1221,2112]
    Key-Value pairs : [1=1221, 2=2112]
Methods Use:
put(Key, Value): First parameter as key and second parameter as Value.keySet(): Creates a set out of the key elements contained in the hash map.values(): Create a set out of the values in the hash map.
put(Key, Value): First parameter as key and second parameter as Value.
keySet(): Creates a set out of the key elements contained in the hash map.
values(): Create a set out of the values in the hash map.
Approach:
Create two-variable named as Key and ValueAccept the input from user in Key and in ValueUse put() method to add Key-Value pair inside the LinkedHashMap
Create two-variable named as Key and Value
Accept the input from user in Key and in Value
Use put() method to add Key-Value pair inside the LinkedHashMap
Below is the implementation of the above approach:
Java
// Java Program to add key-value // pairs to LinkedHashMapimport java.util.*;public class Main {        public static void main(String[] args)    {        // create an instance of LinkedHashMap        LinkedHashMap<Integer, Integer> map            = new LinkedHashMap<Integer, Integer>();          int num, key, val;        num = 2;        for (int i = 0; i < num; i++) {                        // Taking inputs from user            key = i + 1;            val = key * 10;              // Add mappings using put method            map.put(key, val);        }        // Displaying key        System.out.println("Keys: " + map.keySet());          // Displaying value        System.out.println("Values: " + map.values());          // Displaying key-value pair        System.out.println("Key-Value pairs: "                           + map.entrySet());    }}
Keys: [1, 2]
Values: [10, 20]
Key-Value pairs: [1=10, 2=20]
Time Complexity: O(1)
Java-LinkedHashMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap keySet() Method in Java

26 Nov, 2018
The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them.
Syntax:
hash_map.keySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having the keys of the hash map.
Below programs are used to illustrate the working of java.util.HashMap.keySet() Method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the keySet() 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);          // Using keySet() to get the set view of keys        System.out.println("The set is: " + hash_map.keySet());    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The set is: [20, 25, 10, 30, 15]

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the keySet() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Using keySet() to get the set view of keys        System.out.println("The set is: " + hash_map.keySet());    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The set is: [4, Geeks, You, Welcomes]

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
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.
Queue Interface In Java
Object Oriented Programming (OOPs) Concept in Java
Stack Class in Java
Interfaces in Java
ArrayList in Java
Collections in Java
ChronoZonedDateTime isAfter() method in Java with Examples
Multidimensional Arrays in Java
Introduction to Java
PriorityQueue in Java
PHP make sure string has no whitespace?

To check whether a string has no whitespace, use the preg_match() in PHP.
The syntax is as follows 
preg_match('/\s/',$yourVariableName);
The PHP code is as follows
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$name="John Smith";
if ( preg_match('/\s/',$name) ){
   echo "The name (",$name,") has the space";
} else {
   echo "The Name (",$name,") has not the space";
}
?>
</body>
</html>
This will produce the following output
The name (John Smith) has the space