code-rag-bench/online-tutorials huggingface dataset:
How to Use Images as Backgrounds in Tkinter?

If we will create an instance of Tkinter frame and display the window while keep running it, then it will show the default output canvas. However, we can add an image inside the Tkinter canvas as a background using PhotoImage methods and Canvas methods.
Since image support in Tkinter is limited to Gif, PNG and PPM, the PhotoImage(GIF,
PNG, PPM) function takes the location of the image file and displays the canvas with the
image as a background.
First, we will create a PhotoImage Object using the PhotoImage function.
from tkinter import *
from PIL import ImageTk

win = Tk()
win.geometry("700x300")

#Define the PhotoImage Constructor by passing the image file
img= PhotoImage(file='down.png', master= win)
img_label= Label(win,image=img)

#define the position of the image
img_label.place(x=0, y=0)

win.mainloop()
Running the above code snippet will display a window with a background image.
How to create an ordered list in HTML?

To create ordered list in HTML, use the <ol> tag. Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, letters and roman numbers. The default is numbers.
You can try to run the following code to use an ordered list in HTML −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <h1>Developed Countries</h1>
      <p>The list of developed countries :</p>
      <ol>
         <li>US</li>
         <li>Australia</li>
         <li>New Zealand</li>
      </ol>
   </body>
</html>
Output of C Programs | Set 3

03 Feb, 2021
Predict the output of the below program. Question 1 
c
#include <stdio.h>int main(){  printf("%p", main);  getchar();  return 0;}
Output: Address of function main. Explanation: Name of the function is actually a pointer variable to the function and prints the address of the function. Symbol table is implemented like this. 
struct 
{
   char *name;
   int (*funcptr)();
}
symtab[] = {
   "func", func,
   "anotherfunc", anotherfunc,
}; 
Question 2  
c
#include <stdio.h>int main(){   printf("\new_c_question\by");   printf("\rgeeksforgeeks");    getchar();   return 0;}
Output: geeksforgeeks Explanation: First printf prints “ew_c_questioy”. Second printf has \r in it so it goes back to start of the line and starts printing characters.Now try to print following without using any of the escape characters. 
new c questions by
geeksforgeeks
Question 3  
c
# include<stdio.h># include<stdlib.h> void fun(int *a){    a = (int*)malloc(sizeof(int));} int main(){    int *p;    fun(p);    *p = 6;    printf("%d\n",*p);        getchar();    return(0);}
It does not work. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer.This is because fun() makes a copy of the pointer, so when malloc() is called, it is setting the copied pointer to the memory location, not p. p is pointing to random memory before and after the call to fun(), and when you dereference it, it will crash.If you want to add memory to a pointer from a function, you need to pass the address of the pointer (ie. double pointer).Thanks to John Doe for providing the correct solution. For better understanding please go through the following link: https://stackoverflow.com/questions/1398307/how-can-i-allocate-memory-and-return-it-via-a-pointer-parameter-to-the-callingQuestion 4 
c
#include <stdio.h>int main(){    int i;    i = 1, 2, 3;            printf("i = %d\n", i);     getchar();    return 0;}
Output: 1 The above program prints 1. Associativity of comma operator is from left to right, but = operator has higher precedence than comma operator. Therefore the statement i = 1, 2, 3 is treated as (i = 1), 2, 3 by the compiler.Now it should be easy to tell output of below program.
c
#include <stdio.h>int main(){    int i;    i = (1, 2, 3);            printf("i  = %d\n", i);     getchar();     return 0;}
Question 5 
c
#include <stdio.h>int main(){    int first = 50, second = 60, third;    third = first /* Will this comment work? */ + second;    printf("%d /* And this? */ \n", third);          getchar();    return 0;}
Output: 110 /* And this? */ Explanation: Compiler removes everything between “/*” and “*/” if they are not present inside double quotes (“”).
marant102
domkarchel38
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interesting Commands on Mac Terminal

25 Aug, 2020
Terminal is one of the most important tools in MacOS be it any field. To get good knowledge about the terminal is important. It teaches you many things in an innovative way which is liked by most of the developers. It’s a knowledge that only geeks and geniuses have. Here are some commands with the most impressive features.
The commands used below may or may not be installed in your system. To install them use the brew command as follows:
% brew install <command-name>


