code-rag-bench/online-tutorials huggingface dataset:
Output of C programs | Set 36 - GeeksforGeeks

19 Jun, 2019
1. What will be the output of following?
void main(){    int const* p = 5;    printf("%d", ++(*p));}
Options:A. 6B. 5C. Garbage ValueD. Compiler Error
Answer : D
Explanation : It will give compile time error because we are trying to change the constant value. p is a pointer to a “constant integer”. But we tried to change the value of the “constant integer”.
2. What will be the output of following?
void main(){    char* p;    printf("%d %d", sizeof(*p), sizeof(p));}
Options:A. 1 1B. 1 8C. 2 1D. 2 2
Answer : B
Explanation : The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 8.
3. What will be the output of following?
void main(){    int m, i = 0, j = 1, k = 2;    m = i++ || j++ || k++;    printf("%d %d %d %d", m, i, j, k);}
Options:A. 1 1 2 3B. 1 1 2 2C. 0 1 2 2D. 0 1 2 3
Answer : B
Explanation : In an expression involving || operator, evaluation takes place from left to right and will be stopped if one of its components evaluates to true(a non zero value).So in the given expression m = i++ || j++ || k++.It will be stop at j and assign the current value of j in m.therefore m = 1, i = 1, j = 2 and k = 2 (since k++ will not encounter. so its value remain 2)
4. What will be the output of following?
void main(){    int i = 0;    printf("%d %d", i, i++);}
Options:A. 0 1B. 1 0C. 0 0D. 1 1
Answer : B
Explanation : Since the evaluation is from right to left. So when the print statement execute value of i = 0, as its executing from right to left – when i++ will be execute first and print value 0 (since its post increment ) and after printing 0 value of i become 1.
5. What will be the output of following?
#include <stdio.h>int main(void){    char p;    char buf[10] = { 1, 2, 3, 4, 5, 6, 9, 8 };    p = (buf + 1)[5];    printf("%d", p);    return 0;}
Options:A. 5B. 6C. 9D. Error
Answer : C
Explanation : x[i] is equivalent to *(x + i), so (buf + 1)[5] is *(buf + 1 + 5), or buf[6].
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Runtime Errors
Output of Java Program | Set 3
unsigned specifier (%u) in C with Examples
Output of C++ Program | Set 1
Output of Java program | Set 5
How to show full column content in a PySpark Dataframe ?
Output of Java Program | Set 7
Output of C Programs | Set 3
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
How to run a timer in background within your iOS app

If you wish to run a timer in background within your iOS Application, Apple provides beginBackgroundTaskWithExpirationHandler method, you can read more about the same https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiration.
We will be using the same for writing our code for running the timer in background.
So let’s begin.
Step 1 − Open Xcode → Single View Application → Let’s name is BackgroundTimer.
Step 2 − Open AppDelegate.swift and under method applicationDidEnterBackground write the below code.
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
   UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
_ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)
Step 3 − Write new function doSomething()
@objc func doSomething() {
   print("I'm running")
}
func applicationDidEnterBackground(_ application: UIApplication) {
   backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
      UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
   })
   _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)
}
@objc func doSomething() {
   print("I'm running")
}
Run the application
Here we are printing “I’m running” when the application goes to background. When the app goes in background “I’m running” will start printing on the console. Tap the home button and test. However you can run your timer maximum for 3 minutes when your app is in background as specified in Apple documentation and tested.
While running this application, make the application in background and wait for 3 minutes you’ll see after 3 minutes “I’m running” won’t print. Now bring application to foreground and you will notice “I’m running” started printing.
How "getElementByID" works in JavaScript?

The getElementById() is a DOM method used to return the element that has the ID attribute with the specified value. This is one of the most common methods in the HTML DOM and is used almost every time we want to manipulate an element on our document. This method returns null if no elements with the specified ID exists. The ID should be unique within a page. However, if more than one element with the specified ID exists, it returns the last element in the javascript code.
In the following example, there exists a paragraph tag with the inner text "GetElementById" and with an id called "element". Using the DOM method "document.getElementById()" the text inside the paragraph tag is accessed and the value is displayed in the output. Without ".innerHtml" the document.getElementById can't read the inner text part of any tag.
<html>
<body>
<p id="element">GetElementById</p>
<script>
   var s = document.getElementById("element").innerHTML;
   document.write(s);
