code-rag-bench/online-tutorials huggingface dataset:
Print colored message with different fonts and sizes in C

29 Oct, 2018
In C/C++ we can use graphics.h header file for creation of programs which uses graphical functions like creating different objects, setting the color of text, printing messages in different fonts and size, changing the background of our output console and much more.Here we will create a program which will print message (“geeks”) in colored form in different font style and size. listed below are some function used :
setcolor(): It will set the cursor color and hence anything written on the output screen will be of the color as per setcolor().function prototype :setcolor(int)
setcolor(int)
settexttyle(): It set the text font style, its orientation(horizontal/ vertical) and size of font.Function prototype :settextstyle(int style, int orientation, int size);
settextstyle(int style, int orientation, int size);
outtextxy() : It will print message passed to it at some certain coordinate (x,y).function prototype :settextstyle(int style, int orientation, int size);
settextstyle(int style, int orientation, int size);
More functions:TextHeight():textheight();TextWidth():textwidth();SetUserCharSize():-setusercharsize(x1,y1,x2,y2);
textheight();
TextWidth():
textwidth();
SetUserCharSize():-
setusercharsize(x1,y1,x2,y2);
Note: Given program will not run on IDE, try it on your compiler
// C program to print// message as colored characters#include<stdio.h>#include<graphics.h>#include<dos.h>  // function for printing// message as colored charactervoid printMsg(){    // auto detection    int gdriver = DETECT,gmode,i;      // initialize graphics mode    initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI");      for (i=3; i<7; i++)    {        // setcolor of cursor        setcolor(i);                  // set text style as        // settextstyle(font, orientation, size)        settextstyle(i,0,i);                  // print text at coordinate x,y;        outtextxy(100,20*i,"Geeks");                  delay(500);    }     delay(2000);}  // driver programint main(){    printMsg();    return 0;}
Output:


This article is contributed by Shivam Pradhan (anuj_charm). 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.
PremDhadkar
C Language
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Central Limit Theorem

29 May, 2021
The definition: 
The sample mean will approximately be normally distributed for large sample sizes, regardless of the distribution from which we are sampling.  
 
Suppose we are sampling from a population with a finite mean and a finite standard-deviation(sigma). Then Mean and standard deviation of the sampling distribution of the sample mean can be given as: Where represents the sampling distribution of the sample mean of size n each, and are the mean and standard deviation of the population respectively. The distribution of the sample tends towards the normal distribution as the sample size increases.Code: Python implementation of the Central Limit Theorem  
python3
import numpyimport matplotlib.pyplot as plt # number of samplenum = [1, 10, 50, 100] # list of sample meansmeans = []  # Generating 1, 10, 30, 100 random numbers from -40 to 40# taking their mean and appending it to list means.for j in num:    # Generating seed so that we can get same result    # every time the loop is run...    numpy.random.seed(1)    x = [numpy.mean(        numpy.random.randint(            -40, 40, j)) for _i in range(1000)]    means.append(x)k = 0 # plotting all the means in one figurefig, ax = plt.subplots(2, 2, figsize =(8, 8))for i in range(0, 2):    for j in range(0, 2):        # Histogram for each x stored in means        ax[i, j].hist(means[k], 10, density = True)        ax[i, j].set_title(label = num[k])        k = k + 1 plt.show()
Output:  
It is evident from the graphs that as we keep on increasing the sample size from 1 to 100 the histogram tends to take the shape of a normal distribution.Rule of thumb: Of course, the term “large” is relative. Roughly, the more “abnormal” the basic distribution, the larger n must be for normal approximations to work well. The rule of thumb is that a sample size n of at least 30 will suffice.Why is this important? The answer to this question is very simple, as we can often use well developed statistical inference procedures that are based on a normal distribution such as 68-95-99.7 rule and many others, even if we are sampling from a population that is not normal, provided we have a large sample size. 
redstormthecoder
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
ML | Monte Carlo Tree Search (MCTS)
Search Algorithms in AI
Supervised and Unsupervised learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Batch Script - DATE and TIME

The date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system.
This command gets the system date.
DATE

@echo off 
echo %DATE%
The current date will be displayed in the command prompt. For example,
Mon 12/28/2015

