code-rag-bench/online-tutorials huggingface dataset:
Python - Tkinter Toplevel

Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
Here is the simple syntax to create this widget −
w = Toplevel ( option, ... )

options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The background color of the window.
bd
Border width in pixels; default is 0.
cursor
The cursor that appears when the mouse is in this window.
class_
Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection=0 if you don't want that behavior.
font
The default font for text inserted into the widget.
fg
The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
height
Window height.
relief
Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants.
width
The desired width of the window.
Toplevel objects have these methods −
deiconify()
Displays the window, after using either the iconify or the withdraw methods.
frame()
Returns a system-specific window identifier.
group(window)
Adds the window to the window group administered by the given window.
iconify()
Turns the window into an icon, without destroying it.
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
iconify()
Turns the window into an icon, without destroying it.
state()
Returns the current state of the window. Possible values are normal, iconic, withdrawn and icon.
transient([master])
Turns the window into a temporary(transient) window for the given master or to the window's parent, when no argument is given.
withdraw()
Removes the window from the screen, without destroying it.
maxsize(width, height)
Defines the maximum size for this window.
minsize(width, height)
Defines the minimum size for this window.
positionfrom(who)
Defines the position controller.
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
sizefrom(who)
Defines the size controller.
title(string)
Defines the window title.
Try following example yourself −
from Tkinter import *

root = Tk()
top = Toplevel()
top.mainloop()
When the above code is  executed, it produces the following result −

    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
Deep count of elements of an array using JavaScript

We are required to write a JavaScript function that takes in a nested array of element and return the deep count of elements present in the array.
Input
const arr = [1, 2, [3, 4, [5]]];
Output
const output = 7;
Because the elements at level 1 are 2, elements at level 2 are 2 and elements at level 3 are 1, Hence the deep count is 7.
Following is the code −
 Live Demo
const arr = [1, 2, [3, 4, [5]]];
const deepCount = (arr = []) => {
   return arr
   .reduce((acc, val) => {
      return acc + (Array.isArray(val) ? deepCount(val) : 0);
   }, arr.length);
};
console.log(deepCount(arr));
We used the Array.prototype.reduce() method to iterate over the array and if at any iteration we encountered a nested array, we recursively called our function.
7
How to convert a Map to JSON object using JSON-lib API in Java?

A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format. Initially, we can create a POJO class and pass this instance as an argument to the put() method of Map class and finally add this map instance to the accumulateAll() method of JSONObject.
public void accumulateAll(Map map)
In the below example, we can convert Map to a JSON object.
import java.util.*;
import net.sf.json.JSONObject;

public class ConvertMapToJSONObjectTest {
   public static void main(String[] args)throws Exception {
      JSONObject jsonObject = new JSONObject();
      Map<Integer, Employee> employees = new HashMap<Integer, Employee>();

      employees.put(1, new Employee("Adithya", "Jai", 30));
      employees.put(2, new Employee("Vamsi", "Krishna", 28));
      employees.put(3, new Employee("Chaitanya", "Sai", 30));

      jsonObject.accumulateAll(employees);
      System.out.println(jsonObject.toString(3)); // pretty print JSON
   }
   public static class Employee {
      private String firstName, lastName;
      private int age;
      public Employee(String firstName, String lastName, int age) {
         super();
         this.firstName = firstName;
         this.lastName = lastName;
         this.age = age;
      }
      public String getFirstName() {
         return firstName;
      }
      public String getLastName() {
         return lastName;
      }
      public int getAge() {
         return age;
      }
   }
}
{
 "1": {
 "firstName": "Adithya",
 "lastName": "Jai",
 "age": 30
 },
 "2": {
 "firstName": "Vamsi",
 "lastName": "Krishna",
 "age": 28
 },
 "3": {
 "firstName": "Chaitanya",
 "lastName": "Sai",
 "age": 30
 }
}
Redis - String Getrange Command

Redis GETRANGE command is used to get the substring of the string value stored at the key, determined by the offsets start and end (both are inclusive). Negative offsets can be used in order to provide an offset starting from the end of the string.
The function handles out of range requests by limiting the resulting range to the actual length of the string.
Simple string reply.
Following is the basic syntax of Redis GETRANGE command.
redis 127.0.0.1:6379> GETRANGE KEY_NAME start end