</script>
</body>
</html>
GetElementById
GetElementById
In the following example, using the DOM method "getElementById" we have replaced the original text part "GetElementById" with the text "Tutorix" and the result is displayed in the output.
<html>
<body>
<p id="element">GetElementById</p>
<script>
   document.getElementById("element").innerHTML = "Tutorix";
</script>
</body>
</html>
Tutorix
R Statistics - Percentiles

Percentiles are used in statistics to give you a number that describes the value that a given percent of
the values are lower than.
If we take a look at the values of the wt 
(weight) variable from the mtcars data set:
What is the 75. percentile of the weight of the cars? The answer is 3.61 or 3 610 lbs, meaning that 75% or the cars weight 3 610 lbs or less:
Result:
75% 
3.61
If you run the quantile() function without specifying the c() parameter, you will get 
the percentiles of 0, 25, 50, 75 and 100:
Result:
     0%     25%     50%     75%    100% 
1.51300 2.58125 3.32500 3.61000 5.42400 

Quartiles are data divided into four parts, when sorted in an ascending order:

The value of the first quartile cuts off the first 25% of the data
The value of the second quartile cuts off the first 50% of the data
The value of the third quartile cuts off the first 75% of the data
The value of the fourth quartile cuts off the 100% of the data

The value of the first quartile cuts off the first 25% of the data
The value of the second quartile cuts off the first 50% of the data
The value of the third quartile cuts off the first 75% of the data
The value of the fourth quartile cuts off the 100% of the data
Use the quantile() function to get the quartiles.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Google Charts - Material bar chart

Following is an example of a material bar chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used Bar class to show material chart.
//classic chart
var chart = new google.visualization.BarChart(document.getElementById('container'));

//Material chart
var chart = new google.charts.Bar(document.getElementById('container'));

//set the bar to be horizontal using options
var options = {      
   bars: 'horizontal'	  
}; 

googlecharts_bar_material.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart','bar']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable([
               ['Year', 'Asia', 'Europe'],
               ['2012',  900,      390],
               ['2013',  1000,      400],
               ['2014',  1170,      440],
               ['2015',  1250,       480],
               ['2016',  1530,      540]
            ]);

            var options = {title: 'Population (in millions)', bars: 'horizontal'};  

            // Instantiate and draw the chart.
            var chart = new google.charts.Bar(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Find the first circular tour that visits all petrol pumps in C++ Program

Suppose there is a circle, and there are n petrol pumps on the circle. We have two sets of data like −
The amount of petrol that every petrol pump has
Distance from one petrol pump to another.
Calculate the first point, from where a truck will be able to complete the circle. Assume for 1 liter petrol, the truck can go 1 unit of distance. Suppose there are four petrol pumps, and the amount of petrol, and distance from the next petrol pump is as like [(4, 6), (6, 5), (7, 3), (4, 5)], the first point from where truck can make a circular tour is 2nd petrol pump. Output should be start = 1 (index of second patrol pump)
This problem can be solved efficiently using queue. Queue will be used to store the current tour. We will insert the first petrol pump into the queue, we will insert petrol pumps till, we either complete the tour, or current amount of petrol becomes negative. If the amount becomes negative, then we keep deleting petrol pumps until it becomes empty.
 Live Demo
#include <iostream>
using namespace std;
class pump {
   public:
   int petrol;
   int distance;
};
int findStartIndex(pump pumpQueue[], int n) {
   int start_point = 0;
   int end_point = 1;
   int curr_petrol = pumpQueue[start_point].petrol - pumpQueue[start_point].distance;
   while (end_point != start_point || curr_petrol < 0) {
      while (curr_petrol < 0 && start_point != end_point) {
         curr_petrol -= pumpQueue[start_point].petrol - pumpQueue[start_point].distance;
         start_point = (start_point + 1) % n;
         if (start_point == 0)
            return -1;
      }
      curr_petrol += pumpQueue[end_point].petrol - pumpQueue[end_point].distance;
      end_point = (end_point + 1) % n;
   }
   return start_point;
}
int main() {
   pump PumpArray[] = {{4, 6}, {6, 5}, {7, 3}, {4, 5}};
   int n = sizeof(PumpArray)/sizeof(PumpArray[0]);
   int start = findStartIndex(PumpArray, n);
   if(start == -1)
      cout<<"No solution";
   else
      cout<<"Index of first petrol pump : "<<start;
}
Index of first petrol pump : 1
How can we convert a list to the JSON array in Java?

The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. An object is an unordered collection of key/value pairs and an array is an ordered sequence of values.
We can convert a list to the JSON array using the JSONArray.toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.
public static java.lang.String toJSONString(java.util.List list)
import java.util.*;
import org.json.simple.*;
public class ConvertListToJSONArrayTest {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("India");
      list.add("Australia");
      list.add("England");
      list.add("South Africa");
      list.add("West Indies");
      list.add("Newzealand");
      // this method converts a list to JSON Array
      String jsonStr = JSONArray.toJSONString(list);
      System.out.println(jsonStr);
   }
}
["India","Australia","England","South Africa","West Indies","Newzealand"]
Genpact India Pvt Ltd Interview Experience for SDE Role (Off-Campus) - GeeksforGeeks