This command sets or displays the time.
TIME

@echo off 
echo %TIME%
The current system time will be displayed. For example,
22:06:52.87

Following are some implementations which can be used to get the date and time in different formats.
@echo off 
echo/Today is: %year%-%month%-%day% 
goto :EOF 
setlocal ENABLEEXTENSIONS 
set t = 2&if "%date%z" LSS "A" set t = 1 

for /f "skip=1 tokens = 2-4 delims = (-)" %%a in ('echo/^|date') do ( 
   for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( 
      set %%a=%%d&set %%b=%%e&set %%c=%%f)) 
endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF
The above command produces the following output.
Today is: 2015-12-30

 Print
 Add Notes
 Bookmark this page
Circular rotation of an array using deque in C++ - GeeksforGeeks

23 Sep, 2019
Given an array arr[] of integers and another integer D, the task is to perform D circular rotations on the array and print the modified array.
Examples:
Input: Arr[] = {1, 2, 3, 4, 5, 6}, D = 2Output: 5 6 1 2 3 4
Input: Arr[] = {1, 2, 3}, D = 2Output: 2 3 1
Approach:Using Deque in C++, a rotation can be performed deleting the last element from the deque and inserting it at the beginning of the same deque.
Similarly, all the required rotations can be performed and then print the contents of the modified deque to get the required rotated array.
If the number of rotations is more than the size of the deque then just take the mod with N, So, D = D%N.Where D is the number of rotations and N is the size of the deque.
Below is the implementation of the above approach:
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;  // Function to circular rotate// the array by d elementsvoid rotate(deque<int> deq,            int d, int n){    // Push first d elements    // from last to the beginning    for (int i = 0; i < d; i++) {        int val = deq.back();        deq.pop_back();        deq.push_front(val);    }      // Print the rotated array    for (int i = 0; i < n; i++) {        cout << deq[i] << " ";    }    cout << endl;}  // Driver codeint main(){    deque<int> v = { 1, 2, 3, 4, 5, 6, 7 };    int n = v.size();    int d = 5;      rotate(v, d % n, n);}
3 4 5 6 7 1 2

cpp-deque
rotation
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Building Heap from Array
Remove duplicates from sorted array
Count pairs with given sum
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Trapping Rain Water
Difference between tellg and tellp in C++ - GeeksforGeeks

23 Mar, 2021
In this article, we will discuss the functionality of basic_istream<>::tellg and basic_ostream<>::tellp and the difference between them.
tellg(): The function is defined in the istream class, and used with input streams. It returns the position of the current character in the input stream.
Syntax:
pos_type tellg(); 
Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”.
Program 1:
Below is the C++ program to illustrate the use of tellg():
C++
// C++ program to illustrate the// use of tellg()#include <fstream>#include <iostream>using namespace std;  // Driver Codeint main(){    ifstream fin;    char ch;      // Opens the existing file    fin.open("gfg.text");      int pos;    pos = fin.tellg();    cout << pos;      fin >> ch;    pos = fin.tellg();    cout << pos;      fin >> ch;    pos = fin.tellg();    cout << pos;      return 0;}
Input File:
 gfg.text
 
 hello students
Output:
tellp(): The function is defined in the ostream class, and used with output streams. It returns the position of the current character in the output stream where the character can be placed.
Syntax:
pos_type tellp();
Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”.
Program 2:
Below is the C++ program illustrating the use of tellp():
C++
// C++ program illustrating the// use of tellp()#include <fstream>#include <iostream>using namespace std;  // Driver Codeint main(){    ofstream fout;    char ch;      // Opening the already existing file    fout.open("gfg.text", ios::app);    int pos;    pos = fout.tellp();    cout << pos;      fout << "print it";    pos = fin.tellp();    cout << pos;    fout.close();      return 0;}
Input File:
gfg.text

hello students
print it 
Output:
Tabular Difference between tellp() and tellg():
CPP-Library
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Pi(π) in C++ with Examples
Const keyword in C++
Handling the Divide by Zero Exception in C++
Why it is important to write "using namespace std" in C++ program?
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Setting up Sublime Text for C++ Competitive Programming Environment
Deep Learning-Prepare Image for Dataset | by Karthick Nagarajan | Towards Data Science