First, set a key in Redis and then get some part of it.
redis 127.0.0.1:6379> SET mykey "This is my test key" 
OK 
redis 127.0.0.1:6379> GETRANGE mykey 0 3 
"This" 
redis 127.0.0.1:6379> GETRANGE mykey 0 -1 
"This is my test key"


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider a disk pack with a seek time of 4 milliseconds and rotational speed of 10000 rotations per minute (RPM). It has 600 sectors per track and each sector can store 512 bytes of data. Consider a file stored in the disk. The file contains 2000 sectors. Assume that every sector access necessitates a seek, and the average rotational latency for accessing each sector is half of the time for one complete rotation. The total time (in milliseconds) needed to read the entire file is _________.(A) 14020(B) 14000(C) 25030(D) 15000Answer: (A)Explanation:
Seek time (given) = 4ms

RPM = 10000 rotation in 1 min [60 sec]
So, 1 rotation will be =60/10000 =6ms [rotation speed]
Rotation latency= 1/2 * 6ms=3ms
# To access a file, 
  total time includes =seek time + rot. latency +transfer time
TO calc. transfer time, find transfer rate

Transfer rate = bytes on track /rotation speed
so, transfer rate = 600*512/6ms =51200 B/ms

transfer time= total bytes to be transferred/ transfer rate
so, Transfer time =2000*512/51200 = 20ms

Given as each sector requires seek tim + rot. latency
= 4ms+3ms =7ms

Total 2000 sector takes = 2000*7 ms =14000 ms
To read entire file ,total time = 14000 + 20(transfer time)
                                = 14020 ms

Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
Can we call a method on "this" keyword from a constructor in java?

The “this ” keyword in Java is used as a reference to the current object, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.
In the following Java program, the Student class contains two private variables name and age with setter methods and, a parameterized constructor which accepts these two values.
From the constructor, we are invoking the setName() and setAge() methods using "this" keyword by passing the obtained name and age values to them respectively.
From the main method, we are reading name and, age values from user and calling the constructor by passing them. Then we are displaying the values of the instance variables name and class using the display() method.
public class Student {
   private String name;
   private int age;
   public Student(String name, int age){
      this.setName(name);
      this.setAge(age);
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      //Calling the constructor that accepts both values
      new Student(name, age).display();
   }
}
Rohan
Enter the age of the student:
18
Name of the Student: Rohan
Age of the Student: 18
How to include CDN Based Version of jQuery in my HTML file?

Easily include jQuery library into your HTML code directly from Content Delivery Network (CDN). Google and Microsoft provide content delivery for the latest version.
You can try to run the following code to learn how to use Google CDN for jQuery:
Live Demo
<html>
   <head>
      <title>jQuery CDN</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
            document.write("Tutorialspoint!");
         });
      </script>
   </head>
   
   <body>
      <h2>Hello</h2>
   </body>
   
