code-rag-bench/online-tutorials huggingface dataset:
\intercal - Tex Command

\intercal - Used to draw intercal symbol.
{ \intercal }
\intercal command draws intercal symbol.

intercal

⊺



intercal

⊺


intercal

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Python 3 - List pop() Method

The pop() method removes and returns last object or obj from the list.
Following is the syntax for pop() method −
list.pop(obj = list[-1])

obj − This is an optional parameter, index of the object to be removed from the list.
This method returns the removed object from the list.
The following example shows the usage of pop() method.
#!/usr/bin/python3

list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.pop()
print ("list now : ", list1)

list1.pop(1)
print ("list now : ", list1)
When we run above program, it produces the following result −
list now :  ['physics', 'Biology', 'chemistry']
list now :  ['physics', 'chemistry']


    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
What is Calloc in C language?

The C library memory allocation function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it.
The difference in malloc and calloc is that malloc does not set the memory to zero, whereas, calloc sets the allocated memory to zero.
Memory can be allocated in two ways as explained below −
Once memory is allocated at compile time, it cannot be changed during execution. There will be a problem of either insufficiency or else wastage of memory.
The solution is to create memory dynamically i.e. as per the requirement of the user during execution of program.
The standard library functions which are used for dynamic memory management are as follows −
malloc ( )
calloc ( )
realloc ( )
free ( )
This function is used for allocating continuous blocks of memory at run time.
This function is used for allocating continuous blocks of memory at run time.
This is specially designed for arrays.
This is specially designed for arrays.
It returns a void pointer, which points to the base address of the allocated memory.
It returns a void pointer, which points to the base address of the allocated memory.
The syntax for calloc() function is given below −
void *calloc ( numbers of elements, size in bytes)
The following example shows the usage of calloc() function.
int *ptr;
ptr = (int * ) calloc (500,2);
Here, 500 blocks of memory each of size 2 bytes will be allocated continuously. Total memory allocated = 1000 bytes.
int *ptr;
ptr = (int * ) calloc (n, sizeof (int));
Given below is a C Program to compute sum of even numbers and odd numbers in a set of elements using dynamic memory allocation functions Calloc.
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables, pointers//
   int i,n;
   int *p;
   int even=0,odd=0;
   //Declaring base address p using Calloc//
   p = (int * ) calloc (n, sizeof (int));
   //Reading number of elements//
   printf("Enter the number of elements : ");
   scanf("%d",&n);
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Storing elements into location using for loop//
   printf("The elements are : \n");
   for(i=0;i<n;i++){
      scanf("%d",p+i);
   }
   for(i=0;i<n;i++){
      if(*(p+i)%2==0){
         even=even+*(p+i);
      } else {
         odd=odd+*(p+i);
      }
   }
   printf("The sum of even numbers is : %d\n",even);
   printf("The sum of odd numbers is : %d\n",odd);
}
When the above program is executed, it produces the following result −
Enter the number of elements : 4
The elements are :
12
56
23
10
The sum of even numbers is : 78
The sum of odd numbers is : 23
HTML | default Attribute - GeeksforGeeks

03 Dec, 2021
The HTML default Attribute is a Boolean attribute. This attribute is used to specify that the track will be enabled if the user’s preferences do not indicate that another track would be more appropriate. Note: With a default attribute, there must not be more than one track element per media element.Syntax:  
<track src="subtitles_en.vtt" default>
Applicable:  
<track>
Example:  
html
<html> <head>    <style>        body {            text-align: center;        }                 h1 {            color: green;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>    HTML default Attribute</h2>     <video width="100"           height="100"           controls>         <track src="https://write.geeksforgeeks.org/wp-content/uploads/11.mp4"               kind="subtitles"               srclang="en"               label="English"               default>             <source id="myTrack"                    src="https://write.geeksforgeeks.org/wp-content/uploads/11.mp4"                    type="video/mp4">     </video></body> </html>
Output :  
Supported Browsers: The browsers supported by HTML default Attribute are listed below:  
Google Chrome 18.0
Internet Explorer 10.0
Firefox 31.0
Apple Safari 6.0
Opera 15.0
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Python - Convert TSV to CSV file - GeeksforGeeks

05 Nov, 2021
In this article, we will see how to Convert TSV Files to CSV using Python. 
TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\t”) with comma(“,”) as data in CSV file is comma-separated.  
Example:
Input File:
Python3
# Python program to convert .tsv file to .csv file# importing re libraryimport re  # reading given tsv filewith open("Olympic.tsv", 'r') as myfile:    with open("Olympic.csv", 'w') as csv_file:    for line in myfile:              # Replace every tab with comma      fileContent = re.sub("\t", ",", line)              # Writing into csv file      csv_file.write(fileContent)  # outputprint("Successfully made csv file")
Output:
Successfully made csv file
The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False.
Example:
Input File:
Python3
# Python program to convert .tsv file to .csv file# importing pandas libraryimport pandas as pd   tsv_file='GfG.tsv'  # readinag given tsv filecsv_table=pd.read_table(tsv_file,sep='\t')  # converting tsv file into csvcsv_table.to_csv('GfG.csv',index=False)  # outputprint("Successfully made csv file")
Output:
Successfully made csv file
Output File:
Picked
Python-TSV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
HTML small Tag - GeeksforGeeks