Whenever we begin a machine learning project, the first thing that we need is a dataset. Dataset will be the pillar of your training model. You can build the dataset either automatically or manually. Here I am going to share about the manual process.
Dataset is the collection of specific data for your ML project needs. The type of data depends on the kind of AI you need to train. Basically, you have two datasets:
Training
Testing
Composition at 90% and 10% respectively
Whenever you are training a custom model the important thing is images. Yes, of course the images play a main role in deep learning. The accuracy of your model will be based on the training images. So, before you train a custom model, you need to plan how to get images? Here, I’m going to share my ideas on the easy way to get images for a dataset.
Yes, we can get images from Google. Using the Download All Images browser extension we can easily get images in a few minutes. You can check out here for more details about this extension! It is available on major browsers. Unfortunately, this extension is not available on the Safari browser.
Chrome
Firefox
Opera
Once you download images using this extension, you will see the downloaded images in a folder with random filenames. We can rename the files or remove the .png file using the below Python script.
chrome.google.com
Remove PNGs from the downloaded image folder.
Rename your image files
Here we have another way to prepare images for the Dataset. We can easily extract images from video files. Detecto gives a simple solution to get images from the video. Refer Detecto for more information.
pip3 install detecto
Using the following code we can extract images from video files.
You can take pictures of objects which you will use to train your model. The important note is to make sure your images are not beyond 800x600. This will help your dataset train much quicker.
I have prepared a video and explained about the above process. Please check out the below video blog.
As an ML noob, I need to figure out the best way to prepare the dataset for training a model. I hope this will be useful. My ultimate idea is to create a Python package for this process. :)
Yes, I will come up with my next article!
Originally published at www.spritle.com
instance initializer block in Java

Instance initializer block works are used to initialize the properties of an object. It is invoked before the constructor is invoked. It is invoked every time an object is created. See the example below −
Live Demo
public class Tester {
   {
      System.out.println("Inside instance initializer block");
   }
   Tester(){
      System.out.println("Inside constructor");
   }
   public static void main(String[] arguments) {
      Tester test = new Tester();
      Tester test1 = new Tester();
   }
}
Inside instance initializer block
Inside constructor
Inside instance initializer block
Inside constructor
Optional ifPresentOrElse() method in Java with examples

30 Jul, 2019
The ifPresentOrElse(Consumer, Runnable) method of java.util.Optional class helps us to perform the specified Consumer action the value of this Optional object. If a value is not present in this Optional, then this method performs the given empty-based Runnable emptyAction, passed as the second parameter
Syntax:
public void ifPresentOrElse(Consumer<T> action,
                            Runnable emptyAction)

Parameters: This method accepts two parameters:
action: which is the action to be performed on this Optional, if a value is present.
emptyAction: which is the empty-based action to be performed, if no value is present.
Return value: This method returns nothing.
Exception: This method throw NullPointerException if a value is present and the given action is null, or no value is present and the given empty-based action is null.
Below programs illustrate ifPresentOrElse() method:
Note: As this method was added in Java 9, the programs need JDK 9 to execute.
Program 1:
// Java program to demonstrate// Optional.ifPresentOrElse() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print value        System.out.println("Optional: "                           + op);          // apply ifPresentOrElse        op.ifPresentOrElse(            (value)                -> { System.out.println(                         "Value is present, its: "                         + value); },            ()                -> { System.out.println(                         "Value is empty"); });    }}
Output:
Optional: Optional[9455]
Value is present, its: 9455

Program 2:
// Java program to demonstrate// Optional.ifPresentOrElse method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);          try {              // apply ifPresentOrElse            op.ifPresentOrElse(                (value)                    -> { System.out.println(                             "Value is present, its: "                             + value); },                ()                    -> { System.out.println(                             "Value is empty"); });        }        catch (Exception e) {            System.out.println(e);        }    }}
Output:
Optional: Optional.empty
Value is empty

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
Collections in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
Constructors in Java
Multithreading in Java
scriptreplay command in Linux with Examples