</html>
Matplotlib.figure.Figure.set_edgecolor() in Python

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_edgecolor() method figure module of matplotlib library is used to set the edge color of the Figure rectangle.
Syntax: set_edgecolor(self, color)
Parameters: This method accept the following parameters that are discussed below:
color : This parameter is the color.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_edgecolor() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np        fig = plt.figure()       ax = Subplot(fig, 111) fig.add_subplot(ax)   fig.set_edgecolor("green")    fig.suptitle("""matplotlib.figure.Figure.set_edgecolor()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np          fig = plt.figure(figsize =(7, 6))        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])     xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))    fig.set_edgecolor("red")    fig.suptitle("""matplotlib.figure.Figure.set_edgecolor()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
C++ Installation on MacBook M1 for VS Code

12 Mar, 2021
This article is written on CPP installation for the latest  MacBook M1 processor. It’s not like we can’t do CPP programming in the latest MacBook, there is Xcode which is a substitute for other code editors. But still many of the developers like to code on Visual Studio.
So let’s start with this installation of CPP on Visual Studio code.
First download VS Code on your device.
You can also Download M1 specific Visual Studio Code(i.e Visual Studio code- Insiders)
After downloading Visual Studio Code or Visual Studio Code Insiders open it and go to extensions. There is a search tab, just type c++ then click on 1 recommendation and install it. Another extension you have to download is code runner.
During this process, users can come across 2 different types of issues. So let’s discuss what they are and how to resolve them.
Problem 1: After downloading all extensions on VS Code not able to work on CPP.
Follow the below steps to resolve the same issue:
Step 1: Open your terminal and run the below command:
arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/  Homebrew/install/master/install.sh)"
Step 2: Now after the completion of the previous command type : 
arch -x86_64 brew install mingw-w64
Problem 2: #include<bits/stdc++.h> is not found .
If you want to more about the system header file click here. Follow the below steps to resolve the issue:
Step 1: Open terminal using command+space and type terminal.
Step 2: Now move to the below-given path :
/usr/local/include
Step 3: Now create bits directory in the present location
mkdir bits
Step 4: Now move into bits directory and create a file and name it  stdc++.h.
nano stdc++.h
Step 5: After creating a file just copy the code from the GitHub repository and paste that code into stdc++.h file and then press
 {control+x}-> y -> return
Now just try to implement any CPP code to ensure that you are done with the CPP setup on MacBook M1.
C++
#include <bits/stdc++.h>using namespace std;  int main(){    int a= 2, b=4;    cout<<a+b<<endl;    return 0;}
That’s it. You have successfully installed CPP into your Mac M1.
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
Java program to count the number of vowels in a given sentence

To count the number of vowels in a given sentence:
 Read a sentence from the user
 Create a variable (count) initialize it with 0;
 Compare each character in the sentence with the characters {'a', 'e', 'i', 'o', 'u' }
 If a match occurs increment the count.
 Finally print count.
import java.util.Scanner;
public class CountingVowels {
   public static void main(String args[]){
      int count = 0;
      System.out.println("Enter a sentence :");
      Scanner sc = new Scanner(System.in);
      String sentence = sc.nextLine();

      for (int i=0 ; i<sentence.length(); i++){
         char ch = sentence.charAt(i);
         if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'||ch == ' '){
            count ++;
         }
      }
      System.out.println("Number of vowels in the given sentence is "+count);
   }
}
Enter a sentence :
Hi how are you welcome to tutorialspoint
Number of vowels in the given sentence is 22
Resizing images with ImageTk.PhotoImage with Tkinter

The PIL or Pillow library in Python is used for processing images in a Tkinter application. We can use Pillow to open the images, resize them and display in the window. To resize the image, we can use image_resize((width, height) **options) method. The resized image can later be processed and displayed through the label widget.
Let us have a look at the example where we will open an image and resize it to display in the window through the label widget.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

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

# Set the size of the tkinter window
win.geometry("700x350")

# Load the image
image=Image.open('download.png')

# Resize the image in the given (width, height)
img=image.resize((450, 350))

# Conver the image in TkImage
my_img=ImageTk.PhotoImage(img)

# Display the image with label
label=Label(win, image=my_img)
label.pack()

win.mainloop()
Running the above code will display a resized image in the window.
Python Tweepy – Getting the source of a tweet - GeeksforGeeks

18 Jun, 2020
In this article we will see how we can get the source of a status/tweet. The source of the tweet tells us how the tweet was posted. Some examples of sources are :
Twitter for Android
Twitter for iPhone
Twitter Web App
The source attribute of the Status object provides us with the source of the status.
Identifying the source of the status in the GUI :
In the above mentioned status, the source of the status is : Twitter for Android
In order to get the source of the status, we have to do the following :
Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the source attribute present in it.
Identify the status ID of the status from the GUI.
Get the Status object of the status using the get_status() method with the status ID.
From this object, fetch the source attribute present in it.
Example 1 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the statusid = 1272771459249844224  # fetching the statusstatus = api.get_status(id)  # fetching the source attributesource = status.source   print("The source of the status is : " + source)
Output :
The source of the status is : Twitter for Android