17 Mar, 2022
The <small> tag in HTML is used to set small font size.Syntax:  
<small> Contents... </small>
Example 1:  
HTML
<html>         <body>            <h1>GeeksforGeeks</h1>            <h2><small> Tag</h2>                         <!-- html small tag is used here -->            <small>Welcome to GeeksforGeeks!</small>                      </body>         </html>
Output:  
Example 2: Use CSS property to set the font size smaller.  
HTML
<!DOCTYPE html><html>    <head>        <title>small Tag</title>        <style>            body {                text-align:center;            }            h1 {                color:green;            }            .gfg {                font-size:smaller;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>font-size: smaller;</h2>        <div class = "gfg">Welcome to GeeksforGeeks!</div>    </body></html>                   
Output:  
Supported Browsers:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
How Base64 encoding and decoding is done in node.js ? - GeeksforGeeks

25 Jun, 2020
Base64 encoding and decoding can be done in Node.js using the Buffer object.
Encoding the original string to base64: The Buffer class in Node.js can be used to convert a string to a series of bytes. This can be done using the Buffer.from() method that accepts the string to be converted and the current encoding of the string. This encoding can be specified as “utf8”.
The converted bytes can then be returned as a base64 using the toString() method. This method accepts a parameter that specifies the encoding needed during conversion. In this case, “base64” is specified as the encoding to be used. Thus, this method converts any string to the base64 format.
Syntax:
// Create buffer object, specifying utf8 as encoding
let bufferObj = Buffer.from(originalString, "utf8");

// Encode the Buffer as a base64 string
let base64String = bufferObj.toString("base64");

Example:
// The original utf8 stringlet originalString = "GeeksforGeeks";  // Create buffer object, specifying utf8 as encodinglet bufferObj = Buffer.from(originalString, "utf8");  // Encode the Buffer as a base64 stringlet base64String = bufferObj.toString("base64");  console.log("The encoded base64 string is:", base64String);
Output:
The encoded base64 string is: R2Vla3Nmb3JHZWVrcw==
Decoding base64 to original string: The Buffer can also be used to convert the base64 string back to utf8 encoding. The Buffer.from() method is again used to convert the base64 string back to bytes, however, this time specifying the current encoding as “base64”.
The converted bytes can then be returned as the original utf8 string using the toString() method. In this case, “utf8” is specified as the encoding to be used. Thus, this method converts the base64 to its original utf9 format.
Syntax:
// Create a buffer from the string
let bufferObj = Buffer.from(base64string, "base64");

// Encode the Buffer as a utf8 string
let decodedString = bufferObj.toString("utf8");
Example:
// The base64 encoded input stringlet base64string = "R2Vla3Nmb3JHZWVrcw==";  // Create a buffer from the stringlet bufferObj = Buffer.from(base64string, "base64");  // Encode the Buffer as a utf8 stringlet decodedString = bufferObj.toString("utf8");  console.log("The decoded string:", decodedString);
Output:
The decoded string: GeeksforGeeks
Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Express.js res.redirect() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Python program to convert Set into Tuple and Tuple into Set - GeeksforGeeks

26 Nov, 2020
Let’s see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type().
tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.
set(): set method is to convert other type values to set this method is also accepted other type values as an argument and return a set type value.
type(): type method helps the programmer to check the data type of value. This method accepts a value as an argument and it returns type of the value.
Example:
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
Explanation: converting Set to tuple

Input: ('x', 'y', 'z')
Output: {'z', 'x', 'y'}
Explanation: Converting tuple to set

Example 1: convert set into tuple.
Python
#   program to convert set to tuple# create sets = {'a', 'b', 'c', 'd', 'e'}  # print setprint(type(s), " ", s)  # call tuple() method # this method convert set to tuplet = tuple(s)  # print tupleprint(type(t), " ", t)
Output:
<class 'set'>   {'a', 'c', 'b', 'e', 'd'}
<class 'tuple'>   ('a', 'c', 'b', 'e', 'd')

Example 2: tuple into the set.
Python
#program to convert tuple into set  # create tuplet = ('x', 'y', 'z')  # print tupleprint(type(t), "  ", t)  # call set() methods = set(t)  # print setprint(type(s), "  ", s)
Output:
<class 'tuple'>    ('x', 'y', 'z')
<class 'set'>    {'z', 'x', 'y'}

Python set-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Java Program to Find the Volume and Surface Area of Sphere

26 Nov, 2020
A sphere is a geometrical object in 3D space that is the surface of a ball. The sphere is defined mathematically as the set of points that are all at the same distance of radius from a given point in a 3D space.
Example:
Input:     radius = 5
Output:    Surface Area ≈ 314.16
           Volume ≈ 523.6

Input :    radius = 3
Output:    Surface Area ≈ 113.1
           Volume ≈ 113.1
Surface area of  a sphere = 4*3.14*(r*r)
Volume of a sphere = (4/3)*3.14*(r*r*r)
Algorithm
Initializing value of r as 5.0, surface area as 0.0,volume as 0.0Calculating surface area and volume of a sphere using the below formulasSurface area=4*3.14(r*r)Volume=(4/3)3.14(r*r*r)Display surface area and volume
Initializing value of r as 5.0, surface area as 0.0,volume as 0.0
Calculating surface area and volume of a sphere using the below formulas
Surface area=4*3.14(r*r)
Volume=(4/3)3.14(r*r*r)
Display surface area and volume
Implementation:
Java
// Java Program to Find the Volume and Surface Area of// Sphereclass surfaceareaandvolume {    public static void main(String[] args)    {        double r = 5.0, surfacearea = 0.0, volume = 0.0;        surfacearea = 4 * 3.14 * (r * r);        volume = ((double)4 / 3) * 3.14 * (r * r * r);                System.out.println("surfacearea of sphere ="                           + surfacearea);                System.out.println("volume of sphere =" + volume);    }}
surfacearea of sphere =314.0
volume of sphere =523.3333333333334
Time Complexity: O(1)
Space Complexity: O(1)
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Send email to a list of emails from a spreadsheet

10 May, 2020
Nowadays working with Google forms is quite popular. It is used to mass gather information easily. Email addresses are one of the most common piece of information asked. It is stored in a spreadsheet. In this article we shall see how to send an email to all the email addresses present in a spreadsheet.
Prerequisite knowledge:
Loading Excel spreadsheet as pandas DataFrameSend mail from your Gmail account using Python
Loading Excel spreadsheet as pandas DataFrame
Send mail from your Gmail account using Python
Procedure:
Step 1: Read the spreadsheet using the pandas library. The structure of the spreadsheet used here is :
Step 2: Extablish connection with your gmail account using smtplib library.
Step 3: Extract the names and email addresses from the spreadsheet.
Step 4: Run a loop and for every record send an email.
Step 5: Close the smtp server.
The Python implementation is:
# Python code to send email to a list of# emails from a spreadsheet  # import the required librariesimport pandas as pdimport smtplib  # change these as per useyour_email = "XYZ@gmail.com"your_password = "XYZ"  # establishing connection with gmailserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)server.ehlo()server.login(your_email, your_password)  # reading the spreadsheetemail_list = pd.read_excel('C:/Users/user/Desktop/gfg.xlsx')  # getting the names and the emailsnames = email_list['NAME']emails = email_list['EMAIL']  # iterate through the recordsfor i in range(len(emails)):      # for every record get the name and the email addresses    name = names[i]    email = emails[i]      # the message to be emailed    message = "Hello " + name      # sending the email    server.sendmail(your_email, [email], message)  # close the smtp serverserver.close()
Python file-handling-programs
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 7

28 Jun, 2021
typedef struct node {  int value;  struct node *next;}Node;   Node *move_to_front(Node *head) {  Node *p, *q;  if ((head == NULL: || (head->next == NULL))     return head;  q = NULL; p = head;  while (p-> next !=NULL)   {    q = p;    p = p->next;  }  _______________________________  return head;}
(A) q = NULL; p->next = head; head = p;(B) q->next = NULL; head = p; p->next = head;(C) head = p; p->next = q; q->next = NULL;(D) q->next = NULL; p->next = head; head = p;Answer: (D)Explanation: See question 1 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-24/Quiz of this Question
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | a += b is not always a = a + b

23 Nov, 2021
In python a += b doesn’t always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables.
So first, you need to know what happens behinds the scene. 
Creating New Variable:
Python3
a = 10print(" id of a : ", id(10) ," Value : ", a  )
Output :
id of a :  11094592  Value :  10
Here in the above example, value 10 gets stored in memory and its reference gets assigned to a. 
Modifying The Variable:
Python3
a = 10  # Assigning value to variable creats new objectprint(" id of a : ", id(a) ," Value : ", a  ) a = a + 10 # Modifying value of variable creats new objectprint(" id of a : ", id(a) ," Value : ", a  )   a += 10 # Modifying value of variable creats new objectprint(" id of a : ", id(a) ," Value : ", a  )
Output : 
id of a :  11094592  Value :  10
id of a :  11094912  Value :  20
id of a :  11095232  Value :  30
As whenever we create or modify int, float, char, string they create new objects and assign their newly created reference to their respective variables.
But the same behavior is not seen in the list
Python3
a = [0, 1] # stores this array in memory and assign its reference to aprint("id of a: ",id(a) , "Value : ", a ) a = a + [2, 3] # this will also behave same store data in memory and assign ref. to variableprint("id of a: ",id(a) , "Value : ", a ) a += [4, 5]print("id of a: ",id(a) , "Value : ", a ) #But now this will now create new ref. instead this will modify the current object so# all the other variable pointing to a will also gets changes
 Output: 
id of a:  140266311673864 Value :  [0, 1]
id of a:  140266311673608 Value :  [0, 1, 2, 3]
id of a:  140266311673608 Value :  [0, 1, 2, 3, 4, 5]  
At this point you can see the reason why a = a + b some times different from a += b.
Consider these examples for list manipulation: Example 1: 
Python3
list1 = [5, 4, 3, 2, 1]list2 = list1list1 += [1, 2, 3, 4] # modifying value in current reference print(list1)print(list2) # as on line 4 it modify the value without creating new object             # variable list2 which is pointing to list1 gets changes
Output: 
[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]
Example 2 
Python3
list1 = [5, 4, 3, 2, 1]list2 = list1list1 = list1 + [1, 2, 3, 4] # Contents of list1 are same as above# program, but contents of list2 are# different.print(list1)print(list2)
Output: 
[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]
 
expression list1 += [1, 2, 3, 4] modifies the list in-place, which means it extends the list such that “list1” and “list2” still have the reference to the same list.
expression list1 = list1 + [1, 2, 3, 4] creates a new list and changes “list1” reference to that new list and “list2” still refer to the old list.
aayushibhatia2
parthtagalpallewar123
python-list
Python-Operators
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PYGLET – On Mouse Scroll Event

30 Jul, 2021
In this article we will see how we can trigger on mouse scroll event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen).This event get called when the mouse wheel was scrolled. Note that most mice have only a vertical scroll wheel, so scroll_x is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both scroll_x and scroll_y movement.
We can create a window with the help of command given below : 
pyglet.window.Window(width, height, title)
Below is the syntax of the on mouse scroll event, this method get called when this event is triggered :
@window.event       
def on_mouse_scroll(x, y, scroll_x, scroll_y):
    print("Mouse scrolled")
Below is the implementation :
Python3
# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = "GeeksforGeeks" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text,                          font_name ='Times New Roman',                          font_size = 36,                          x = window.width//2, y = window.height//2,                          anchor_x ='center', anchor_y ='center') new_label = pyglet.text.Label(text,                          font_name ='Times New Roman',                          font_size = 10,                          x = 25, y = 25) # on draw event@window.eventdef on_draw():             # clearing the window    window.clear()         # drawing the label on the window    label.draw()      # key press event   @window.eventdef on_key_press(symbol, modifier):     # key "C" get press    if symbol == pyglet.window.key.C:                 print("Key C is pressed")  # on mouse scroll event@window.eventdef on_mouse_scroll(x, y, scroll_x, scroll_y):         # printing some message    print("Mouse scrolled")         # image for iconimg = image = pyglet.resource.image("logo.png") # setting image as iconwindow.set_icon(img)                 # start running the applicationpyglet.app.run()
Output :  
Mouse scrolled
Mouse scrolled
Mouse scrolled
Mouse scrolled
Mouse scrolled
Mouse scrolled
Mouse scrolled
Mouse scrolled
Mouse scrolled
 
varshagumber28
Python-gui
Python-Pyglet
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Examples - File Size

How to get a files size in bytes ?
This example shows how to get a file's size in bytes by using file.exists() and file.length() method of File class.
import java.io.File;

public class Main {
   public static long getFileSize(String filename) {
      File file = new File(filename);
      if (!file.exists() || !file.isFile()) {
         System.out.println("File doesn\'t exist");
         return -1;
      }
      return file.length();
   }
   public static void main(String[] args) {
      long size = getFileSize("c:/java.txt");
      System.out.println("Filesize in bytes: " + size);
   }
}
The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file.
File size in bytes: 480

The following is another sample example of files size in java
import java.io.File;

public class FileSizeExample { 
   public static void main(String[] args) { 
      File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.png");
      if(file.exists()) { 
         double bytes = file.length();
         double kilobytes = (bytes / 1024);
         double megabytes = (kilobytes / 1024);
         double gigabytes = (megabytes / 1024);
         double terabytes = (gigabytes / 1024);
         double petabytes = (terabytes / 1024);
         double exabytes = (petabytes / 1024);
         double zettabytes = (exabytes / 1024);
         double yottabytes = (zettabytes / 1024);
         
         System.out.println("bytes : " + bytes);
         System.out.println("kilobytes : " + kilobytes);
         System.out.println("megabytes : " + megabytes);
         System.out.println("gigabytes : " + gigabytes);
         System.out.println("terabytes : " + terabytes);
         System.out.println("petabytes : " + petabytes);
         System.out.println("exabytes : " + exabytes);
         System.out.println("zettabytes : " + zettabytes);
         System.out.println("yottabytes : " + yottabytes);
      } else {
         System.out.println("File does not exists!");
      }
   }
}
The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file.
bytes : 6119.0
kilobytes : 5.9755859375
megabytes : 0.005835533142089844
gigabytes : 5.698762834072113E-6
terabytes : 5.565198080148548E-9
petabytes : 5.434763750145066E-12
exabytes : 5.307386474751041E-15
zettabytes : 5.182994604249064E-18
yottabytes : 5.061518168211976E-21

 Print
 Add Notes
 Bookmark this page
Can we have variables and methods in an enum in Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can define an enumeration using the keyword enum followed by the name of the enumeration as −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Enumerations are similar to classes and, you can have variables, methods, and constructors within them. Only concrete methods are allowed in an enumeration.
In the following example, we are defining an enumeration with name Vehicles and declaring five constants in it.
In addition to it we are having a constructor, instance variable and an instance method.
 Live Demo
enum Vehicles {
   //Declaring the constants of the enum
   ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
   //Instance variable of the enum
   int i;
   //Constructor of the enum
   Vehicles() {}
   //method of the enum
   public void enumMethod() {
      System.out.println("This is a method of enumeration");
   }
}
public class EnumExample{
   public static void main(String args[]) {
      Vehicles vehicles[] = Vehicles.values();
      for(Vehicles veh: vehicles) {
         System.out.println(veh);
      }
      System.out.println("Value of the variable: "+vehicles[0].i);
      vehicles[0].enumMethod();
   }
}
ACTIVA125
ACTIVA5G
ACCESS125
VESPA
TVSJUPITER
Value of the variable: 0
This is a method of enumeration
In the Following Java example, we are declaring 5 constants with values, we have an instance variable to hold the value(s) of the constant, a parameterized constructor to initialize it and a getter method to get these values.
 Live Demo
import java.util.Scanner;
enum Scoters {
   //Constants with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
   //Instance variable
   private int price;
   //Constructor to initialize the instance variable
   Scoters (int price) {
      this.price = price;
   }
   //Static method to display the price
   public static void displayPrice(int model){
      Scoters constants[] = Scoters.values();
      System.out.println("Price of: "+constants[model]+" is "+constants[model].price);
   }
}
public class EnumerationExample {
   public static void main(String args[]) {
      Scoters constants[] = Scoters.values();
      System.out.println("Value of constants: ");
      for(Scoters d: constants) {
         System.out.println(d.ordinal()+": "+d);
      }
      System.out.println("Select one model: ");
      Scanner sc = new Scanner(System.in);
      int model = sc.nextInt();
      //Calling the static method of the enum
      Scoters.displayPrice(model);
   }
}
Value of constants:
0: ACTIVA125
1: ACTIVA5G
2: ACCESS125
3: VESPA
4: TVSJUPITER
Select one model:
2
Price of: ACCESS125 is 75000
Find the size of a list - Python - GeeksforGeeks

17 May, 2020
In Python, a list is a collection data type that can store elements in an ordered manner and can also have duplicate elements. The size of a list means the amount of memory (in bytes) occupied by a list object. In this article, we will learn various ways to get the size of a python list.
1.Using getsizeof() function:
The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example.
Example 1:
import sys  # sample listslist1 = [1, 2, 3, 5]list2 = ["GeeksForGeeks", "Data Structure", "Algorithms"]list3 = [1, "Geeks", 2, "For", 3, "Geeks"]  # print the sizes of sample listsprint("Size of list1: " + str(sys.getsizeof(list1)) + "bytes")print("Size of list2: " + str(sys.getsizeof(list2)) + "bytes")print("Size of list3: " + str(sys.getsizeof(list3)) + "bytes")
Output:
Size of list1: 96bytes
Size of list1: 88bytes
Size of list1: 112bytes
Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used.
1.Using inbuilt __sizeof__() method:
Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:
# sample listslist1 = [1, 2, 3, 5]list2 = ["GeeksForGeeks", "Data Structure", "Algorithms"]list3 = [1, "Geeks", 2, "For", 3, "Geeks"]  # print the sizes of the sample listsprint("Size of list1: " + str(list1.__sizeof__()) + "bytes")print("Size of list2: " + str(list2.__sizeof__()) + "bytes")print("Size of list3: " + str(list3.__sizeof__()) + "bytes")
Output:
Size of list1: 72bytes
Size of list1: 64bytes
Size of list1: 88bytes
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Traversing a map (or unordered_map) in C++ STL

Here we will see the map container and its use in C++. The maps are defined as associative containers that store elements in a hash-mapped fashion. Each element is associated with a key and value. No two mapped values can have identical keys. These are some fundamental methods that are present inside the map container in C++.
begin(): This returns an iterator to the first element in the map.
end()− This returns an iterator to the theoretical element that follows last element in the map.
size() − This returns the number of elements in the map.
max_size() − This returns the maximum number of elements that the map can hold.
empty() − This returns whether the map is empty or not.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 };
   int num = sizeof(A) / sizeof(A[0]);
   map<int, int> my_map;
   for (int p = 0; p < num; p++)
      my_map[A[p]]++;
   cout <<"Item Frequency"<< endl;
   for (auto p : my_map)
      cout << p.first <<" : "<< p.second << endl;
}
Item Frequency
2 : 4
3 : 1
4 : 2
5 : 1
The unordered_map is another type of map container present in C++ STL. This is an associated container that collects or stores elements formed by combination of key value pair. The key is used to uniquely identify the value. In this case, both key and value can be of any type predefined or user-defined.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 };
   int num = sizeof(A) / sizeof(A[0]);
   unordered_map<int, int> my_map;
   for (int p = 0; p < num; p++)
      my_map[A[p]]++;
   cout <<Item Frequency"<< endl;
   for (auto p : my_map)
      cout << p.first <<" : "<< p.second << endl;
}
Item Frequency
5 : 1
4 : 2
2 : 4
3 : 1
Python Program to swap the First and the Last Character of a string - GeeksforGeeks