09 Dec, 2021
I have applied at Genpact through a referral that was given by my senior, rounds are as follows:-
First Round(Technical Round): It went for 1.5 hrs and they have asked the following questions:-
IntroductionHow does Java Works?What is Interface, write a code to explain it?What are Collections in java, explain any one collection through coding?What is Exception Handling in java?Print a Matrix in Snake PatternPrint the following pattern for input 5.*####
###**
***##
###**
*####What are Debouncing and throttling in Javascript?Explain Closure with a sample code?Explain async and await in Javascript?Can you describe the main difference between the Array.forEach() loop and Array.map() methods and why you would pick one versus the other?What’s a typical use case for anonymous functions?What’s the difference between host objects and native objects?Explain the difference between: function Person(){}, var person = Person(), and var person = new Person()?Explain Your final year project. (and some counter questions on it)
Introduction
How does Java Works?
What is Interface, write a code to explain it?
What are Collections in java, explain any one collection through coding?
What is Exception Handling in java?
Print a Matrix in Snake Pattern
Print the following pattern for input 5.*####
###**
***##
###**
*####
*####
###**
***##
###**
*####
What are Debouncing and throttling in Javascript?
Explain Closure with a sample code?
Explain async and await in Javascript?
Can you describe the main difference between the Array.forEach() loop and Array.map() methods and why you would pick one versus the other?
What’s a typical use case for anonymous functions?
What’s the difference between host objects and native objects?
Explain the difference between: function Person(){}, var person = Person(), and var person = new Person()?
Explain Your final year project. (and some counter questions on it)
Second Round(HR Round+Cultural Fit Round):-
IntroductionTell me something about your college which you don’t like.Tell me your five Weaknesses.Why Genpact?Why should I hire you?You Salary Expectations?
Introduction
Tell me something about your college which you don’t like.
Tell me your five Weaknesses.
Why Genpact?
Why should I hire you?
You Salary Expectations?
It went for 25 minutes almost and finally, I got selected.
Genpact
Marketing
Off-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience
Amazon Interview Experience for SDE-1
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Persistent Systems Interview Experience (Martian Program)
Zoho Interview | Set 2 (On-Campus)
How to Fix: if using all scalar values, you must pass an index - GeeksforGeeks

19 Dec, 2021
In this article, we discuss how to fix the error: if using all scalar values, you must pass an index in Python.
Python3
# Importing pandas libraryimport pandas as pd;  # Creating a dictionary or the data to # be converted to the dataframedict = {'column-1': 1,'column-2': 2,        'column-3': 3,'column-4': 4}  # Converting to the dataframedf = pd.DataFrame(dict)  print(df)
Output:
ValueError: If using all scalar values, you must pass an index
The column values that are going to be present must be a vector i.e lists [a,b,c], and not the scalars it should be a list as per the syntax of the function to convert it into the data frame. After converting that into the data frame the keys appear as the column headers and values i.e value of the dictionary appears as the columns. 
In this method, an error can be fixed where the user needs to convert the scalars as vectors by making them as lists in python.
Example:
Python3
# Importing pandas libraryimport pandas as pd  # Creating a dictionary or the data to# be converted to the dataframedict = {'column-1': [1], 'column-2': [2],         'column-3': [3], 'column-4': [4]}  # Converting to the dataframedf = pd.DataFrame(dict)  print(df)
Output:
   column-1  column-2  column-3  column-4
0         1         2         3         4
In this method, an error can be fixed where the user needs to specify the index while converting it into a data frame in python language.
Syntax:
pd.DataFrame(dict,index=[0])
Python3
# Importing pandas libraryimport pandas as pd  # Creating a dictionary or the data to # be converted to the dataframedict = {'column-1': 1, 'column-2': 2,         'column-3': 3, 'column-4': 4}  # Converting to the dataframedf = pd.DataFrame(dict, index=[0])  print(df)
Output:
   column-1  column-2  column-3  column-4