Example 2 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1273112322773581824.
# the ID of the statusid = 1273112322773581824  # fetching the statusstatus = api.get_status(id  # fetching the source attributesource = status.source   print("The source of the status is : " + source)
Output :
The source of the status is : Twitter Web App

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
LocalDateTime plusMinutes() method in Java with Examples - GeeksforGeeks

30 Nov, 2018
The plusMinutes() method of LocalDateTime class is used to return a copy of this date-time with the specified minutes added.
Syntax:
public LocalDateTime plusMinutes(long minutes)

Parameter: It accepts a single parameter minutes which specifies the minutes to add which may be negative.
Return Value: This method returns a LocalDateTime based on this date-time with the minutes added.
Exceptions: The programs throws a DateTimeException which is thrown if the result exceeds the supported date range.
Below programs illustrate the YearMonth.plusMinutes() method in Java:
Program 1:
// Program to illustrate the plusMinutes() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        LocalDateTime dt1            = LocalDateTime                  .parse("2018-01-11T10:15:30");          System.out.println("LocalDateTime with 15 minutes added: "                           + dt1.plusMinutes(15));    }}
LocalDateTime with 15 minutes added: 2018-01-11T10:30:30

Program 2:
// Program to illustrate the plusMinutes() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        LocalDateTime dt1            = LocalDateTime                  .parse("2018-01-11T08:15:30");          System.out.println("LocalDateTime with -2 minutes added: "                           + dt1.plusMinutes(-2));    }}
LocalDateTime with -2 minutes added: 2018-01-11T08:13:30

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#plusMinutes(long)
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
p5.js | cursor() Function - GeeksforGeeks

30 Oct, 2019
The cursor() function in p5.js is used to set the cursor to a predefined symbol or an image or it makes visible if already hidden. To set an image as the cursor, the recommended size is 16×16 or 32×32 pixels. The values for parameters x and y must be less than the dimensions of the image.
Syntax:
cursor(type, x, y)
Parameters: This function accepts three parameters as mentioned above and described below:
type: This parameter stores the type of cursor like ARROW, CROSS, HAND, MOVE, TEXT and WAIT Native CSS properties: ‘grab’, ‘progress’, ‘cell’ etc. External: path for cursor’s images (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png).
x: This parameter stores the horizontal active spot of the cursor.
y: This parameter stores the vertical active spot of the cursor.
Below program illustrates the cursor() function in p5.js:
Example: This example uses cursor() function to display the cursor.
function setup() {        // Create canvas    createCanvas(400, 400);          // Set the text size    textSize(40);           // Set the text alignment    // to center    textAlign(CENTER);}  function draw() {    cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');}
Output:
Reference: https://p5js.org/reference/#/p5/cursor
Akanksha_Rai
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Perl matching operator - GeeksforGeeks

07 May, 2019
m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.To print this matched pattern and the remaining string, m operator provides various operators which include $, which contains whatever the last grouping match matched.$& – contains the entire matched string$` – contains everything before the matched string$’ – contains everything after the matched string
Syntax: m/String/
Return:0 on failure and 1 on success
Example 1:
#!/usr/bin/perl -w  # Text String$string = "Geeks for geeks is the best";  # Let us use m operator to search # "or g"$string =~ m/or g/;  # Printing the Stringprint "Before: $`\n";print "Matched: $&\n";print "After: $'\n";
Before: Geeks f
Matched: or g
After: eeks is the best

Example 2:
#!/usr/bin/perl -w  # Text String$string = "Welcome to GeeksForGeeks";  # Let us use m operator to search # "to Ge"$string =~ m/to Ge/;  # Printing the Stringprint "Before: $`\n";print "Matched: $&\n";print "After: $'\n";
Before: Welcome 
Matched: to Ge
After: eksForGeeks

perl-operators
Perl-String
Perl-String-Operators
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | Inheritance in OOPs
Perl | Opening and Reading a File
Perl | Multidimensional Hashes
Perl | Scope of Variables
Perl | ne operator
Perl | Hashes
Perl | Data Types
Perl | defined() Function
puts() vs printf() for printing a string - GeeksforGeeks

27 May, 2021
In C, given a string variable str, which of the following two should be preferred to print it to stdout? 
1) puts(str);
2) printf(str);
puts() can be preferred for printing a string because it is generally less expensive (implementation of puts() is generally simpler than printf()), and if the string has formatting characters like ‘%s’, then printf() would give unexpected results. Also, if str is a user input string, then use of printf() might cause security issues (see this for details). Also note that puts() moves the cursor to next line. If you do not want the cursor to be moved to next line, then you can use following variation of puts(). 
fputs(str, stdout)
You can try following programs for testing the above discussed differences between puts() and printf().
Program 1 
C
// C program to show the use of puts#include <stdio.h>int main(){    puts("Geeksfor");    puts("Geeks");     getchar();    return 0;}
Program 2 
C
// C program to show the use of fputs and getchar#include <stdio.h>int main(){    fputs("Geeksfor", stdout);    fputs("Geeks", stdout);     getchar();    return 0;}
Program 3 
C
// C program to show  the side effect of using// %s in printf#include <stdio.h>int main(){    // % is intentionally put here to show side effects of    // using printf(str)    printf("Geek%sforGeek%s");    getchar();    return 0;}
Program 4 
C
// C program to show the use of puts#include <stdio.h>int main(){    puts("Geek%sforGeek%s");    getchar();    return 0;}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
TusharSharma5
pamanbpl15
simmytarika5
C-Input and Output Quiz
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
fork() in C
std::string class in C++
Enumeration (or enum) in C
Command line arguments in C/C++
TCP Server-Client implementation in C
Different methods to reverse a string in C/C++
Structures in C
Exception Handling in C++
C# | How to change Title of the Console - GeeksforGeeks