25 Nov, 2020
Given a String. The task is to swap the first and the last character of the string.
Examples:
Input: GeeksForGeeks
Output: seeksForGeekG
 
Input: Python
Output: nythoP
Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follow the below steps to swap characters –
We initialize a variable start, which stores the first character of the string (string[0])We initialize another variable end that stores the last character (string[-1])Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character.Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it.
We initialize a variable start, which stores the first character of the string (string[0])
We initialize another variable end that stores the last character (string[-1])
Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character.
Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it.
Below is the implementation.
Python3
def swap(string):          # storing the first character    start = string[0]          # storing the last character    end = string[-1]          swapped_string = end + string[1:-1] + start    print(swapped_string)      # Driver Codeswap("GeeksforGeeks")swap("Python")
Output:
seeksforGeekG
nythoP
Python string-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How does Query.prototype.lean() work in Mongoose ? - GeeksforGeeks

17 Mar, 2021
The Query.prototype.lean() function return the documents from queries with the lean option enabled are plain JavaScript objects, not Mongoose Documents.
Syntax:  
Query.prototype.lean()
Parameters: This function has one val parameter of boolean type.Return Value: This function returns Query Object.
Mongoose Installation:
npm install mongoose
After installing the mongoose module, you can check your mongoose version in command prompt using the command. 
npm mongoose --version
After that, you can just create a folder and add a file for example, index.js as shown below.
Database: The sample database used here is shown below:  
Example 1:
index.js
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {     name: { type: String },    age: { type: Number }});  const query = User.find().lean(true)console.log("Lean Value:", query._mongooseOptions);
The project structure will look like this:  
Run index.js file using below command: 
node index.js
Output: 
Lean Value: { lean: true }
Example 2:
index.js
const express = require('express');const mongoose = require('mongoose');const app = express()  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {     name: { type: String },    age: { type: Number }});  const query = User.find().lean(false)console.log("Lean Value:", query._mongooseOptions);  app.listen(3000, function(error ) {    if(error) console.log(error)    console.log("Server listening on PORT 3000")});
The project structure will look like this:  
Run index.js file using below command: 
node index.js
Output: 
Server listening on PORT 3000
Lean Value: { lean: false }
Reference: https://mongoosejs.com/docs/api/query.html#query_Query-lean 
Mongoose
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
How to connect Node.js with React.js ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to remove focus from a Tkinter widget?