0         1         2         3         4
Picked
Python How-to-fix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
How to post data to specific URL using WebClient in C#?

We can Get and Post data from a Web API using Web client. Web client provides
common methods for sending and receiving data from Server
Web client is easy to use for consuming the Web API. You can also use httpClient
instead of WebClient
The WebClient class uses the WebRequest class to provide access to resources.
WebClient instances can access data with any WebRequest descendant registered with
the WebRequest.RegisterPrefix method.
Namespace:System.Net
Assembly:System.Net.WebClient.dll
UploadString Sends a String to the resource and returns a String containing any response.
class Program{
   public static void Main(){
      User user = new User();
      try{
         using (WebClient webClient = new WebClient()){
            webClient.BaseAddress = "https://jsonplaceholder.typicode.com";
            var url = "/posts";
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            webClient.Headers[HttpRequestHeader.ContentType] ="application/json";
            string data = JsonConvert.SerializeObject(user);
            var response = webClient.UploadString(url, data);
            var result = JsonConvert.DeserializeObject<object>(response);
            System.Console.WriteLine(result);
         }
      }
      catch (Exception ex){
         throw ex;
      }
   }
}
class User{
   public int id { get; set; } = 1;
   public string title { get; set; } = "First Data";
   public string body { get; set; } = "First Body";
   public int userId { get; set; } = 222;
}
{
   "id": 101,
   "title": "First Data",
   "body": "First Body",
   "userId": 222
}
Generating random number in a range in C - GeeksforGeeks

23 Apr, 2018
How to generate a random number in a given range in C.
Examples:
Input : Lower = 50,
        Upper = 100,
        Count of random Number = 5 
Output : 91 34 21 88 29 
Explanation: lower is the lower limit of the 
range and upper is the upper limit of the range.
Output contains 5 random numbers in given range.


As C does not have an inbuilt function for generating a number in the range, but it does have rand function which generate a random number from 0 to RAND_MAX. With the help of rand () a number in range can be generated as num = (rand() % (upper – lower + 1)) + lower
// C program for generating a// random number in a given range.#include <stdio.h>#include <stdlib.h>#include <time.h>  // Generates and prints 'count' random// numbers in range [lower, upper].void printRandoms(int lower, int upper,                              int count){    int i;    for (i = 0; i < count; i++) {        int num = (rand() %           (upper - lower + 1)) + lower;        printf("%d ", num);    }}  // Driver codeint main(){    int lower = 5, upper = 7, count = 1;      // Use current time as     // seed for random generator    srand(time(0));      printRandoms(lower, upper, count);      return 0;}
7

Note : Output generated on each run may be different because number is generated randomly.
Random Algorithms
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
3D scatterplots in Python Matplotlib with hue colormap and legend

To plot 3D scatter plots in Python with hue colormap and legend, we can take the following steps−
Set the figure size and adjust the padding between and around the subplots
Create x, y and z data points using numpy.
Create a new figure or activate an existing figure using figure() method.
Get the current axes, creating one if necessary.
Get the hue colormap, defining a palette.
Plot x, y and z data points using scatter() method.
Place a legend on the plot.
To display the figure, use show() method.
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

fig = plt.figure()
ax = fig.gca(projection='3d')
cmap = ListedColormap(sns.color_palette("husl", 256).as_hex())
sc = ax.scatter(x, y, z, s=40, c=x, marker='o', cmap=cmap, alpha=1)
plt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05, 1), loc=2)

plt.show()
Explain the concept of Sorting in C language