17 Apr, 2019
scriptreplay command is used to replay a typescript/terminal_activity stored in the log file that was recorded by the script command. With the help of timing information, the log files are played and the outputs are generated in the terminal with the same speed the original script was recorded. The replay does not run the command again but it only displays the same information once again, thus scriptreplay must be run on the same type of terminal the typescript was recorded in order to work properly.By default, the replay displays the information stored in typescript file if no other filename is specified.
Syntax:
scriptreplay [-t] timingfile [typescript] [divisor]
Example: To replay a recorded script with script filename as geeksforgeeks and timing output file as time_log.
Options:
-t, –timing: This option is used for script timing output file.Example: To replay the script timing file, time_log.
Example: To replay the script timing file, time_log.
-s, –typescript: This option is used for script terminal session output file.Example: To replay the script namely geeksforgeeks using -s option.
Example: To replay the script namely geeksforgeeks using -s option.
-d, –divisor: This option is used when we want to speed up or slow down execution with time divisor. The argument here is a floating point number.Example 1: To replay the script, geeksforgeeks with 2x speed we will use 2 as a divisor.Input:The replay speed will increase by twice.Output:Example 2: To replay the script, geeksforgeeks with 2 times slower we will use 0.2 as a divisor.
Example 1: To replay the script, geeksforgeeks with 2x speed we will use 2 as a divisor.
Input:
The replay speed will increase by twice.
Output:
Example 2: To replay the script, geeksforgeeks with 2 times slower we will use 0.2 as a divisor.
-V, –version: Output version information and exit.
-h, –help: Display this help and exit.
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
Python Program to convert a list into matrix with size of each row increasing by a number