28 Jan, 2019
Given the normal Console in C#, the task is to find the default value of Title and change it to something else.
Approach: This can be done using the Title property in the Console class of the System package in C#. The title refers to the string to be displayed in the title bar of the console. The maximum length of the title string is 24500 characters. If the retrieved title is longer than 24500 characters in a get operation then it will give InvalidOperationException and f the retrieved title is longer than 24500 characters in a set operation then it will give ArgumentOutOfRangeException.
Program 1: Finding the default Title
// C# program to illustrate the// Console.Title Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Display current Title        Console.WriteLine("Default Title: {0}",                          Console.Title);    }}}
Output:
Program 2: Changing the Title to 100
// C# program to illustrate the// Console.Title Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Display current Title        Console.WriteLine("Default Title: {0}",                               Console.Title);          // Set the Title to GeeksForGeeks        Console.Title = "GeeksForGeeks";          // Display current Title        Console.WriteLine("Changed Title: {0}",                               Console.Title);    }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
Introduction to .NET Framework
C# | Data Types
What is the difference between a list and an array in C#?

An array stores a fixed-size sequential collection of elements of the same type, whereas list is a generic collection.
To define a List −
List<string7gt; myList = new List<string>();
To set elements in a list, you need to use the Add method −
myList.Add("Audi");
myList.Add("BMW");
myList.Add("Chevrolet");
myList.Add("Hyundai");
To define Arrays −
int[] arr = new int[5];

To initialize and set elements to Arrays −
int[] arr = new int[5] {23, 14, 11, 78, 56};
CSS - margin-top

The margin-top property sets the width of the margin on the top of an element.
length − Any length value.
length − Any length value.
percentage − The margin's width is calculated with respect to the width of the element's containing block.
percentage − The margin's width is calculated with respect to the width of the element's containing block.
auto − Default, Let the browsers automatically set the margin.
auto − Default, Let the browsers automatically set the margin.
All the HTML elements.
object.style.marginTop = "5px"

Here is the example −
<html>
   <head>
   </head>

   <body>
      <p style = "margin-top: 15px; border:1px solid black;">
         This is a paragraph with a specified top margin
      </p>
      
      <p style = "margin-top: 5%; border:1px solid black;">
         This is another paragraph with a specified top margin in percent
      </p>
   </body>