Why sorting makes searching easier in C language? How can you judge the sorting efficiency in C?
Sorting is the process of arranging elements either in ascending (or) descending order.
The term sorting came into existence when humans realized the importance of searching quickly.
The term sorting came into existence when humans realized the importance of searching quickly.
There are different things in life that we need to search for, particular record in database, roll numbers in a list, a number in a telephone directory, a specific page in a book etc.
There are different things in life that we need to search for, particular record in database, roll numbers in a list, a number in a telephone directory, a specific page in a book etc.
If the data was kept in an unordered and unsorted form, it becomes difficult to search a particular thing. But fortunately, the concept of sorting came into existence, making it easier for everyone to arrange data in an order.
If the data was kept in an unordered and unsorted form, it becomes difficult to search a particular thing. But fortunately, the concept of sorting came into existence, making it easier for everyone to arrange data in an order.
Sorting arranges data in a sequence which makes searching easier.
Sorting arranges data in a sequence which makes searching easier.
If we want to arrange a deck of cards in order, we will start by checking every card, and accordingly, make the deck as we move on.
If we want to arrange a deck of cards in order, we will start by checking every card, and accordingly, make the deck as we move on.
It takes so much of time to arrange the deck in order, yet we do it in the same manner. But, computers don't work like this.
It takes so much of time to arrange the deck in order, yet we do it in the same manner. But, computers don't work like this.
From the beginning of the programming age, scientists have been working on solving the problem of sorting by different algorithms to sort the data.
From the beginning of the programming age, scientists have been working on solving the problem of sorting by different algorithms to sort the data.
The criteria to judge which algorithm is better than the other is as follows −
Time taken to sort the given data.
Memory Space required to do so.
Following is the C program for sorting the data −
#include<stdio.h>
int main(){
   int a[50], i,j,n,t,sm;
   printf("enter the No: of elements in the list:\n");
   scanf("%d", &n);
   printf("enter the elements:\n");
   for(i=0; i<n; i++){
      scanf ("%d", &a[i]);
   }
   for (i=0; i<n-1; i++){
      sm=i;
      for (j=i+1; j<n; j++){
         if (a[j] < a[sm]){
            sm=j;
         }
      }
      t=a[i];
      a[i]=a[sm];
      a[sm]=t;
   }
   printf ("after selection sorting the elements are:\n");
   for (i=0; i<n; i++)
      printf("%d\t", a[i]);
   return 0;
}
When the above program is executed, it produces the following result −
enter the No: of elements in the list:
4
enter the elements:
34
12
56
7
after selection sorting the elements are:
7 12 34 56
Vim - Tips And Tricks

Now we got fair idea about Vim. Let us discuss few tips and tricks of Vim to improve productivity. In this section, we will discuss following items −
Convert spaces to tabs and vice-versa
Highlight miss-spelled words
Word completion
Copy line character by character
Indent code
Change file format
If you are editing a file and you want to convert entered tab character to spaces then execute following command −
:set expandtab

Note that, this command will not change existing tabs to spaces. To achieve this execute following command −
:set tabstop = 4 shiftwidth = 4 expandtab 
:retab

In above command we are instructing Vim to convert tabs into 4 spaces
To convert spaces to tabs execute below command −
:set noexpandtab :retab!

We can instruct Vim to highlight miss-spelled words. To do this execute following command −
:set spell

Below image highlights misspelled word in Vim −
Vim also provides word completion. For this execute following command in insert mode −
Ctrl + p

Use following command to copy and paste line character by character −
Copy and paste text located above the cursor
Copy and paste text located below the cursor
Note the we have to use these commands in insert mode.
If you have un-indented code to indent it execute following command −
=%

For instance, if you have un-indented code like this −
Then go to line 4 and execute =% command. It will indent code like this −
To change file format to UNIX execute following command −
:set ff = unix

To change file format to DOS execute following command −
:set ff = dos


    46 Lectures 
     5.5 hours 

 Jason Cannon
 Print
 Add Notes
 Bookmark this page
Explain the END OF FILE (EOF) with a C Program

The End of the File (EOF) indicates the end of input.
After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.
Refer to the algorithm given below for EOF.
Step 1: Open file in write mode.
Step 2: Until character reaches end of the file, write each character in filepointer.
Step 3: Close file.
Step 4: Again open file in read mode.
Step 5: Reading the character from file until fp equals to EOF.
Step 5: Print character on console.
Step 6: Close file.
Following is the C program for End of File (EOF) −
#include <stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w"); //open the file in write mode
   printf("enter the text then press cntrl Z:\n");
   while((ch = getchar())!=EOF) //reading char by char until it equals to EOF{
      i.e. when u press ctrlZ the while loop terminates
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF) //reading the character from file until fp equals to EOF{
      putchar(ch);
   }
   fclose(fp);
   return 0;
}
When the above program is executed, it produces the following result −
enter the text then press cntrl Z:
This is the EOF demonstration example
if your text typing is over press cntrlZ
^Z
text on the file:
This is the EOF demonstration example
if your text typing is over press cntrlZ
Python Pandas - Return the string alias of the Time series frequency applied on the given Period object