24 Jan, 2021
Given a list and a number N, the task here is to write a python program to convert it to matrix where each row has N elements more than previous row elements from list.
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 3
Output : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Explanation : Each row has 3 elements more than previous row.
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 4
Output : [[4, 6, 8, 1], [4, 6, 8, 1, 2, 9, 0, 10], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Explanation : Each row has 4 elements more than previous row.
Method 1 : Using loop and slicing
In this, we perform task of getting chunks using slicing, and conversion of list into Matrix is done using loop.
Program:
Python3
# initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]  # printing original listprint("The original list is : " + str(test_list))  # initializing NN = 3  res = []for idx in range(0, len(test_list) // N):      # getting incremented chunks    res.append(test_list[0: (idx + 1) * N])  # printing resultprint("Constructed Chunk Matrix : " + str(res))
Output:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Method 2 : Using list comprehension and list slicing 
In this, we perform task of setting values using list comprehension as a shorthand. Rest all the operations are done similar to above method.
Program:
Python3
# initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]  # printing original listprint("The original list is : " + str(test_list))  # initializing NN = 3  # getting incremented chunks# using list comprehension as shorthandres = [test_list[0: (idx + 1) * N] for idx in range(0, len(test_list) // N)]  # printing resultprint("Constructed Chunk Matrix : " + str(res))
Output:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Python list-programs
Python
Python Programs
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Serializable Interface in Java

24 Nov, 2020
The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods. Classes implement it if they want their instances to be Serialized or Deserialized. Serialization is a mechanism of converting the state of an object into a byte stream. Serialization is done using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is done using ObjectInputStream. Thus it can be used to make an eligible for saving its state into a file. 
Declaration
public interface Serializable

Example: The below example shows a class that implements Serializable Interface.
Java
// Java Program to demonstrate a class// implementing Serializable interface  import java.io.Serializable;  public static class Student implements Serializable {    public String name = null;    public String dept = null;    public int id = 0;}
Here, you can see that Student class implements Serializable, but does not have any methods to implement from Serializable.
Example: Below example code explains Serializing and Deserializing an object.
Java
// Java program to illustrate Serializable interfaceimport java.io.*;  // By implementing Serializable interface// we make sure that state of instances of class A// can be saved in a file.class A implements Serializable {    int i;    String s;      // A class constructor    public A(int i, String s)    {        this.i = i;        this.s = s;    }}  public class Test {    public static void main(String[] args)        throws IOException, ClassNotFoundException    {        A a = new A(20, "GeeksForGeeks");          // Serializing 'a'        FileOutputStream fos            = new FileOutputStream("xyz.txt");        ObjectOutputStream oos            = new ObjectOutputStream(fos);        oos.writeObject(a);          // De-serializing 'a'        FileInputStream fis            = new FileInputStream("xyz.txt");        ObjectInputStream ois = new ObjectInputStream(fis);        A b = (A)ois.readObject(); // down-casting object          System.out.println(b.i + " " + b.s);          // closing streams        oos.close();        ois.close();    }}
Output:
20 GeeksForGeeks

Must Read: Serialization and Deserialization in Java
Java-Collections
Java-I/O
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <frame> noresize Attribute

30 Sep, 2019
The HTML <frame> noresize attribute is used to specify that the frame element can not be resize by the user. This type of attribute is used to looks at the size of the frame element.
Syntax:
<frame noresize="noresize">
Attribute Values:
noresize: It defines the frame element that can not be resize by the user.
Note: The <frame> tag is not supported by HTML 5.
Example:
<!DOCTYPE html> <html>   <head>     <title>HTML frame noresize Attribute</title> </head>   <frameset cols="30%, 40%, 30%">     <frame name="top"        src="attr1.png" noresize="noresize"/>     <frame name="main"        src="gradient3.png" marginwidth="30" />     <frame name="bottom" marginwidth="30"        src="col_last.png" marginwidth="40" /> </frameset>   </html>                    
Output:
Supported Browsers: The browsers supported by HTML <frame> noresize Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to change the column names in R within aggregate function?

The column names in an R data frame are an important part of the data because by reading the column names any viewer is likely to understand the theoretical background behind it. If that name is not appropriate then we might want to change it. While using the aggregate function to calculate mean or any other statistical summary, it is possible to change that name with another name by defining the new name with list.
Consider the below data frame −
set.seed(1)
x1<-rnorm(100)
x2<-rep(c(LETTERS[1:25]),times=4)
df<-data.frame(x1,x2)
head(df,20)
    x1       x2
1  -0.62645381 A
2   0.18364332 B
3  -0.83562861 C
4   1.59528080 D
5   0.32950777 E
6  -0.82046838 F
7   0.48742905 G
8   0.73832471 H
9   0.57578135 I
10 -0.30538839 J
11  1.51178117 K
12  0.38984324 L
13 -0.62124058 M
14 -2.21469989 N
15  1.12493092 O
16 -0.04493361 P
17 -0.01619026 Q
18  0.94383621 R
19  0.82122120 S
20  0.59390132 T
tail(df,20)
      x1      x2
81  -0.5686687 F
82  -0.1351786 G
83   1.1780870 H
84  -1.5235668 I
85   0.5939462 J
86   0.3329504 K
87   1.0630998 L
88  -0.3041839 M
89   0.3700188 N
90   0.2670988 O
91  -0.5425200 P
92   1.2078678 Q
93   1.1604026 R
94   0.7002136 S
95   1.5868335 T
96   0.5584864 U
97  -1.2765922 V
98  -0.5732654 W
99  -1.2246126 X
100 -0.4734006 Y
Changing the name of columns inside aggregate function with mean −
new_df <- aggregate(list(One=df$x1),list(Two=df$x2),mean)
head(new_df)
  Two One
1 A  0.001742391
2 B -0.256867612
3 C -0.491038988
4 D  0.015527244
5 E  0.397738022
6 F  0.487485583
new_df
 Two One
1  A  0.001742391
2  B -0.256867612
3  C -0.491038988
4  D  0.015527244
5  E  0.397738022
6  F  0.487485583
7  G -0.029439692
8  H  0.314987172
9  I -0.107967715
10 J -0.305889090
11 K  0.957838684
12 L  0.254853279
13 M -0.073749635
14 N -0.179163387
15 O  0.352983062
16 P -0.140796234
17 Q -0.216660692
18 R  1.066689266
19 S  0.557837845
20 T  0.916147688
21 U  0.311369542
22 V -0.209955094
23 W  0.220139712
24 X -1.065102039
25 Y -0.056525141
Application Layer - GeeksforGeeks

09 Oct, 2019
 The Layer 1 (Physical Layer) PDU is the bit or, more generally, symbol 
 The Layer 2 (Data Link Layer) PDU is the frame.
 The Layer 3 (Network Layer) PDU is the packet.
 The Layer 4 (Transport Layer) PDU is the segment
              for TCP or the datagram for UDP.
 The Layer 5 (Application Layer) PDU is the data or message.

m1: Send an email from a mail client to a mail server
m2: Download an email from mailbox server to a mail client
m3: Checking email in a web browser
The web browser requests a webpage using HTTP.The web browser establishes a TCP connection with the web server.The web server sends the requested webpage using HTTP.The web browser resolves the domain name using DNS.
The web browser requests a webpage using HTTP.
The web browser establishes a TCP connection with the web server.
The web server sends the requested webpage using HTTP.
The web browser resolves the domain name using DNS.
(i)  HTTP
(ii) FTP
(iii) TCP
(iv) POP3 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is "network ID" and "host ID" in IP Addresses?
Create a dictionary with list comprehension in Python
What is Transmission Control Protocol (TCP)?
Python - Update values of a list of dictionaries
How to Calculate Number of Host in a Subnet?
Bash Scripting - How to check If File Exists
How to Get Cell Value from Pandas DataFrame?
How to Calculate Correlation Between Two Columns in Pandas?
DateTime.ToFileTimeUtc() Method in C# - GeeksforGeeks

10 Feb, 2019
This method is used to convert the value of the current DateTime object to a Windows file time.
Syntax: public long ToFileTimeUtc ();
Return Value: This method returns the value of the current DateTime object expressed as a Windows file time.
Exception: This method will give ArgumentOutOfRangeException if the resulting file time would represent a date and time before 12:00 midnight January 1, 1601 C.E. UTC.
Below programs illustrate the use of DateTime.ToFileTimeUtc() Method:
Example 1:
// C# program to demonstrate the// DateTime.ToFileTimeUtc()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTime            DateTime date = new DateTime(2011, 1,                                    1, 4, 0, 15);              // converting current DateTime object            // to a Windows file time.            // using ToFileTimeUtc() method;            long value = date.ToFileTimeUtc();              // Display the TimeSpan            Console.WriteLine("Windows file time(UTC) "+                                       "is {0}", value);        }          catch (ArgumentOutOfRangeException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Windows file time(UTC) is 129383280150000000

Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// DateTime.ToFileTimeUtc()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTime            DateTime date = new DateTime(1600, 1,                                    1, 4, 0, 15);              // converting current DateTime             // object to a Windows file time.            // using ToFileTimeUtc() method;            long value = date.ToFileTimeUtc();              // Display the TimeSpan            Console.WriteLine("Windows file time(UTC) is "+                                             "{0}", value);        }          catch (ArgumentOutOfRangeException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.ArgumentOutOfRangeException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tofiletimeutc?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
Partial Classes in C#
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Lambda Expressions in C#
Linked List Implementation in C#
Convert String to Character Array in C#
How to detect if JavaScript is disabled in a browser?

To detect if JavaScript is disabled in a web browser, use the <noscript> tag. The HTML <noscript> tag is used to handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text message.
Here’s an example,
<!DOCTYPE html>
<html>
   <head>
      <title>HTML noscript Tag</title>
   </head>

   <body>
      <script>
         <!--
            document.write("Hello JavaScript!")
         -->
      </script>
     
      <noscript>
         Your browser does not support JavaScript!
      </noscript>
   </body>
</html>
Python 3 - Number fabs() Method

The fabs() method returns the absolute value of x. Although similar to the abs() function, there are differences between the two functions. They are −
abs() is a built in function whereas fabs() is defined in math module.
abs() is a built in function whereas fabs() is defined in math module.
fabs() function works only on float and integer whereas abs() works with complex number also.
fabs() function works only on float and integer whereas abs() works with complex number also.
Following is the syntax for the fabs() method −
import math

math.fabs( x )

Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric value.
This method returns the absolute value of x.
The following example shows the usage of the fabs() method.
#!/usr/bin/python3
import math   # This will import math module

print ("math.fabs(-45.17) : ", math.fabs(-45.17))
print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))
When we run the above program, it produces the following result −
math.fabs(-45.17) :  45.17
math.fabs(100) :  100.0
math.fabs(100.72) :  100.72
math.fabs(math.pi) :  3.141592653589793


    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