</html>
This will produce following result −

   This is a paragraph with a specified top margin


   This is another paragraph with a specified top margin in percent


    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Sorting string characters by frequency in JavaScript

We are required to write a JavaScript function that takes in the string of characters as the only argument.
Our function should prepare and a new string based on the original string in which the characters that appear for most number of times are placed first followed by number with decreasing frequencies.
For example, if the input to the function is −
const str = 'free';
Then the output should be −
const output = 'eefr';
Since e appears twice it is placed first followed by r and f.
The code for this will be −
 Live Demo
const str = 'free';
const frequencySort = (str = '') => {
   let map = {}
   for (const letter of str) {
      map[letter] = (map[letter] || 0) + 1;
   };
   let res = "";
   let sorted = Object.keys(map).sort((a, b) => map[b] - map[a])
   for (let letter of sorted) {
      for (let count = 0; count < map[letter]; count++) {
         res += letter
      }
   }
   return res;
};
console.log(frequencySort(str));
The steps we took are −
First, we prepared a hashmap of letter count
First, we prepared a hashmap of letter count
Then we sorted the map by count of letters
Then we sorted the map by count of letters
And finally, we generated res string from the sorted letter
And finally, we generated res string from the sorted letter
And the output in the console will be −
eefr
Ruby | Keywords - GeeksforGeeks

26 Oct, 2018
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error.
Example:
# Ruby program to illustrate Keywords   #!/usr/bin/ruby  # here 'if' is a keyword# it can't be used as variableif = 20  # Here 'if' and 'end' are keywords.  # if condition to check whether  # your age is enough for voting if if >= 18  puts "You are eligible to vote."end
Compile Time Error:
Error(s), warning(s):
source_file.rb:7: syntax error, unexpected ‘=’if = 20^source_file.rb:12: syntax error, unexpected >=if if >= 18^source_file.rb:14: syntax error, unexpected keyword_end, expecting end-of-input
There are total 41 keywords present in Ruby as shown below:
Example:
# Ruby program to illustrate the use of Keywords   #!/usr/bin/ruby      # defining class Vehicle # using the 'class' keywordclass GFG     # defining method # using 'def' keyworddef geeks          # printing result     puts "Hello Geeks!!"     # end of the method # using 'end' keywordend     # end of class GFG # using 'end' keywordend     # creating object obj = GFG.new     # calling method using object obj.geeks 
Output:
Hello Geeks!!

Reference: http://ruby-doc.org/docs/keywords/1.9/Object.html
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array slice() function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Include v/s Extend in Ruby
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | String gsub! Method
Ruby | Numeric round() function
Ruby | Types of Iterators
Ruby | Array count() operation
C | Structure & Union | Question 4 - GeeksforGeeks

28 Jun, 2021
Consider the following C declaration
struct {     short s[5];    union {          float y;          long z;     }u; } t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is (GATE CS 2000)
(A) 22 bytes(B) 14 bytes(C) 18 bytes(D) 10 bytesAnswer: (C)Explanation: Short array s[5] will take 10 bytes as size of short is 2 bytes.
When we declare a union, memory allocated for the union is equal to memory needed for the largest member of it, and all members share this same memory space. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).Quiz of this Question
C-Structure & Union
Structure & Union
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Misc | Question 7
Output of C programs | Set 64 (Pointers)
rmdir - Unix, Linux Command

rmdir - remove empty directories
rmdir [OPTION]... DIRECTORY...
Remove the DIRECTORY(ies), if they are empty.

Example-1:
rmdir command will delete the empty directories. i.e directory without any sub-directories or files:
$ rmdir test
Example-2:
To Delete Nested Empty Directories in Linux:
$ rmdir -p dir1/dir2/dir3

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
What are the advantages of Lambda Expressions in Java?