To return the string alias of the Time series frequency applied on the given Period object, use the period.freqstr property.
At first, import the required libraries −
import pandas as pd
The pandas.Period represents a period of time. Creating two Period objects −
period1 = pd.Period("2020-09-23 03:55:20")
period2 = pd.Period(freq="Y", year = 2021, month = 2, day = 14, hour = 2, minute = 35)
Display the Period objects −
print("Period1...\n", period1)
print("Period2...\n", period2)
Get the string alias of the frequency −
res1 = period1.freqstr
res2 = period2.freqstr
Following is the code −
import pandas as pd

# The pandas.Period represents a period of time
# creating two Period objects
period1 = pd.Period("2020-09-23 03:55:20")
period2 = pd.Period(freq="Y", year = 2021, month = 2, day = 14, hour = 2, minute = 35)

# display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# get the string alias of the frequency
res1 = period1.freqstr
res2 = period2.freqstr

# Return the string alias of the frequency from two Period objects
print("\nString alias of the frequency from the 1st Period object ...\n", res1)
print("\nString alias of the frequency from the 2nd Period object ...\n", res2)
This will produce the following code −
Period1...
2020-09-23 03:55:20

Period2...
2021

String alias of the frequency from the 1st Period object ...
<Second>

String alias of the frequency from the 2nd Period object ...
<YearEnd: month=12>
Tryit Editor v3.7

HTML Input types
Tryit: input type = number
How can I use MySQL IF() function within SELECT statement?

It is quite possible to use MySQL IF() function within SELECT statement by providing the name of the column along with a condition as the first argument of IF() function. To understand it, consider the following data from table ‘Students’.
mysql> Select * from Students;
+----+-----------+-----------+----------+----------------+
| id | Name      | Country   | Language | Course         |
+----+-----------+-----------+----------+----------------+
| 1  | Francis   | UK        | English  | Literature     |
| 2  | Rick      | USA       | English  | History        |
| 3  | Correy    | USA       | English  | Computers      |
| 4  | Shane     | France    | French   | Computers      |
| 5  | Validimir | Russia    | Russian  | Computers      |
| 6  | Steve     | Australia | English  | Geoinformatics |
| 7  | Rahul     | India     | Hindi    | Yoga           |
| 8 | Harshit | India | Hindi | Computers |
+----+-----------+-----------+----------+----------------+
8 rows in set (0.00 sec)
Now, with the help of the following query, having IF() function within SELECT statement, we are going to get the names and course details of the Students and if they have the English Language then it writes ‘Eng_Language’ otherwise ‘Other language’.
mysql> Select Name, IF(Language = 'English', "Eng_Language", "Other Language") AS 'Native Language', Course from students;
+-----------+-----------------+----------------+
| Name      | Native Language | Course         |
+-----------+-----------------+----------------+
| Francis   | Eng_Language    | Literature     |
| Rick      | Eng_Language    | History        |
| Correy    | Eng_Language    | Computers      |
| Shane     | Other Language  | Computers      |
| Validimir | Other Language  | Computers      |
| Steve     | Eng_Language    | Geoinformatics |
| Rahul     | Other Language  | Yoga           |
| Harshit   | Other Language  | Computers      |
+-----------+-----------------+----------------+
8 rows in set (0.00 sec)
How to retrieve source code from Python objects?

We use the getsource() method of inspect module to get the source code of the function.
inspect.getsource(object)
Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.
If the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.
We import the inspect module and retrieve the source code for given script as follows
#baz.py
import inspect
class foo:
      def bar():
          print 'Hello'
print(inspect.getsource(foo))
C:/Users/TutorialsPoint1/~.py
class foo:
      def bar():
          print 'Hello'
How to convert Date to String in Java 8?

The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.
Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.
The toString() method of the LocalDate class converts the date value of the current Date object in to String and returns it.
Following Java example accepts month, year and, day values from user, creates a date object from it and, converts it to String.
import java.time.LocalDate;
import java.util.Scanner;
public class DateToString {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      System.out.println("Enter the month: ");
      int month = sc.nextInt();
      System.out.println("Enter the day: ");
      int day = sc.nextInt();
      //Getting the given date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      //Converting given date to String
      String date = givenDate.toString();
      System.out.println("Given date :"+date);
   }
}
Enter the year:
2019
Enter the month:
09
Enter the day:
26
Given date :2019-09-26
Python | Pandas Timestamp.replace