How to make the web page height to fit screen height with HTML?

Many ways are available to make the web page height to fit the screen height −
Give relative heights −
html, body {
   height: 100%;
}
You can also give fixed positioning −
#main
{
   position:fixed;
   top:0px;
   bottom:0px;
   left:0px;
   right:0px;
}
You can also use Viewport height to fulfill your purpose −
height: 100vh;
How to get the size of a string in Python?

Python has a method called len() that gives us the length of any composite object. To get the length of a string, just pass the string to the len() call. 
print(len('Hello World!'))
12
If you want the size of the string in bytes, you can use the getsizeof() method from the sys module. 
from sys import getsizeof
getsizeof('Hello World!')
33
You can read more about it at sys.getsizeof()
How to trim down non printable characters from a string in Python?

If you have only ASCII characters and want to remove the non-printable characters, the easiest way is to filter out those characters using string.printable. For example,
>>> import string
>>> filter(lambda x: x in string.printable, '\x01string')
string
The 0x01 was not printed as it is not a printable character. If you need to support Unicode as well, then you need to use the Unicode data module and regexes to remove these characters.
import sys, unicodedata, re
# Get all unicode characters
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
# Get all non printable characters
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')
# Create regex of above characters
control_char_re = re.compile('[%s]' % re.escape(control_chars))
# Substitute these characters by empty string in the original string.
def remove_control_chars(s):
    return control_char_re.sub('', s)