To active the focus on a particular widget during the execution of a Tkinter program, we can use focus_set() method. Adding the focus creates a gray line around the widget and makes it visible to the user.
There might be some cases when we need to remove the focus from the desired widget.
This can be done either by removing the focus_set() property or switching the focus from one widget to another.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter Frame
win.geometry("750x250")

#Define a function to show the message
def logged_in():
   messagebox.showinfo("Message", "Successfully Logged In!")
   win.destroy()

#Define a Label widget
Label(win, text= "Login to the System", font=('Aerial', 14, 'bold')).pack(pady=15)
#Create an entry widget
Label(win, text="Enter Username").pack()
username= Entry(win, width= 20)
username.pack()
Label(win, text= "Enter passowrd").pack()
password= Entry(win, show="*", width= 20)
password.pack()
password.focus_set()
#Add a Bottom widget
button=ttk.Button(win, text="Login", command= logged_in)
button.pack(pady=13)

#Create a Button widget
win.mainloop()
In the above code snippet, the focus is currently set to the Password Entry Field, which can be unset or switched by adding focus_set() to another widget.
Recursive program for prime number in C++

We are given an integer as input. The goal is to find whether the input number Num is a prime or non-prime using recursion.
To check if a number is prime or not, start traversing from i=2 to i<=Num/2. If any i is fully divisible by Num then the number is non-prime as prime numbers are only divisible by 1 and the number itself.
Input − Num = 32
Output − 32 is non-Prime!
Explanation − If we start traversing from i=2 to i<=32/2, then at first it will be fully divisible by 2 which tells it is non-prime.
Input − Num = 43
Output − 43 is a Prime number!
Explanation − If we start traversing from i=2 to i<=43/2, then it will not be divisible by any number between 2 and 21. Which tells it is prime.
In this approach we are using the recursive function checkPrime(int num1, int index) which takes input number and index which will take values from 2 to num1/2.
For base case-: if num1<2 return 1 as it is non-prime.
If num1==2 return 2 as it is prime.
Else:- if(index<=num1/2) then we reached point upto which no index fully divided num1 so return 1 as it is possible for prime numbers only.
Otherwise recurse for next index using result=checkPrime(num1, index+1)
Take the input number Num
Take the input number Num
Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0.
Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0.
If num1<2 return 0 as numbers less than 2 are non-prime.
If num1<2 return 0 as numbers less than 2 are non-prime.
If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers.
If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers.
If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime
If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime
Recurse for the next index using result=checkPrime(num1, index+1).
Recurse for the next index using result=checkPrime(num1, index+1).
Return result.
Return result.
Print result obtained inside main.
Print result obtained inside main.
#include <bits/stdc++.h>
using namespace std;
int checkPrime(int num1, int index){
   if(num1<2){
      return 0;
   }
   if (num1 == 2 || num1==3){
      return 1;
   }
   if (num1 % index == 0){
      return 0;
   }
   if (index <= num1/2){
      return 1;
   }
   int result=checkPrime(num1, index+1);

   return (result);
}
int main(){
   int Num = 31;
   if (checkPrime(Num,2)==1){
      cout <<Num<<" is a Prime number !";
   }
   else{
      cout <<Num<<" is non Prime!";
   }

   return 0;
}
If we run the above code it will generate the following Output
31 is a Prime number!
How to replace innerHTML of a div using jQuery?