14 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.replace() function is used to replace the member values of the given Timestamp. The function implements datetime.replace, and it also handles nanoseconds.
Syntax :Timestamp.replace()
Parameters :year : intmonth : intday : inthour : intminute : intsecond : intmicrosecond : intnanosecond : inttzinfo : intfold : int
Return : Timestamp with fields replaced
Example #1: Use Timestamp.replace() function to replace the year value in the given Timestamp.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                  hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.replace() function to replace the current year in the object with 2019.
# replace yearts.replace(year = 2019)
Output :
As we can see in the output, the Timestamp.replace() function has returned a Timestamp object with year value equal to 2019.
Example #2: Use Timestamp.replace() function to replace the year, month and hour value in the given Timestamp.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                  hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.replace() function to replace the current year, month and hour value in the object.
# replace year, month and hour valuets.replace(year = 2019, month = 12, hour = 1)
Output :
As we can see in the output, the Timestamp.replace() function has returned a Timestamp object with year value equal to 2019, month value equal to 12 and hour value equal to 1.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between std::set vs std::vector in C++ STL

21 Jun, 2022
Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators.
Examples:
vector <int> v;
v.push_back(1);
v.push_back(2);
v.clear();
Below is the implementation of vectors in C++: 
C++
// C++ program to demonstrate the// working of vector in cpp#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){    vector<int> v;     // Inserting elements in vector    v.push_back(11);    v.push_back(6);    v.push_back(12);    v.push_back(0);    v.push_back(0);     // Elements are stored in the    // order of insertion with the    // duplicate element    cout << "Elements in vector are:\n";    for (auto it : v) {        cout << it << " ";    }     return 0;}
Elements in vector are:
11 6 12 0 0
Time Complexity: O(N) // For N insertionsAuxiliary Space: O(1)
Set: Set is also one of the templates of Standard Template Library or STL. It is a container of unique elements whose value can’t be modified once added to the set, but can be deleted or inserted. The elements of the sets are always stored in sorted form.
Examples:
set <int> s;
s.insert(1);
s.insert(12);
int key = 1;
s.erase(key);
Below is the implementation of sets in C++: 
C++
// C++ program to demonstrate the// working of set in c++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){    set<int> s;     // Insert elements into the set    s.insert(11);    s.insert(6);    s.insert(12);    s.insert(0);     // Duplicate elements    s.insert(0);     cout << "Elements in set:\n";     // The inserted elements get sorted     // Print the elements of the set    for (auto it : s) {        cout << it << " ";    }     return 0;}
Elements in set:
0 6 11 12
Time Complexity: O(Nlog N) // For N insertionsAuxiliary Space: O(1)
Tabular Difference between the vector and set:
Vector
Set
jayanth_mkv
cpp-set
cpp-vector
C++
C++ Programs
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Writing First C++ Program - Hello World Example
Object Oriented Programming in C++
Inheritance in C++
Basic Input / Output in C++
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
C++ program for hashing with chaining
Passing a function as a parameter in C++
Java Type Casting Examples

We can convert one data types into another data type using casting when narrowing happens in case widening happens, no casting is required. 
Narrowing refers to passing a higher size data type like int to a lower size data type like short. It may lead to data loss. Following program output will be 44.
public class MyFirstJavaProgram {
   public static void main(String []args) {
      int a = 300;
      byte b = (byte)a; // narrowing
      System.out.println(b);
   }
}
Widening refers to passing a lower size data type like int to a higher size data type like long. 
public class MyFirstJavaProgram {
   public static void main(String []args) {
      int a = 300;
      long b = a;
      System.out.println(b);
   }
}
sympy.stats.Exponential() in python

05 Jun, 2020
With the help of sympy.stats.Exponential() method, we can get the continuous random variable representing the exponential distribution.
Syntax : sympy.stats.Exponential(name, rate)Return : Return continuous random variable.
Example #1 :In this example we can see that by using sympy.stats.Exponential() method, we are able to get the continuous random variable which represents the Exponential distribution by using this method.
# Import sympy and Exponentialfrom sympy.stats import Exponential, densityfrom sympy import Symbol  rate = Symbol("rate", integer = True, positive = True)z = Symbol("z")  # Using sympy.stats.Exponential() methodX = Exponential("x", rate)gfg = density(X)(z)  pprint(gfg)
Output :
-rate*zrate*e
Example #2 :
# Import sympy and Exponentialfrom sympy.stats import Exponential, densityfrom sympy import Symbol  rate = 5z = 0.5  # Using sympy.stats.Exponential() methodX = Exponential("x", rate)gfg = density(X)(z)  pprint(gfg)
Output :
0.410424993119494
Python SymPy-Stats
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
issubset() in python