print (remove_control_chars('\x00\x01String'))
This will give the output:
String
How to get the value of the rel attribute of a link in JavaScript?

To get the value of the rel attribute of a link in JavaScript, use the rel property. The rel is used to set the following status of a page i.e. follow and nofollow.
You can try to run the following code to get the value of the rel attribute of a link.
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p><a id="anchorid" rel="nofollow" href="https://www.qries.com/">Qries</a></p>
      <script>
         var myVal = document.getElementById("anchorid").rel;
         document.write("Value of rel attribute: "+myVal);
      </script>
   </body>
</html>
Converting array of Numbers to cumulative sum array in JavaScript

We have an array of numbers like this −
const arr = [1, 1, 5, 2, -4, 6, 10];
We are required to write a function that returns a new array, of the same size but with each
element being the sum of all elements until that point.
Therefore, the output should look like −
const output = [1, 2, 7, 9, 5, 11, 21];
Therefore, let’s write the function partialSum(),
The full code for this function will be −
const arr = [1, 1, 5, 2, -4, 6, 10];
const partialSum = (arr) => {
   const output = [];
   arr.forEach((num, index) => {

      if(index === 0){
         output[index] = num;
      }else{
         output[index] = num + output[index - 1];
      }
   });
   return output;
};
console.log(partialSum(arr));
Here, we iterated over the array and kept assigning the elements of output array a new value
every time, the value being the sum of current number and its predecessor.
The output of the code in the console will be −
[
   1, 2, 7, 9,
   5, 11, 21
]
Print all permutations of a given string

Printing all permutations of a given string is an example of backtracking problem. We will reduce the size of the substring to solve the sub-problems, then again backtrack to get another permutation from that section.
For an example, if the string is ABC, the all permutations will be ABC, ACB, BAC, BCA, CAB, CBA.
The complexity of this algorithm is O(n!). It is a huge complexity. When the string size increases, it takes a longer time to finish the task.
Input:
A string “ABC”
Output:
All permutations of ABC is:
ABC
ACB
BAC
BCA
CBA
CAB
stringPermutation(str, left, right)
Input: The string and left and right index of characters.
Output: Print all permutations of the string.
Begin
   if left = right, then
      display str
   else
      for i := left to right, do
         swap str[left] and str[i]
         stringPermutation(str, left+1, right)
         swap str[left] and str[i]             //for backtrack
      done
End
#include<iostream>
using namespace std;

void stringPermutation(string str, int left, int right) {
   if(left == right)
      cout << str << endl;
   else {
      for(int i = left; i<= right; i++) {
         swap(str[left], str[i]);
         stringPermutation(str, left + 1, right);
         swap(str[left], str[i]); //swap back for backtracking
      }
   }
}

int main() {
   string str = "ABC";
   cout << "All permutations of " << str << " is: " <<endl<<endl;
   stringPermutation(str, 0, str.size()-1);
}