To replace innerHTML of a div in jQuery, use the html() or text() method.
You can try to run the following code to learn how to replace innerHTML of a div:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button1").click(function(){  
       $('#demo').html('Demo text');
   });
});
</script>
</head>
<body>

<div id="demo">This is <b>Amit</b>!
</div>
<button id="button1">Replace</button>
</body>
</html>
Java Program to display table with columns in the output using Formatter

To display table with columns as output, use the Formatter class. For working with Formatter class, import the following package −
import java.util.Formatter;
Consider an array with some elements. This is the array which we will be shown as output in tabular form −
double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 };
While displaying the double array values, use the %f to set spaces −
for (double d : arr) {
   f.format("%14.2f %14.2f %15.2f\n", d, Math.ceil(d), Math.floor(d));
}
The following is an example −
 Live Demo
import java.util.Formatter;
public class Demo {
   public static void main(String[] argv) throws Exception {
      double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 };
      Formatter f = new Formatter();
      f.format("%15s %15s %15s\n", "Points1", "Points2", "Points3");
      System.out.println("The point list...\n");
      for (double d : arr) {
         f.format("%14.2f %14.2f %15.2f\n", d, Math.ceil(d), Math.floor(d));
      }
      System.out.println(f);
   }
}
The point list...
Points1 Points2 Points3
1.70 2.00 1.00
2.50 3.00 2.00
3.10 4.00 3.00
4.50 5.00 4.00
5.70 6.00 5.00
6.90 7.00 6.00
7.70 8.00 7.00
8.90 9.00 8.00
9.10 10.00 9.00
Undo and redo features in a Tkinter Text widget

Tkinter Text widget is another input widget similar to the Entry widget which accepts multiline user input in a text field. It contains many inbuilt features and functions which helps to configure the default properties of the text widget. However, to add undo/Redo features in the Tkinter text widget, we can use Boolean attributes undo which ensures that the text can be retrieved again.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

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

# Create a Text widget with undo is set
text=Text(win, width=60, height=20, undo=True)
text.pack()

text.insert(END, "Enter anything Here...")

win.mainloop()
Run the above code to display a text widget that has Undo/Redo features enabled.
To test the feature, write something in the Text widget and press Ctrl+Z to undo or Ctrl+Y to redo the text.