20 May, 2022
Python set issubset() method returns True if all elements of a set A are present in another set B which is passed as an argument and returns false if all elements not present.
A.issubset(B)
checks whether A is a subset of B or not.
returns true if A is a subset of B otherwise false.
Python
# Python program to demonstrate working of# issubset(). A = {4, 1, 3, 5}B = {6, 0, 4, 1, 5, 0, 3, 5} # Returns Trueprint(A.issubset(B)) # Returns False# B is not subset of Aprint(B.issubset(A))
Output: 
True
False
Python
# Another Python program to demonstrate working# of issubset().A = {1, 2, 3}B = {1, 2, 3, 4, 5}C = {1, 2, 4, 5} # Returns Trueprint(A.issubset(B)) # Returns False# B is not subset of Aprint(B.issubset(A)) # Returns Falseprint(A.issubset(C)) # Returns Trueprint(C.issubset(B))
Output: 
True
False
False
True
kumar_satyam
surinderdawra388
simmytarika5
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to break line without using <br> tag in HTML / CSS ?

15 Feb, 2019
Use block-level elements to break the line without using <br> tag. There are many ways to break the line without using <br> tag.The used properties are listed below:
white-space: pre; It is used to make elements acts like <pre> tag.
display: block; It sets the display property of elements to block.
Example 1: This example uses white-space to pre to break the line.
<!DOCTYPE html> <html>   <head>     <title>         Line break withoutusing br tag    </title> </head>   <body style = "text-align:center;">       <h1 style = "color:green;" >         GeeksForGeeks     </h1>           <div style="white-space: pre">        GeeksforGeeks        GeeksforGeeks    </div></body>   </html>                    
Output:
Example 2: This example uses display property to break the line.
<!DOCTYPE html> <html>   <head>     <title>         Line break using display property    </title>        <style>        p span {            display: block;        }    </style></head>  <body style = "text-align:center;">       <h1 style = "color:green;" >         GeeksForGeeks     </h1>               <p>        <span>GeeksforGeeks_1</span>        <span>GeeksforGeeks_2</span>    </p></body>   </html>                    
Output:
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to update multiple documents in MongoDB?

You need to use multi:true to update multiple documents. Let us first create a collection with documents −
> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc0b50a6c6dd317adc8")
}
> db.multiUpdateDemo.insertOne({"ClientName":"Carol","ClientAge":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc1b50a6c6dd317adc9")
}
> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":39});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc3b50a6c6dd317adca")
}
> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":41});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc5b50a6c6dd317adcb")
}
> db.multiUpdateDemo.insertOne({"ClientName":"David","ClientAge":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc6b50a6c6dd317adcc")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.multiUpdateDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cda5bc0b50a6c6dd317adc8"),
   "ClientName" : "John",
   "ClientAge" : 29
}
{
   "_id" : ObjectId("5cda5bc1b50a6c6dd317adc9"),
   "ClientName" : "Carol",
   "ClientAge" : 31
}
{
   "_id" : ObjectId("5cda5bc3b50a6c6dd317adca"),
   "ClientName" : "John",
   "ClientAge" : 39
}
{
   "_id" : ObjectId("5cda5bc5b50a6c6dd317adcb"),
   "ClientName" : "John",
   "ClientAge" : 41
}
{
   "_id" : ObjectId("5cda5bc6b50a6c6dd317adcc"),
   "ClientName" : "David",
   "ClientAge" : 35
}
Following is the query to perform multi-update. The ClientName “John” for 3 clients will now have updated age using the below query −
> db.multiUpdateDemo.update({'ClientName': 'John'}, {$set: {'ClientAge': 34}}, {multi: true});
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Let us check the documents once again −
> db.multiUpdateDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cda5bc0b50a6c6dd317adc8"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cda5bc1b50a6c6dd317adc9"),
   "ClientName" : "Carol",
   "ClientAge" : 31
}
{
   "_id" : ObjectId("5cda5bc3b50a6c6dd317adca"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cda5bc5b50a6c6dd317adcb"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cda5bc6b50a6c6dd317adcc"),
   "ClientName" : "David",
   "ClientAge" : 35
}