All permutations of ABC is:
ABC
ACB
BAC
BCA
CBA
CAB
Get filename from path without extension using Python - GeeksforGeeks

26 Mar, 2021
Getting a filename from Python using a path is a complex process not because of the regex we need to use to separate the filename from the path but because of the different types of separators used in file paths in different operating systems. For example, UNIX-based systems like Linux or Mac Os uses “/”  (Forward Slash) as separators of the directory while Windows uses “\” (Back Slash)  for separating the directories inside the path. So to avoid all these problems we would use a built-in package in python ntpath and use that to first extract the basename (the name that contains the filename with the extension). Then we could use simple python slicing to find the filename without the extension.  
Firstly we would use the ntpath module. Secondly, we would extract the base name of the file from the path and append it to a separate array. The code for the same goes like this.
Python3
# import moduleimport ntpath  # used path style of both the UNIX# and Windows os to show it works on both.paths = [    "E:\Programming Source Codes\Python\sample.py",    "D:\home\Riot Games\VALORANT\live\VALORANT.exe"]  # empty array to store file basenamesfilenames = []  for path in paths:    # used basename method to get the filename    filenames.append(ntpath.basename(path))
Then we would take the array generated and find the last occurrence of the “.” character in the string. Remember finding only the instance of “.”  instead of the last occurrence may create problems if the name of the file itself contains “.”. We would find that index using rfind and then finally slice the part of the string before the index to get the filename. The code looks something like this. Again you can store those filenames in a list and use them elsewhere but here we decided to print them to the screen simply.
Python3
# get names from the listfor name in filenames:        # finding the index where     # the last "." occurs    k = name.rfind(".")          # printing the filename    print(name[:k])
Below is the complete program:
Python3
# import moduleimport ntpath  # used path style of both the UNIX# and Windows os to show it works on both.paths = [    "E:\Programming Source Codes\Python\sample.py",    "D:\home\Riot Games\VALORANT\live\VALORANT.exe"]  # empty array to store file basenamesfilenames = []  for path in paths:        # used basename method to get the filename    filenames.append(ntpath.basename(path))  # get names from the listfor name in filenames:        # finding the index where     # the last "." occurs    k = name.rfind(".")          # printing the filename    print(name[:k])
Output:
Picked
python-file-handling
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
Throwable getMessage() method in Java with Examples - GeeksforGeeks

06 Feb, 2019
The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value.
Syntax:
public String getMessage()
Return Value: This method returns the detailed message of this Throwable instance.
Below programs demonstrate the getMessage() method of java.lang.Throwable Class
Example 1:
// Java program to demonstrate// the getMessage() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {              // divide the numbers            divide(2, 0);        }          catch (ArithmeticException e) {              System.out.println("Message String = "                               + e.getMessage());        }    }      // method which divide two numbers    public static void divide(int a, int b)        throws ArithmeticException    {          int c = a / b;          System.out.println("Result:" + c);    }}
Message String = / by zero

Example 2:
// Java program to demonstrate// the getMessage() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {              test();        }          catch (Throwable e) {              System.out.println("Message of Exception : "                               + e.getMessage());        }    }      // method which throws UnsupportedOperationException    public static void test()        throws UnsupportedOperationException    {          throw new UnsupportedOperationException();    }}
Message of Exception : null

References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getMessage()
Java-Exception Handling
Java-Exceptions
Java-Functions
Java-lang package
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Java 11 - Var in Lambda

Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.
(@NonNull var value1, @Nullable var value2) -> value1 + value2

Consider the following example −
ApiTester.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@interface NonNull {}

public class APITester {
   public static void main(String[] args) {		
      List<String> tutorialsList = Arrays.asList("Java", "HTML");

      String tutorials = tutorialsList.stream()
         .map((@NonNull var tutorial) -> tutorial.toUpperCase())
         .collect(Collectors.joining(", "));

      System.out.println(tutorials);
   }
}
Java
HTML

There are certain limitations on using var in lambda expressions.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
(var v1, v2) -> v1 + v2

var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
(var v1, String v2) -> v1 + v2

var parameters can only be used with parenthesis. Following will throw compilation error.
var parameters can only be used with parenthesis. Following will throw compilation error.
var v1 -> v1.toLowerCase()


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page