Make your Mac talk what you want using the say command:
% say Hello Geeks


Set up a login message to display for yourself on your Mac using the following command –
% sudo write /Library/Preferences/com.apple.loginwindow LoginwindowText "Login Message for Display"


% cowsay <message>


% emac


After the above command press “enter” then “escape” then “x”. Now you enter the following commands:
doctor
snake
solitaire
pong.
These are some command, there are many more. The doctor provides you a psychiatrist to talk and snakes, solitaire, etc are games.
This command displays random quotes
% fortune


You can see the complete Star Wars animation in your terminal using this command.
% nc towel.blinkenlights.nl 23


This command displays a neo style matrix on the terminal.
% cmatrix


This command reverses all the content of the file. It is used as follows.
Shell
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <th> height Attribute

26 Jun, 2019
The HTML <th> height Attribute is used to specify the height of the table header cell. If the <th> height attribute is not set then it takes default height according to content. It is not supported by HTML 5.
Syntax:
<th height="pixels | %">
Attribute Values:
pixels: It sets the height of table header cell in terms of pixels.
%: It sets the height of table header cell in terms of percentage (%).
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML th height Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML th height Attribute</h2>      <table border="1" width="500">        <tr>            <th height="50">NAME</th>            <th height="50">AGE</th>            <th height="50">BRANCH</th>        </tr>          <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>          <tr>            <td>RAKESH</td>            <td>25</td>            <td>EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <th> height 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.
numpy.fromstring() function – Python

18 Aug, 2020
numpy.fromstring() function create a new one-dimensional array initialized from text data in a string.
Syntax : numpy.fromstring(string, dtype = float, count = -1, sep = ‘ ‘)
Parameters :
string : [str] A string that contained the data.
dtype : [data-type, optional] Data-type of the array. Default data type is float.
count : [int, optional] Number of items to read. If this is negative (the default), the count will be determined from the length of the data.
sep : [str, optional] The string separating numbers in the data.
Return : [ndarray] Return the constructed array.
Code #1 :
Python3
# Python program explaining# numpy.fromstring() function   # importing numpy as geekimport numpy as geek   gfg = geek.fromstring('1 2 3 4 5', dtype = float, sep = ' ')   print(gfg)
Output :
[1. 2. 3. 4. 5.]
Code #2 :
Python3
# Python program explaining# numpy.fromstring() function   # importing numpy as geekimport numpy as geek   gfg = geek.fromstring('1 2 3 4 5 6', dtype = int, sep = ' ')   print(gfg)
Output :
[1 2 3 4 5 6]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find equation of a plane passing through 3 points in C++

In this tutorial, we will be discussing a program to find equation of a plane passing through 3 points.
For this we will be provided with 3 points. Our task is to find the equation of the plane consisting of or passing through those three given points.
 Live Demo
#include <bits/stdc++.h>
#include<math.h>
#include <iostream>
#include <iomanip>
using namespace std;
//finding the equation of plane
void equation_plane(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){
   float a1 = x2 - x1;
   float b1 = y2 - y1;
   float c1 = z2 - z1;
   float a2 = x3 - x1;
   float b2 = y3 - y1;
   float c2 = z3 - z1;
   float a = b1 * c2 - b2 * c1;
   float b = a2 * c1 - a1 * c2;
   float c = a1 * b2 - b1 * a2;
   float d = (- a * x1 - b * y1 - c * z1);
   std::cout << std::fixed;
   std::cout << std::setprecision(2);
   cout << "Equation of plane is " << a << " x + " << b << " y + " << c << " z + " << d << " = 0";
}
int main(){
   float x1 =-1;
   float y1 = 2;
   float z1 = 1;
   float x2 = 0;
   float y2 =-3;
   float z2 = 2;
   float x3 = 1;
   float y3 = 1;
   float z3 =-4;
   equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3);
   return 0;
}
Equation of plane is 26.00 x + 7.00 y + 9.00 z + 3.00 = 0
How to create Python dictionary from list of keys and values?