A lambda expression is an inline code that implements a functional interface without creating a concrete or anonymous class. A lambda expression is basically an anonymous method.
Fewer Lines of Code − One of the most benefits of a lambda expression is to reduce the amount of code. We know that lambda expressions can be used only with a functional interface. For instance, Runnable is a functional interface, so we can easily apply lambda expressions.
Sequential and Parallel execution support by passing behavior as an argument in methods − By using Stream API in Java 8, the functions are passed to collection methods. Now it is the responsibility of collection for processing the elements either in a sequential or parallel manner.
Higher Efficiency − By using Stream API and lambda expressions, we can achieve higher efficiency (parallel execution) in case of bulk operations on collections. Also, lambda expression helps in achieving the internal iteration of collections rather than external iteration.
(parameters) -> expression
  or
(parameters) -> { statements; }
import java.util.*;

public class LambdaExpressionTest {
   public static void main(String args[]) {
      new LambdaExpressionTest().print();
   }
   public static void print() {
      List<String> list = new ArrayList<String>();
      list.add("Tutorials Point");
      list.stream().forEach((String) -> { // lambda expression
         System.out.println("The string is: " + list);
      });
   }
}
The string is: [Tutorials Point]
C++ Program for Deadlock free condition in Operating Systems

Given with the P number of processes in the memory and N number of needed resources by them to complete their execution and the task is to find the minimum number of resources R which should be allotted to the processes such that deadlock will never occur.
Deadlock is situation in an operating system where multiple processes residing in the memory doesn’t able to perform their execution because the resources which are needed for program execution is being hold by another resource who is waiting for some other resource for completion.
Let’s say there are two processes P1 and P2 in memory where P1 requires resource R1 and P2 requires resource R2, but the deadlock will arise when P1 hold the resource R2 and wait for the resource R1 similarly P2 hold resource R1 and wait for the resource R2.
This is the example of circular wait which is one of the causes of deadlock. So, to prevent deadlock we need to calculate the number of resources which should be available for the processes such that deadlock will not occur.
R >= P * (N - 1) + 1
where, R is the Resources, P is the processes and N is the need of processes
Input-: processes = 5, need = 3
Output-: minimum required resources are: 11
Input-: Processes = 7, need = 2
Output-: minimum required resources are: 8
Approach used in the below program is as follows −
Input the number of processes and need of the processes in the memory
Apply the formula given to calculate the number of resources required
Display the result
START
Step 1-> declare function to calculate the minimum number of resources needed
   int min_resource(int process, int need)
   declare int calculate = 0
   set calculate = process * (need - 1) + 1
   return calculate
Step 2-> In main()
   Declare int process = 5 and need = 3
   Call min_resource(process, need)
STOP
#include <bits/stdc++.h>
using namespace std;
//calculate minimum number of resources needed
int min_resource(int process, int need) {
   int calculate = 0;
   calculate = process * (need - 1) + 1;
   return calculate;
}
int main() {
   int process = 5, need = 3;
   cout << "minimum required resources are : " <<min_resource(process, need);
   return 0;
}
minimum required resources are : 11
Using combination of “AND” and “OR” in SELECT in ABAP

You can use the following query:
SELECT * FROM my_table
WHERE condition 1
AND condition 2
AND ( id EQ '2' or id EQ ‘3’ ).
Note: There should be space after and before bracket.
Alternatively you can use IN statement as below:
SELECT * FROM my_table
WHERE condition 1
AND condition 2
AND EQ IN ('2', ‘3’ ).
How to extract email id from text using Python regular expression?

The following code using Python regex extracts the email id from given string/text
import re
s ='manogna@tutorialspoint.com56'
result =re.findall('[a-zA-Z0-9]\S*@\S*[a-zA-Z]', s)
print result
This gives the output
['manogna@tutorialspoint.com']
Transform Perl Arrays to Strings

We can use the join() function in Perl to rejoin the array elements and form one long scalar string. This function has the following syntax −
join EXPR, LIST
This function joins the separate strings of LIST into a single string with fields separated by the value of EXPR and returns the string. Following is the example −
 Live Demo
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";

# transform above strings into arrays.
@string = split('-', $var_string);
@names = split(',', $var_names);

$string1 = join( '-', @string );
$string2 = join( ',', @names );

print "$string1\n";
print "$string2\n";
This will produce the following result −
Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry,David,Roger,Ken,Michael,Tom
Default to and select the first item in Tkinter Listbox