If L1 and L2 are list objects containing keys and respective values, following methods can be used to construct dictionary object.
Zip two lists and convert to dictionary using dict() function
>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = dict(zip(L1,L2))
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using dictionary comprehension syntax
>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = {k:v for k,v in zip(L1,L2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
How to convert numbers to words using Python?

The constructor for the string class in python, ie, str can be used to convert a number to a string in python. For example,
i = 10050
str_i = str(i)
print(type(str_i))
This will give the output:
<class 'str'>
But if you want something that converts integers to words like 99 to ninety-nine, you have to use an external package or build one yourself. The pynum2word module is pretty good at this task. You can install it using
$ pip install pynum2word
Then use it in the following way
>>> import num2word
>>> num2word.to_card(16)
'sixteen'
>>> num2word.to_card(23)
'twenty-three'
>>> num2word.to_card(1223)
'one thousand, two hundred and twenty-three'
gettext - Unix, Linux Command

Display native language translation of a textual message.

gettext is an internationalization and localization system commonly used for writing multilingual programs. For gettext to work, the message catalogue is required.
$ cat test.sh
gettext -s "This message to be translated"

$ xgettext -c /

msgid "This message to be translated"
msgstr ""

$ msginit --locale=es --input=name.pot

msgid "This message to be translated"
msgstr "This is a translated message"

$ msginit --locale=es --input=es.pot


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Add space between pagination links with CSS

You can try to run the following code to add space between pagination links with CSS:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .demo {
            display: inline-block;
         }
         .demo a {
            color: red;
            padding: 5px 12px;
            text-decoration: none;
            transition: background-color 2s;
            border: 1px solid orange;
         }
         .demo a.active {
            background-color: orange;
            color: white;
            border-radius: 5px;
         }
         .demo a:hover:not(.active) {
            background-color: yellow;
         }
         .demo a:first-child {
            border-top-left-radius: 10px;
            border-bottom-left-radius: 10px;
         }
         .demo a:last-child {
            border-top-right-radius: 10px;
            border-bottom-right-radius: 10px;
         }
      </style>
   </head>
   <body>
      <h2>Our Quizzes</h2>
      <div class = "demo">
         <a href = "prev.html"><</a>
         <a href = "quiz1.html">Quiz1</a>
         <a href = "quiz2.html">Quiz2</a>
         <a href = "quiz3.html" class = "active">Quiz3</a>
         <a href = "quiz4.html">Quiz4</a>
         <a href = "next.html">></a>
     </div>
   </body>
</html>
Python | Program that matches a word containing ‘g’ followed by one or more e’s using regex

29 Dec, 2020
Prerequisites : Regular Expressions | Set 1, Set 2
Given a string, the task is to check if that string contains any g followed by one or more e’s in it, otherwise, print No match.
Examples :
Input : geeks for geeks
Output : geeks 
         geeks

Input : graphic era
Output : No match 

Approach : Firstly, make a regular expression (regex) object that matches a word which contains ‘g’ followed by one or more e’s, then pass a string in the findall method. This method returns the list of the matched strings. Loop through the list and print each matched word.
\w – represent Any letter, numeric digit, or the underscore character.* means zero or more occurrence of the character.+ means one or more occurrence of the character.
Below is the implementation :
# Python program that matches a word# containing ‘g’ followed by one or# more e’s using regex  # import re packagesimport re  # Function check if the any word of# the string containing 'g' followed# by one or more e'sdef check(string) :            # Regex \w * ge+\w * will match     # text that contains 'g', followed     # by one or more 'e'    regex = re.compile("ge+\w*")      # The findall() method returns all     # matching strings of the regex pattern    match_object = regex.findall(string)      # If length of match_object is not    # equal to zero then it contains    # matched string    if len(match_object) != 0 :          # looping through the list        for word in match_object :            print(word)                  else :        print("No match")    # Driver Code     if __name__ == '__main__' :      # Enter the string    string = "Welcome to geeks for geeks"      # Calling check function    check(string)
Output :
geeks
geeks
ManasChhabra2
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Replace delimiter

10 Jul, 2020
Given List of Strings and replacing delimiter, replace current delimiter in each string.
Input : test_list = [“a, t”, “g, f, g”, “w, e”, “d, o”], repl_delim = ‘ ‘Output : [“a t”, “g f g”, “w e”, “d o”]Explanation : comma is replaced by empty spaces at each string.
Input : test_list = [“g#f#g”], repl_delim = ‘, ‘Output : [“g, f, g”]Explanation : hash is replaced by comma at each string.
Method #1 : Using replace() + loopThe combination of above functions provide a brute force method to solve this problem. In this, a loop is used to iterate through each string and perform replacement using replace().
# Python3 code to demonstrate working of # Replace delimiter# Using loop + replace()  # initializing listtest_list = ["a, t", "g, f, g", "w, e", "d, o"]   # printing original listprint("The original list is : " + str(test_list))  # initializing replace delimiterrepl_delim = '#'  # Replace delimiterres = []for ele in test_list:           # adding each string after replacement using replace()    res.append(ele.replace(", ", repl_delim))  # printing result print("Replaced List : " + str(res))
The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']

 
Method #2 : Using list comprehension + replace()The combination of above functions can provide one liner to this problem. This is similar to above method, just encapsulated in list comprehension.
# Python3 code to demonstrate working of # Replace delimiter# Using list comprehension + replace()  # initializing listtest_list = ["a, t", "g, f, g", "w, e", "d, o"]   # printing original listprint("The original list is : " + str(test_list))  # initializing replace delimiterrepl_delim = '#'  # Replace delimiter# iterating inside comprehension, performing replace using replace()res = [sub.replace(', ', repl_delim) for sub in test_list]  # printing result print("Replaced List : " + str(res))
The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
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
Evaluate the Mathematical Expressions using Tkinter in Python

17 Feb, 2022
This article focuses on the evaluation of mathematical expression using the Tkinter and math packages in Python. 
Tkinter: Python Tkinter is a GUI programming package or built-in package. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. 
Math module: In python, a variety of mathematical operations can be carried out with ease by importing a python module called “math” that specifies various functions, making our tasks simpler. 
Importing the  tkinter & math packages.
Create the main window.
Add number of widgets to the main window : Entry , Label.
Evaluating the expression.
Displaying message.
Apply the event trigger on the widgets.
PYTHON
# Importing tkinter module as tkimport tkinter as tk # Importing all functions/methods# from math modulefrom math import * # Import messagebox class from tkinterfrom tkinter import messagebox # function for evaluating the expressiondef eval_expression(event):    result.configure(text = " Result: " +                     str(eval(entry.get())))         messagebox.showinfo("Evaluate Expression",                        "Successfully evaluated" )  # creating Tk windowroot = tk.Tk() # set geometry of root windowroot.geometry('300x150+600+200') # set the title of root windowroot.title('Evaluate Expression') # label and entry fieldinput_label = tk.Label(root,                      text = " Enter Your Expression:",).grid(row = 1)entry = tk.Entry(root) # bind 'enter' event to the# eval_expression() through# entry widgetentry.bind("
OUTPUT :
Evaluate expression GUI
Evaluate expression working
 
varshagumber28
punamsingh628700
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program for Leaders in an array

13 Dec, 2021
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the array be size. 
Method 1 (Simple) Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.  
Java
class LeadersInArray {    /*Java Function to print leaders in an array */    void printLeaders(int arr[], int size)     {        for (int i = 0; i < size; i++)         {            int j;            for (j = i + 1; j < size; j++)             {                if (arr[i] <=arr[j])                    break;            }            if (j == size) // the loop didn't break                System.out.print(arr[i] + " ");        }    }      /* Driver program to test above functions */    public static void main(String[] args)     {        LeadersInArray lead = new LeadersInArray();        int arr[] = new int[]{16, 17, 4, 3, 5, 2};        int n = arr.length;        lead.printLeaders(arr, n);    }}
Output: 
17 5 2
Time Complexity: O(n*n)Method 2 (Scan from right) Scan all the elements from right to left in an array and keep track of maximum till now. When maximum changes its value, print it.Below image is a dry run of the above approach: 
Below is the implementation of the above approach: 
Java
class LeadersInArray {    /* Java Function to print leaders in an array */    void printLeaders(int arr[], int size)    {        int max_from_right =  arr[size-1];           /* Rightmost element is always leader */        System.out.print(max_from_right + " ");               for (int i = size-2; i >= 0; i--)        {            if (max_from_right < arr[i])            {                       max_from_right = arr[i];            System.out.print(max_from_right + " ");            }        }        }      /* Driver program to test above functions */    public static void main(String[] args)     {        LeadersInArray lead = new LeadersInArray();        int arr[] = new int[]{16, 17, 4, 3, 5, 2};        int n = arr.length;        lead.printLeaders(arr, n);    }}
Output:
2 5 17
Time Complexity: O(n) 
Please refer complete article on Leaders in an array for more details!
Amazon
Payu
Arrays
Java
Java Programs
Amazon
Payu
Arrays
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
Python | Substring removal in String list

30 Jan, 2020
While working with strings, one of the most used application is removing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the removing of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + replace()The replace method can be coupled with the list comprehension technique to achieve this particular task. List comprehension performs the task of iterating through the list and replace method replaces the section of substring with empty string.
# Python3 code to demonstrate# Substring removal in String list# using list comprehension + replace()  # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']  # printing original list print("The original list : " + str(test_list ))  # using list comprehension + replace()# Substring removal in String listres = [sub.replace('4', '') for sub in test_list]      # print resultprint("The list after substring removal : " + str(res))
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring removal : ['', 'kg', 'butter', 'for', '0', 'bucks']

 
Method #2 : Using map() + lambda + replace()The combination of these functions can also be used to perform this particular task. The map and lambda help to perform the task same as list comprehension and replace method is used to perform the remove functionality. But this method is poor when it comes to performance than method above.
# Python3 code to demonstrate# Substring removal in String list# using list comprehension + map() + lambda  # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']  # printing original list print("The original list : " + str(test_list ))  # using list comprehension + map() + lambda# Substring removal in String listres = list(map(lambda st: str.replace(st, "4", ""), test_list))      # print resultprint("The list after substring removal : " + str(res))
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring removal : ['', 'kg', 'butter', 'for', '0', 'bucks']

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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
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
Get specific elements from embedded array in MongoDB?

To get specific elements, use $match with dot notation. Let us create a collection with documents −
> db.demo641.insert(
...    {
...       ProductId:101,
...       "ProductInformation":
...      (                            [
...          {
...             ProductName:"Product-1",
...             "ProductPrice":1000
...          },
...          {
...             ProductName:"Product-2",
...             "ProductPrice":500
...          },
...          {
...             ProductName:"Product-3",
...             "ProductPrice":2000
...          },
...          {
...             ProductName:"Product-4",
...             "ProductPrice":3000
...          }
...       ]
...    }
... );
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo641.find();
This will produce the following output −
{
   "_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
   [
      { "ProductName" : "Product-1", "ProductPrice" : 1000 },
      { "ProductName" : "Product-2", "ProductPrice" : 500 },
      { "ProductName" : "Product-3", "ProductPrice" : 2000 },
      { "ProductName" : "Product-4", "ProductPrice" : 3000 }
   ] 
}
Following is the query to get specific elements from embedded array in MongoDB
> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();
This will produce the following output −
{
   "ProductInformation" : {
      "ProductName" : "Product-1",
      "ProductPrice" : 1000
   }
}
{
   "ProductInformation" : {
      "ProductName" : "Product-3",
      "ProductPrice" : 2000
   }
}
Python | Pandas dataframe.memory_usage()

22 Jun, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.memory_usage() function return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of object dtype. This value is displayed in DataFrame.info by default.  
Syntax: DataFrame.memory_usage(index=True, deep=False)Parameters : index : Specifies whether to include the memory usage of the DataFrame’s index in returned Series. If index=True the memory usage of the index the first item in the output. deep : If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values.Returns : A Series whose index is the original column names and whose values is the memory usage of each column in bytes  
For link to the CSV file used in the code, click hereExample #1: Use memory_usage() function print the memory usage of each column in the dataframe along with the memory usage of the index. 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv("nba.csv") # Print the dataframedf
  Let’s use the memory_usage() function to find the memory usage of each column. 
Python3
# Function to find memory use of each# column along with the index# even if we do not set index = True,# it will show the index usage as well by default.df.memory_usage(index = True)
Output :  
  Example #2: Use memory_usage() function to find the memory use of each column but not of the index. 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv("nba.csv") # Function to find memory use of each# column but not of the index# we set index = Falsedf.memory_usage(index = False)
Output :  
 
surinderdawra388
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Third Normal Form (3NF)

31 Jul, 2019
Although Second Normal Form (2NF) relations have less redundancy than those in 1NF, they may still suffer from update anomalies. If we update only one tuple and not the other, the database would be in an inconsistent state. This update anomaly is caused by a transitive dependency. We need to remove such dependencies by progressing to Third Normal Form (3NF).
Third Normal Form (3NF):A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form.
A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> Y:
X is a super key.Y is a prime attribute (each element of Y is part of some candidate key).
X is a super key.
Y is a prime attribute (each element of Y is part of some candidate key).
In other words,
A relation that is in First and Second Normal Form and in which no non-primary-key attribute is transitively dependent on the primary key, then it is in Third Normal Form (3NF).
Note – If A->B and B->C are two FDs then A->C is called transitive dependency.
The normalization of 2NF relations to 3NF involves the removal of transitive dependencies. If a transitive dependency exists, we remove the transitively dependent attribute(s) from the relation by placing the attribute(s) in a new relation along with a copy of the determinant.
Consider the examples given below.
Example-1:In relation STUDENT given in Table 4,
FD set:{STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}
Candidate Key:{STUD_NO}
For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:
STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE) 
STATE_COUNTRY (STATE, COUNTRY) 
Example-2:Consider relation R(A, B, C, D, E)
A -> BC,
CD -> E, 
B -> D, 
E -> A 
All possible candidate keys in above relation are {A, E, CD, BC} All attribute are on right sides of all functional dependencies are prime.
Note –Third Normal Form (3NF) is considered adequate for normal relational database design because most of the 3NF tables are free of insertion, update, and deletion anomalies. Moreover, 3NF always ensures functional dependency preserving and lossless.
DBMS-Normalization
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
Introduction of B-Tree
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
How to Make Changes to The Application Deployed on Heroku ?

11 Jul, 2022
Many of the times we need to make changes to our deployed project for some reason. Either we want to have a new version of the project, add new features to the project, remove a bug, or for some other reasons. If your project is deployed on Heroku Cloud Platform, you can easily make your changes using the CLI and deploy them to Heroku. In this blog, we will discuss the step-by-step process to make changes in your project and deploy it on Heroku.  Let’s start first with the short introduction of Heroku...
Heroku is a cloud platform service that allows you to build, deliver, monitor, and scale apps. It is a container-based cloud Platform as a Service (PaaS). It provides the freedom to the developers to focus on the core product instead of getting distracted from maintaining servers, hardware, or infrastructure. 
Prerequisite: Introduction and Installation of Heroku CLI
Heroku CLI can easily be downloaded and installed by the following the steps given here. Make sure to log in to Heroku CLI.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
After successful login, you will see the following in the terminal :
Open another terminal and use git to clone your repository.
$ heroku git:clone -a your_app
$ cd your_app

Make all the required changes in your project 
$ git add .
$ git commit -am "changes made to the project"
$ git push heroku master

Enjoy! Your project is now successfully updated and deployed.
Now, in case if you want to change your main deploy branch from “master” to “main”(any other branch) for both manual and automatic deploys, you can do so by following these simple steps:
To do this we first need to create a new branch locally.
$ git checkout -b main

We need to delete the old branch so that the local environment only knows about the main branch.
$ git branch -D master

This will empty the remote repository but it will not impact the running application.
$ heroku repo:reset -a your_app

Finally, using the new default branch you can redeploy the application.
$ git push heroku main

Heroku Cloud
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Tryit Editor v1.6

SELECT * FROM Customers
ORDER BY CustomerName DESC;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How do I get the creation date of a MySQL table?

To get the creation date of MySQL table, use the information_schema. The syntax is as follows −
SELECT create_time FROM INFORMATION_SCHEMA.TABLES
   WHERE table_schema = 'yourDatabaseName’
   AND table_name = 'yourTableName';
Apply the above syntax for your database and the table name. Here I am using the database ‘business’ and table name is ‘student’. The query is as follows −
mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES
   -> WHERE table_schema = 'business'
   -> AND table_name = 'student';
The following is the output displaying the creation time of a table −
+---------------------+
| CREATE_TIME         |
+---------------------+
| 2018-10-01 12:26:57 |
+---------------------+
1 row in set (0.12 sec)
Let us see another example and create a table from scratch.
mysql> create table DateAsStringDemo
   -> (
   -> YourDateTime datetime
   -> );
Query OK, 0 rows affected (0.57 sec)
I have just created a table and my current date time is as follows −
mysql> select now();
The following is the output −
+---------------------+
| now()               |
+---------------------+
| 2018-11-26 18:12:29 |
+---------------------+
1 row in set (0.00 sec)
Now you can check the creation time of the above table, which will give the date 2018-11-26.
The query is as follows −
mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES
   -> WHERE table_schema = 'test'
   -> AND table_name = 'DateAsStringDemo';
The following is the output −
+---------------------+
| CREATE_TIME         |
+---------------------+
| 2018-11-26 18:01:44 |
+---------------------+
1 row in set (0.00 sec)
Unary operators in C/C++

Here we will see what are the unary operators in C / C++. Unary operator is operators that act upon a single operand to produce a new value. The unary operators are as follows.
These operators have right-to-left associativity. Unary expressions generally involve syntax that precedes a postfix or primary expression
Let's look at an example of the -(minus) and casting() unary operators.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int x;
   float y = 1.23;
   x = (int) y;
   x = -x;
   cout << x;
   return 0;
}
-1
Explain the basic structure of a program in Java?

A typical structure of a Java program contains the following elements
Package declaration
Import statements
Comments
Class definition
Class variables, Local variables
Methods/Behaviors
A class in Java can be placed in different directories/packages based on the module they are used. For all the classes that belong to a single parent source directory, a path from source directory is considered as package declaration.
There can be classes written in other folders/packages of our working java project and also there are many classes written by individuals, companies, etc which can be useful in our program. To use them in a class, we need to import the class that we intend to use. Many classes can be imported in a single program and hence multiple import statements can be written.
The comments in Java can be used to provide information about the variable, method, class or any other statement. It can also be used to hide the program code for a specific time.
A name should be given to a class in a java file. This name is used while creating an object of a class, in other classes/programs.
The Variables are storing the values of parameters that are required during the execution of the program. Variables declared with modifiers have different scopes, which define the life of a variable.
Execution of a Java application starts from the main method. In other words, its an entry point for the class or program that starts in Java Run-time.
A set of instructions which form a purposeful functionality that can be required to run multiple times during the execution of a program. To not repeat the same set of instructions when the same functionality is required, the instructions are enclosed in a method. A method’s behavior can be exploited by passing variable values to a method.
Live Demo
package abc; // A package declaration
import java.util.*; // declaration of an import statement
   // This is a sample program to understnd basic structure of Java (Comment Section)
   public class JavaProgramStructureTest { // class name
      int repeat = 4; // global variable
      public static void main(String args[]) { // main method
      JavaProgramStructureTest test = new JavaProgramStructureTest();
         test.printMessage("Welcome to Tutorials Point");
   }
   public void printMessage(String msg) { // method
      Date date = new Date(); // variable local to method
      for(int index = 0; index < repeat; index++) { // Here index - variable local to for loop
         System.out.println(msg + "From" + date.toGMTString());
      }
   }
}
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Preview an image before it is uploaded in JavaScript

For security reasons browsers do not allow accessing the path of the image file selected via an input, i.e.JavaScript in browsers has no access to the File System. Therefore, our task is to preview the image file selected via the input before we send it to any server or anywhere else.
WE can use the createObjectURL() function of the URL class to create a url of the image selected by the input and then provide that url to the src attribute of an img tag.
The code for this will be −
<img id="preview"/>
<input type="file" accept="image/*" onchange="previewImage(event)">
<script>
   const previewImage = e => {
      const preview = document.getElementById('preview');
      preview.src = URL.createObjectURL(e.target.files[0]);
      preview.onload = () => URL.revokeObjectURL(preview.src);
   };
</script>
This method will parse the file taken in by the <input /> and then it will create a string containing a base64 representation of the image.
The code for this will be −
 Live Demo
<img id="preview"/>
<input type="file" accept="image/*" onchange="previewImage(event)">
<script>
   const previewImage = e => {
      const reader = new FileReader();
      reader.readAsDataURL(e.target.files[0]);
      reader.onload = () => {
         const preview = document.getElementById('preview');
         preview.src = reader.result;
      };
   };
</script>
The output for both the methods will look like −
Java Examples - Calculating Fibonacci Series

How to use  method for calculating Fibonacci series?
This example shows the way of using  method for calculating Fibonacci Series upto numbers.
public class MainClass {
   public static long fibonacci(long number) {
      if ((number == 0) || (number == 1)) return number;
      else return fibonacci(number - 1) + fibonacci(number - 2);
   }
   public static void main(String[] args) {
      for (int counter = 0; counter <= 10; counter++){
         System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
      }
   }
}
The above code sample will produce the following result.
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55

The following is an another example of Fibonacci series
public class ExampleFibonacci {
   public static void main(String a[]) {
      int count = 15;
      int[] feb = new int[count];
      feb[0] = 0;
      feb[1] = 1;
      
      for(int i = 2; i < count; i++) {
         feb[i] = feb[i-1] + feb[i-2];
      } 
      for(int i = 0; i < count; i++) {
         System.out.print(feb[i] + " ");
      }
   }
}
The above code sample will produce the following result.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

 Print
 Add Notes
 Bookmark this page
BigInteger class in Java


The java.math.BigInteger class provides operations analogs to all of Java's primitive integer operators and for all relevant methods from java.lang.Math.
It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations. All operations behave as if BigIntegers were represented in twos-complement notation.
The semantics of arithmetic operations and bitwise logical operations are similar to those of Java's integer arithmetic operators and Java's bitwise integer operators respectively. The semantics of shift operations extend those of Java's shift operators to allow for negative shift distances.
Comparison operations perform signed integer comparisons. Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. Bit operations operate on a single bit of the twos-complement representation of their operand.
All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter.
Following is the declaration for java.math.BigInteger class −
public class BigInteger    
   extends Number      
      implements Comparable<BigInteger>
Following are the fields for java.math.BigInteger class −
static BigInteger ONE − The BigInteger constant one.
static BigInteger ONE − The BigInteger constant one.
static BigInteger TEN − The BigInteger constant ten.
static BigInteger TEN − The BigInteger constant ten.
static BigInteger ZERO − The BigInteger constant zero.
static BigInteger ZERO − The BigInteger constant zero.
Live Demo
import java.math.BigInteger;

public class Tester {
   public static void main(String[] args) {
      // create 3 BigInteger objects
      BigInteger bi1, bi2;
 
      // assign values to bi1, bi2
      bi1 = new BigInteger("123");
      bi2 = new BigInteger("-50");

      System.out.println("Absolute value of "          
         + bi2 + " is " + bi2.abs());
      System.out.println("Result of addition of "          
         + bi1 + ", "+ bi2 + " is " +bi1.add(bi2));
      System.out.println("Result of and opearation of "
         + bi1 + ", "+ bi2 + " is " +bi1.and(bi2));
      System.out.println("Result of bitCount opearation of "
         + bi1 + " is " +bi1.bitCount());
      System.out.println("Result of compareTo opearation of "
         + bi1 + ", "+ bi2 + " is " +bi1.compareTo(bi2));
   }
}
Absolute value of -50 is 50
Result of addition of 123, -50 is 73
Result of and opearation of 123, -50 is 74
Result of bitCount opearation of 123 is 6
Result of compareTo opearation of 123, -50 is 1
Cordova - Battery Status

This Cordova plugin is used for monitoring device's battery status. The plugin will monitor every change that happens to device's battery.
To install this plugin, we need to open the command prompt window and run the following code.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-pluginbattery-status 

When you open the index.js file, you will find the onDeviceReady function. This is where the event listener should be added.
window.addEventListener("batterystatus", onBatteryStatus, false); 

We will create the onBatteryStatus callback function at the bottom of the index.js file.
function onBatteryStatus(info) { 
   alert("BATTERY STATUS:  Level: " + info.level + " isPlugged: " + info.isPlugged); 
}
When we run the app, an alert will be triggered. At the moment, the battery is 100% charged.
When the status is changed, a new alert will be displayed. The battery status shows that the battery is now charged 99%.
If we plug in the device to the charger, the new alert will show that the isPlugged value is changed to true.
This plugin offers two additional events besides the batterystatus event. These events can be used in the same way as the batterystatus event.
batterylow
The event is triggered when the battery charge percentage reaches low value. This value varies with different devices.
batterycritical
The event is triggered when the battery charge percentage reaches critical value. This value varies with different devices.

    45 Lectures 
     2 hours 

 Skillbakerystudios

    16 Lectures 
     1 hours 

 Nilay Mehta
 Print
 Add Notes
 Bookmark this page