Tkinter Listbox widgets are used to display a scrollable list of items with vertically stacked menus. Sometimes, we may need to set the list item selected, by default. We can use the select_set(list_item_index) method by specifying the index of the list items that need to be selected by default.
So, let us suppose that we have a list of programming languages in our Listbox and what we want is to set the first item selected, then we can provide the index of a first list item in the method. The method must be invoked before the end of mainloop() function.
#Import tkinter library
from tkinter import *
#Create an instance of Tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
listbox=Listbox(win) #Create a listbox widget
listbox.pack(padx=10,pady=10,fill=BOTH, expand=True)
listbox.insert(1, "Python")
listbox.insert(2, "Java")
listbox.insert(3, "C++")
listbox.insert(4, "Rust")
listbox.insert(5, "GoLang")
listbox.insert(6, "C#")
listbox.insert(7, "JavaScript")
listbox.insert(8, "R")
listbox.insert(9, "Php")

#Select the first item of listbox
listbox.select_set(0)
win.mainloop()
Running the above code will display a list of programming languages.
In the given output, the first list item in the list box is selected, by default.
What is the difference between All and Any in C# Linq?

Any(<predicate>) method returns true if at least one of the elements in the source sequence matches the provided predicate. Otherwise, it returns false. On the other hand, the All(<predicate>) method returns true if every element in the source sequence matches the provided predicate. Otherwise, it returns false
static void Main(string[] args){
   IEnumerable<double> doubles = new List<double> { 1.2, 1.7, 2.5, 2.4 };
   bool result = doubles.Any(val => val < 1);
   System.Console.WriteLine(result);
   IEnumerable<double> doubles1 = new List<double> { 0.8, 1.7, 2.5, 2.4 };
   bool result1 = doubles1.Any(val => val < 1);
   System.Console.WriteLine(result1);
   Console.ReadLine();
}
False
True
static void Main(string[] args){
   IEnumerable<double> doubles = new List<double> { 0.8, 0.9, 0.6, 0.7 };
   bool result = doubles.All(val => val < 1);
   System.Console.WriteLine(result);
   IEnumerable<double> doubles1 = new List<double> { 0.8, 0.9, 1.0, 0.7 };
   bool result1 = doubles1.All(val => val < 1);
   System.Console.WriteLine(result1);
   Console.ReadLine();
}
True
False
ReactJS – shouldComponentUpdate() method

In this article, we are going to see how to increase the performance of React application by rerendering the component only when the props passed to it changes or on when certain conditions are met.
This method is majorly used to take an exit from the complex React lifecycle, but using it extensively may lead to bugs in the application.
shouldComponentUpdate(nextProps, nextState)
By default, the return value of this method is true; but if it returns false, then the render(), componentWillUpdate() and componentDidUpdate() methods are not called.
In this example, we will build a React application with components only getting re-rendered if the props passed to them changes.
Our first component in the following example is App. This component is the parent of the MyComp component. We are creating MyComp separately and just adding it inside the JSX tree in our App component. Only the App component needs to be exported.
App.jsx
import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = { color: '#000' };
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
            <button onClick={() => this.setState({ color: '#ff0000' })}>
               Change Color
            </button>
            <MyComp />
         </div>
      );
   }
}
class MyComp extends React.Component {
   shouldComponentUpdate(nextProps) {
      // Rendering the component only if
      // passed props value is changed
      if (nextProps.value !== this.props.value) {
         return true;
      } else {
         return false;
      }
   }
   render() {
      console.log('MyComp component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
In the above example, MyComp component gets re-rendered only if the received props and the previous props are different. The above code will generate the following result −
In the next example, we are going to execute the same code without shouldComponentUpdate() method to see the difference.
App.jsx
import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = { color: '#000' };
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
            <button onClick={() => this.setState({ color: '#ff0000' })}>
               Change Color
            </button>
            <MyComp />
         </div>
      );
   }
}
class MyComp extends React.Component {
   render() {
      console.log('MyComp component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
Here, MyComp component gets re-rendered every time when the parent component, i.e., the App component gets re-rendered. The above code will generate the following result −