code-rag-bench/online-tutorials huggingface dataset:
Delegates in C#

A delegate in C# is a reference to the method. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Let us see how to declare delegates in C#.
delegate <return type> <delegate-name> <parameter list>
Let us see an example to learn how to work with Delegates in C#.
 Live Demo
using System;
using System.IO;
namespace DelegateAppl {
   class PrintString {
      static FileStream fs;
      static StreamWriter sw;
      // delegate declaration
      public delegate void printString(string s);
      // this method prints to the console
      public static void WriteToScreen(string str) {
         Console.WriteLine("The String is: {0}", str);
      }
      // this method prints to a file
      public static void WriteToFile(string s) {
         fs = new FileStream("c:\\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }
      // this method takes the delegate as parameter and uses it to
      // call the methods as required
      public static void sendString(printString ps) {
         ps("Hello World");
      }
      static void Main(string[] args) {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}
The String is: Hello World
DAX Logical - IF function

Checks a condition given as the first argument of the function and returns one value if the condition is TRUE and returns another value if the condition is FALSE.
IF (<logical_test>, <value_if_true>, [<value_if_false>])

logical_test
Any value or expression that can be evaluated to TRUE or FALSE.
value_if_true
The value that is returned if the logical test is TRUE.
value_if_false
Optional.
The value that is returned if the logical test is FALSE.
If omitted, FALSE is returned.
Any type of value that can be returned by an expression.
If value_if_false is omitted, IF treats it as an empty string value ("").
If value_if_false is omitted, IF treats it as an empty string value ("").
If the value referenced in the logical_test is a column, IF returns the value that corresponds to the current row. Thus, the IF function returns a column of all the values resulting from the logical test corresponding to each of the rows.
If the value referenced in the logical_test is a column, IF returns the value that corresponds to the current row. Thus, the IF function returns a column of all the values resulting from the logical test corresponding to each of the rows.
If you have 3 values to return, then you can nest the IF functions.
If you have 3 values to return, then you can nest the IF functions.
=IF([Country]="USA",1,0)
Returns a calculated column of 1’s and 0’s. These values can be summed up.
If you name the column as USA Medals, then you can write the following −
then you can write the following -

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
C++ program to implement Inverse Interpolation using Lagrange Formula

In this tutorial, we will be discussing a program to implement Inverse Interpolation using Lagrange formula.
Inverse Interpolation is defined as the method of finding the value of an independent variable from the given value of dependent value lying between two tabulated set of values for an unknown function.
#include <bits/stdc++.h>
using namespace std;
//structuring the values of x and y
struct Data {
   double x, y;
};
//calculating inverse interpolation
double calc_invinter(Data d[], int n, double y){
   double x = 0;
   int i, j;
   for (i = 0; i < n; i++) {
      double xi = d[i].x;
      for (j = 0; j < n; j++) {
         if (j != i) {
            xi = xi * (y - d[j].y) / (d[i].y - d[j].y);
         }
      }
      x += xi;
   }
   return x;
}
int main(){
   Data d[] = {
      { 1.27, 2.3 },
      { 2.25, 2.95 },
      { 2.5, 3.5 },
      { 3.6, 5.1 }
   };
   int n = 6;
   double y = 4.5;
   cout << "Value of x (y = 4.5) : " << calc_invinter(d, n, y) << endl;
   return 0;
}
Value of x (y = 4.5) : 2.51602
Python Program for cube sum of first n natural numbers

In this article, we will learn about the solution and approach to solve the given problem statement.
Problem statement −Given an input n, we need to print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.
Here we will discuss two approach to reach the solution of the problem statement −
Brute-force approach using loops.
Mathematical solution of sum of n numbers.
Approach 1 −Computing sum of each term by adding by iterating over the numbers
 Live Demo
def sumOfSeries(n):
   sum = 0
   for i in range(1, n+1):
      sum +=i*i*i
   return sum
# Driver Function
n = 3
print(sumOfSeries(n))
36
Approach 2 −Computation using mathematical formula
Here we will be using mathematical sum formulae which is aldready derived for the cubic sum of natural numbers.
Sum = ( n * (n + 1) / 2 ) ** 2
 Live Demo
def sumOfSeries(n):
   x = (n * (n + 1) / 2)
   return (int)(x * x)
# main
n = 3
print(sumOfSeries(n))
36
In this article, we learned about the approach to compute the cube sum of first n natural numbers.
How to invoke the Firefox browser in Selenium with python?

We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package.
For invoking the Firefox browser, we have to select the Firefox class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation.
Every firefox browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser.
Next we need to download the gecko driver version as per our browser version. The path of the geckodriver.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser.
Code Implementation
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to close the browser
driver.close()
How to center an image in canvas Python Tkinter

Let us consider that we are creating a GUI-based application using Tkinter and we
want to load an image in the Tkinter canvas.
By default, the canvas loads the images according to its width and height.
However, we can manipulate the position of an image in any direction
(N,S,E,W,NS, EW, etc.) by passing the ‘Direction’ value in the anchor parameter.
An anchor is a parameter which is invoked along with the image function; it defines
the direction or position of the image in the canvas.
By using anchor parameters, we can align the text and images in any direction. For now, we will create an image label by using the Label function such that,
Label(root, text= " ", other Options(color, width,height,..))
After creating the image label using the above function, we will adjust its position
using the ‘anchor’ property. Since we have to place the image at the center, we will pass the value of anchor as “CENTER”.
#import the tkinter library in the notebook

from tkinter import *
#creating an instance of the tkinter canvas
win= Tk()
#define the size of the window
win.geometry("700x150")

#define the image label having some properties

label_img= Label(win, text= "Hello World", font= "sans-serif",relief=
"solid",width= 20, height= 8, anchor= CENTER)
label_img.pack()
#displaying the canvas without closing the window
win.mainloop()
Running the above snippet will generate the output and place the image at the
center of the canvas.
C program to demonstrate fork() and pipe()

In this problem, we will demonstrate fork() and pipe(). Here we will create a C program for Linux that will concatenate two string, using 2 processes one will take input and send it to others which will concatenate the string with a predefined string and return the concatenated string.
First lets recap fork() and pipe()
fork() − it creates a child process, this child process ahs a new PID and PPID.
pipe() is a Unix, Linux system call that is used for inter-process communication.
Let’s take an example for understanding the problem,
Learn programming
Predefined string: at tutorialspoint
Learn programming at tutorialspoint
P1 take input of string “learn programming”
Sends it to P2 using the pipe.
P2 concatenates the strings and sends back to p1 which prints it.
In the program, we will create two processes, say P1 and P2 using the fork() function. It has the following three return values which show the state of the program.
return value < 0, process creation failed.
return value = 0, child process.
return value > 0, which will be the process ID of the child process to the parent process i.e. The parent process will be executed.
We will create two pipes one for communicating from P1 to P2 and other from P2 to P1 as the pipe is one way.
C program to demonstrate fork() and pipe()
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main(){
   int p12[2];
   int p21[2];
   char fixed_str[] = " at tutorialspoint";
   char input_str[100];
   pid_t P;
   if (pipe(p12)==-1 || pipe(p21)==-1 ){
      fprintf(stderr, "Filed to create pipe" );
      return 1;
   }
   scanf("%s", input_str);
   P = fork();
   if (P < 0){
      fprintf(stderr, "fork Failed" );
      return 1;
   }
   else if (P > 0){
      char concat_str[100];
      close(p12[0]);
      write(p12[1], input_str, strlen(input_str)+1);
      close(p12[1]);
      wait(NULL);
      close(p21[1]);
      read(p21[0], concat_str, 100);
      printf("Concatenated string %s\n", concat_str);
      close(p21[0]);
   }
   else{
      close(p12[1]);
      char concat_str[100];
      read(p12[0], concat_str, 100);
      int k = strlen(concat_str);
      int i;
      for (i=0; i<strlen(fixed_str); i++)
      concat_str[k++] = fixed_str[i];
      concat_str[k] = '\0';
      close(p12[0]);
      close(p21[0]);
      write(p21[1], concat_str, strlen(concat_str)+1);
      close(p21[1]);
      exit(0);
   }
}
Concatenated string Learn at tutorialspoint
How to set the height of an element with JavaScript?

Use the height property to set the height of an element. You can try to run the following code to set the height of a button with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <h1>Heading 1</h1>
      <p>This is Demo Text.</p>
      <button type="button" id="myID" onclick="display()">Update Height</button>
      <script>
         function display() {
            document.getElementById("myID").style.height = "100px";
         }
      </script>
   </body>
</html>
How to loop through arrays in JavaScript objects?

Looping through arrays inside objects is the same as looping through objects. We have to use 'for...in' loop to loop through arrays inside objects.
In the following example, an object "obj" is defined. This object has an array in it. Using 'for...in' loop, the elements in that array are displayed as shown in the output. 
Live Demo
<html>
<body>
   <script>
      var res = ""
      var obj = {
            "name":"Elon musk",
            "age":48,
            "companies": [
               {"location":"Newyork", "name":["Tesla", "Spacex", "Neuralink"]},        
               {"location":"Florida", "name":["paypal", "solarcity"]},
            ]
            }
            for (var i in obj.companies) {
               res += "The companies in " + " "+ obj.companies[i].location + "</br>";
               for (var j in obj.companies[i].name) {
                  res += obj.companies[i].name[j] + "</br>";
               }
            }
            document.write(res);
      </script>
</body>
</html>
The companies in Newyork
Tesla
Spacex
Neuralink
The companies in Florida
paypal
solarcity
How is Session Management done in JSP?

JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across.
a one-page request or
visit to a website or
store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().
Python – Spelling checker using Enchant

23 Jun, 2021
Enchant is a module in Python, which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in the dictionary or not.
Enchant can also be used to check the spelling of words. The check() method returns True if the passed word is present in the language dictionary, else it returns False. This functionality of the check() method can be used to spell check words.
The suggest() method is used to suggest the correct spelling of the incorrectly spelled word.  
Python3
# import the enchant moduleimport enchant # create dictionary for the language# in use(en_US here)dict = enchant.Dict("en_US") # list of wordswords = ["cmputr", "watr", "study", "wrte"] # find those words that may be misspelledmisspelled =[]for word in words:    if dict.check(word) == False:        misspelled.append(word)print("The misspelled words are : " + str(misspelled)) # suggest the correct spelling of# the misspelled wordsfor word in misspelled:    print("Suggestion for " + word + " : " + str(dict.suggest(word)))
Output :  
The misspelled words are : ['cmputr', 'watr', 'wrte']
Suggestion for cmputr : ['computer']
Suggestion for watr : ['wart', 'watt', 'wat', 'war', 'water', 'wat r']
Suggestion for wrte : ['rte', 'write', 'wrote', 'wert', 'wite', 'w rte']
 
ysachin2314
arorakashish0911
Python Enchant-module
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
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
What is the max size of localStorage values?

28 Jan, 2022
Currently localStorage only supports strings as values, and the objects need to be converted to JSON strings before they are stored in the localStorage. Data stored using local storage isn’t sent back to the server (unlike cookies, ). All the data stays on the client-side, thus there is a defined limitation regarding the length of the values, and we can currently store from 2 MB to 10 MB size of data depending upon the browser we use.
Syntax:
localStorage.setItem ( 'abc', 10 ); 
// this integer 10 gets converted to a string "10" 
// and then stored in localStorage variable named "abc".
Code:
This code is to calculate the size of localStorage variable.
javascript
<!DOCTYPE html><html><head><title>Page Title</title>  <script>    //this script is to find the size of localStorage         function func1(num)    {        return new Array((num * 1024) + 1).join('a')    }     // Determine the size of localStorage if it's not set     if (!localStorage.getItem('size')) {    var i = 0;    try {        // Test up to 10 MB        for (i = 0; i <= 10000; i += 250) {            localStorage.setItem('test', func1(i));        }        } catch (e) {        localStorage.removeItem('test');        localStorage.setItem('size', i ? i - 250 : 0);        }    }         // when window is loaded this function is// called and the size of localStorage is calculated   window.onload = function calculate(){    var el = document.getElementById('size');           el.innerHTML = localStorage.getItem('size');}   </script></head><body><div >     localStorage limit in your Browser is     <span id="size">...</span> KBs.</div></body></html>
Output:
localStorage limit in your Browser is 5000 KBs.
Explanation:
This javascript code will run by adding continuously increasing length strings until the browser engine throws an exception. After this point, it will clear the test data and will set a size key in localStorage that will store the size of localStorage in kilobytes (KBs).
Reference: https://www.geeksforgeeks.org/html-dom-storage-setitem-method/  
adnanirshad158
HTML5
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python PIL | Kernel() method

14 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.
PIL.ImageFilter.Kernel() Create a convolution kernel. The current version only supports 3×3 and 5×5 integer and floating point kernels.
Syntax: PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)
Parameters:size – Kernel size, given as (width, height). In the current version, this must be (3, 3) or (5, 5).kernel – A sequence containing kernel weights.scale – Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.offset – Offset. If given, this value is added to the result, after it has been divided by the scale factor.
Returns type: An image.
Image Used:
     # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter   # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG")   # applying the Kernel filterim2 = im1.filter(ImageFilter.Kernel((3, 3),      (-1, -1, -1, -1, 9, -1, -1, -1, -1), 1, 0))  im2 = im2.show()                 
Output:
Another example: Here change kernel value to obtain output, we can change other parameters as well.
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter   # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter   # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG")   # applying the Kernel filterim2 = im1.filter(ImageFilter.Kernel((3, 3),          (-1, -1, -1, -1, 11, -2, -2, -2, -2), 1, 0))  im2 = im2.show()                 
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
XSLT <if>

<xsl:if> tag specifies a conditional test against the content of nodes.
Following is the syntax declaration of <xsl:if> element.
<xsl:if 
  test = boolean-expression > 
</xsl:if> 

test
The condition in the xml data to test.
Parent elements
xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements
Child elements
xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:for-each, xsl:if, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements
This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks marks to be greater than 90 and then prints the student(s) details.
students.xml
<?xml version = "1.0"?> 
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?> 
<class> 
   <student rollno = "393"> 
      <firstname>Dinkar</firstname> 
      <lastname>Kad</lastname> 
      <nickname>Dinkar</nickname> 
      <marks>85</marks> 
   </student> 
   <student rollno = "493"> 
      <firstname>Vaneet</firstname> 
      <lastname>Gupta</lastname> 
      <nickname>Vinni</nickname> 
      <marks>95</marks> 
   </student> 
   <student rollno = "593"> 
      <firstname>Jasvir</firstname> 
      <lastname>Singh</lastname> 
      <nickname>Jazz</nickname> 
      <marks>90</marks> 
   </student> 
</class>
students.xsl
<?xml version = "1.0" encoding = "UTF-8"?> 
<xsl:stylesheet version = "1.0" 
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
   <xsl:template match = "/"> 
      <html> 
         <body> 
            <h2>Students</h2> 
            <table border = "1"> 
               <tr bgcolor = "#9acd32"> 
                  <th>Roll No</th> 
                  <th>First Name</th> 
                  <th>Last Name</th> 
                  <th>Nick Name</th> 
                  <th>Marks</th> 
               </tr> 
					
               <xsl:for-each select = "class/student"> 
					
                  <xsl:if test = "marks > 90"> 
                     <tr> 
                        <td><xsl:value-of select = "@rollno"/></td> 
                        <td><xsl:value-of select = "firstname"/></td> 
                        <td><xsl:value-of select = "lastname"/></td> 
                        <td><xsl:value-of select = "nickname"/></td> 
                        <td><xsl:value-of select = "marks"/></td>
LocalTime format() method in Java with Examples

03 Dec, 2018
The format() method of a LocalTime class is used to format this time using the specified formatter passed as a parameter. This method formats this time based on passed formatter to a string.
Syntax:
public String format(DateTimeFormatter formatter)

Parameters: This method accepts a single parameter formatter which is the specified formatter. It should not be null.
Return value: This method returns the formatted time string.
Exception: This method throws a DateTimeException if an error occurs during printing.
Below programs illustrate the format() method:
Program 1:
// Java program to demonstrate// LocalTime.format() method  import java.time.*;import java.time.format.DateTimeFormatter;  public class GFG {    public static void main(String[] args)    {          // create a LocalTime Objects        LocalTime time            = LocalTime.parse("03:18:23");          // create formatter Object        DateTimeFormatter formatter            = DateTimeFormatter.ISO_TIME;          // apply format        String value = time.format(formatter);          // print result        System.out.println("value : "                           + value);    }}
value : 03:18:23

Program 2:
// Java program to demonstrate// LocalTime.format() method  import java.time.*;import java.time.format.DateTimeFormatter;  public class GFG {    public static void main(String[] args)    {          // create a LocalTime Objects        LocalTime time            = LocalTime.parse("23:59:59");          // create formatter Object for ISO_LOCAL_TIME        DateTimeFormatter formatter            = DateTimeFormatter.ISO_LOCAL_TIME;          // apply format        String value = time.format(formatter);          // print result        System.out.println("value : "                           + value);    }}
value : 23:59:59

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#format(java.time.format.DateTimeFormatter)
Java-Functions
Java-LocalTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Introduction to Java
Java Program to Find the Volume and Surface Area of Cuboid

01 Dec, 2020
A Cuboid is a 3-dimensional box-like figure represented in the 3-dimensional plane. A cuboid has 6 rectangle-shaped faces. Each face meets another face at 90 degrees each. Three sides of cuboid meet at the same vertex. Since it is made up of 6 rectangle faces, it has length, width and height of different dimension. Given the dimensions of the cuboid, find the Surface area and Volume of a cuboid. The formula’s to calculate the area and volume are given below.
Examples:
Input : 20 15 10
Output : Surface Area = 1300
         Volume = 3000 
  

Input : 30 5 10
Output : Surface Area = 1000
         Volume = 1500
Formulas:
Volume = length * breadth * height
Surface Area of Cuboid = 2(length * breadth + breadth * height + height * length)
Approach :
Given the dimensions of the cone, say length L, height H and breadth B of a cuboid.
Calculate Volume and Surface Area
Example 1:
Java
// Java Program to Find the Volume and Surface Area of// Cuboids  import java.io.*;  class GFG {    public static void main(String[] args)    {        // specify L,B and H        double L = 20, B = 15, H = 10;                // calculate SurfaceArea        double SurfaceArea = 2 * (L * B + B * H + H * L);                // calculate Volume        double Volume = L * B * H;                System.out.println(            "The Surface area of cuboid is : "            + SurfaceArea);                System.out.println("The Volume of the cuboid is : "                           + Volume);    }}
The Surface area of cuboid is : 1300.0
The Volume of the cuboid is : 3000.0
Example 2:
Java
import java.io.*;  class GFG {    public static void main(String[] args)    {        // specify L,B and H        double L = 30, B = 5, H = 10;                // calculate SurfaceArea        double SurfaceArea = 2 * (L * B + B * H + H * L);                // calculate Volume        double Volume = L * B * H;                System.out.println(            "The Surface area of cuboid is : "            + SurfaceArea);                System.out.println("The Volume of the cuboid is : "                           + Volume);    }}
The Surface area of cuboid is : 1000.0
The Volume of the cuboid is : 1500.0
Time Complexity = O(n)
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
What do you mean by static memory allocation in C programming?

Memory can be allocated in the following two ways −
Static variable defines in one block of allocated space, of a fixed size. Once it is allocated, it can never be freed.
Memory is allocated for the declared variable in the program.
The address can be obtained by using ‘&’ operator and can be assigned to a pointer.
The address can be obtained by using ‘&’ operator and can be assigned to a pointer.
The memory is allocated during compile time.
The memory is allocated during compile time.
It uses stack for maintaining the static allocation of memory.
It uses stack for maintaining the static allocation of memory.
In this allocation, once the memory is allocated, the memory size cannot change.
In this allocation, once the memory is allocated, the memory size cannot change.
It is less efficient.
It is less efficient.
The final size of a variable is decided before running the program, it will be called as static memory allocation. It is also called compile-time memory allocation.
We can't change the size of a variable which is allocated at compile-time.
Static memory allocation is generally used for an array. Let’s take an example program on arrays −
 Live Demo
#include<stdio.h>
main (){
   int a[5] = {10,20,30,40,50};
   int i;
   printf (“Elements of the array are”);
   for ( i=0; i<5; i++)
      printf (“%d, a[i]);
}
Elements of the array are
1020304050
Let’s consider another example to calculate sum and product of all elements in an array −
 Live Demo
#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int array[5]={10,20,30,40,50};
   int i,sum=0,product=1;
   //Reading elements into the array//
   //For loop//
   for(i=0;i<5;i++){
      //Calculating sum and product, printing output//
      sum=sum+array[i];
      product=product*array[i];
   }
   //Displaying sum and product//
   printf("Sum of elements in the array is : %d\n",sum);
   printf("Product of elements in the array is : %d\n",product);
}
Sum of elements in the array is : 150
Product of elements in the array is : 12000000
PL/SQL | User Input - GeeksforGeeks

03 Oct, 2018
Prerequisite – PL/SQL IntroductionIn PL/SQL, user can be prompted to input a value using & character. & can be used to prompt input for different data types. Consider, following table:
Following queries will create a new table named GFG in the database.
SQL> create table GFG (id number(4), author varchar2(50), 
                                          likes number(4)) 
Table created.
SQL> insert into GFG values(1, 'sam', 10);
1 row created.
SQL> insert into GFG values(2, 'maria', 30);
1 row created.
SQL> insert into GFG values(3, 'ria', 40);
1 row created. 
SQL> select * from GFG;
1. Numeric value –& is used to input numeric values from the user.
Syntax:
&value 
Example-1: Consider, the table GFG. Let us select a record with a given id. (Here, id is a numeric value)
SQL> select * from GFG where id=&id;
Enter value for id: 2
old 1: select * from GFG where id=&id
new 1: select * from GFG where id=2 
Example-2: Let us update a record with a given id. (Here, id is a numeric value)
SQL> update GFG set likes=50 where id=&id;
Enter value for id: 1
old 1: update GFG set likes=50 where id=&id
new 1: update GFG set likes=50 where id=1
1 row updated. 
SQL> select * from GFG; 
2. Text Value –& can also be used to input text values from the user.
Syntax:
'&value' 
Example-1: Consider, the table GFG. Let us select a record with a given author. (Here, author is a text value)
SQL> select * from GFG where author='&author';
Enter value for author: maria
old 1: select * from GFG where author='&author'
new 1: select * from GFG where author='maria' 
Example-2: Let us update a record with a given author. (Here, author is a text value)
SQL> update GFG set likes=10 where author='&author';
Enter value for author: sam
old 1: update GFG set likes=10 where author='&author'
new 1: update GFG set likes=10 where author='sam' 
1 row updated. 
SQL> select * from GFG; 
DBMS-SQL
SQL-PL/SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
CTE in SQL
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between Primary Key and Foreign Key
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
SQL | Views
How to create a function in MATLAB ? - GeeksforGeeks

26 May, 2021
A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functions which are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions.
Syntax:
function output_params = function_name(iput_params)
       % Statements
end
The function starts with the keyword function.
Returning variables of the function are defined in output_params
function_name specifies the name of the function
input_params are input arguments to the function
Below are some examples that depict how to use functions in MATLAB:
Example 1: Function with one output
The function calculates the mean of the input vector
Matlab
% Input vectorvalues = [12, 4, 8.9, 6, 3]; % function return mean of vector cfunction m = stat(x)    n = length(x);    m = sum(x)/n;end mean = stat(values)
 
 
Output :
 
mean = 6.7800
 
Example 2: Function with multiple outputs
 
The function calculates both nCr and nPr of inputs n and r.
 
Matlab
% Inputx = 3;y = 2; % Function return p = nPr and c = nCrfunction [p,c] = perm(n,r)    p = factorial(n)/factorial(n-r);    c = p*factorial(r);end [p,c] = perm(x,y)
 
 
Output :
 
p = 6
c = 12
 
Example 3: Multiple functions in a file
 
stat2() function calculates the standard deviation of the input vector.
stat1() calculates the mean of the input vector.
 
Matlab
values = [12, 4, 8.9, 6, 3]; % Function returns standard deviation of vector xfunction sd = stat2(x)    m = stat1(x);    n = length(x)    sd = sqrt(sum((x-m).^2/n));end % Function returns mean of vector xfunction m = stat1(x)    n = length(x);    m = sum(x)/n;end stat2(values)
Output :
n = 5
ans = 3.2975
Example 4: Function with no input_params
In this program, we will create the sin_plot() function that plots the sin() function
Matlab
% Plotting sin(x) functionfunction sin_plot()    x = linspace(0,2*pi,100);      y = sin(x);    plot(x,y);end sin_plot()
 
 
Output :
 
 
saurabh1990aror
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Convolution VS Correlation
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Laplacian of Gaussian Filter in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Forward and Inverse Fourier Transform of an Image in MATLAB
Differential or Derivatives in MATLAB
MATLAB Syntax
How to Remove Salt and Pepper Noise from Image Using MATLAB?
How to Normalize a Histogram in MATLAB?
How to Change Colours in Command Prompt in Windows? - GeeksforGeeks

23 Mar, 2020
Command Prompt is a neat command-line interpreter that comes in-built with the Windows operating system. Command prompt is still used for performing various functions such as, collecting information on the network state of the computer, troubleshooting the system, deleting files, formatting computers, etc.Customizing the Command Prompt according to your needs may end up resulting in your productivity and if you are a young learner who started learning about Command Prompt recently, you will want to check this out! First, it’s important to know for reference how a default Command Prompt terminal looks like, it looks something like this:
Here, we are going to change the color text and also the background color of cmd. Assume 2 variable x & y which are associated with specific colors.
color xy
‘x‘ represents the color of the Terminal’s background, whereas,‘y‘ represents the color of the font on the Command Prompt Terminal.
Following the HEX values of the colors supported by Command Prompt:
    0 = Black       8 = Gray
    1 = Blue        9 = Light Blue
    2 = Green       A = Light Green
    3 = Aqua        B = Light Aqua
    4 = Red         C = Light Red
    5 = Purple      D = Light Purple
    6 = Yellow      E = Light Yellow
    7 = White       F = Bright White

Example 1: Suppose we want a white background, so after referring to the color table above we will type, ‘f’ in place of ‘x’. Similarly, if we want a light purple colored font, we will type ‘d’ in place of ‘y’.(x & y are the variables we had assumed earlier).
color fd
Example 2: ‘0’ specifies the black color attribute, and since its typed at the place of ‘x’ i.e. it will be applied to background. ‘a’ specifies the light green color attribute, and since its typed at the place of ‘y’ i.e light green attribute will be applied to the font color.
color 0a
Note: To get all the related information on using color command in Command Prompt you can use the following command
color /?
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Add External JAR File to an IntelliJ IDEA Project?
Difference between RUN vs CMD vs ENTRYPOINT Docker Commands
How to Delete Temporary Files in Windows 10?
How to Convert Kotlin Code to Java Code in Android Studio?
How to Clone Android Project from GitHub in Android Studio?
How to Install Flutter on Windows?
How to Install Z Shell(zsh) on Linux?
Top 10 VS Code Extensions For Angular Developers
Autorun a Python script on windows startup
How to Access Localhost on Mobile Browsers?
Python | Convert a list of lists into tree-like dict - GeeksforGeeks

18 Feb, 2019
Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary.
Examples:
Input : [[1], [2, 1], [3, 1], [4, 2, 1], [5, 2, 1], [6, 3, 1], [7, 3, 1]]
Output : {1: {2: {4: {}, 5: {}}, 3: {6: {}, 7: {}}}}

Input : [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]
Output : {'A': {'C': {'D': {}}, 'B': {}}}

 Method #1 : Naive MethodThis is a Naive approach in which we use two for loops to traverse the list of lists. We initialize the empty dictionary ‘tree’ to currTree and each time we check if the key (list of list’s item) is included in the currTree or not. If not, include it in the currTree, otherwise do nothing. Finally, assign the currTree[key] to currTree.
# Python3 program to Convert a list# of lists into Dictionary (Tree form)  def formTree(list):    tree = {}    for item in list:        currTree = tree          for key in item[::-1]:            if key not in currTree:                currTree[key] = {}            currTree = currTree[key]                  return tree  # Driver Codelst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]print(formTree(lst))
{'A': {'B': {}, 'C': {'D': {}}}}

 Method #2 : Using reduce()The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We will use reduce() to traverse the dictionary and reuse getTree() to find the location to store the value for setTree(). All but the last element in mapList is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key.
# Python3 program to Convert a list# of lists into Dictionary (Tree form)  from functools import reducefrom operator import getitem  def getTree(tree, mappings):    return reduce(getitem, mappings, tree)      def setTree(tree, mappings):    getTree(tree, mappings[:-1])[mappings[-1]] = dict()  # Driver Codelst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]tree ={}for item in lst:    setTree(tree, item[::-1])  print(tree)
{'A': {'B': {}, 'C': {'D': {}}}}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Matplotlib.axes.Axes.text() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.text() function in axes module of matplotlib library is also used to add the text s to the axes at location x, y in data coordinates.
Syntax:
Axes.text(self, x, y, s, fontdict=None, withdash=, **kwargs)

Parameters: This method accept the following parameters that are described below:
s: This parameter is the text to be add.
xy: This parameter is the point (x, y) where text is to be placed.
fontdict: This parameter is an optional parameter and a dictionary to override the default text properties.
withdash: This parameter is also an optional parameter and creates a TextWithDash instance instead of a Text instance.
Returns: This method returns the text which is a created text instance..
Below examples illustrate the matplotlib.axes.Axes.text() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()ax.text(3, 4, 'GeeksforGeeks', style ='italic',        fontsize = 30, color ="green")  ax.set(xlim =(0, 8), ylim =(0, 8))ax.set_title('matplotlib.axes.Axes.text() Example',             fontsize = 14, fontweight ='bold')  plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()ax.set_xlabel('xlabel')ax.set_ylabel('ylabel')  ax.text(3, 8, 'GeeksforGeeks',        style ='italic',        fontsize = 30,        bbox ={'facecolor':'green',               'alpha':0.6, 'pad':20})  ax.text(3.5, 6, 'Python matplotlib Module',        fontsize = 15)  ax.text(3.5, 3, 'Axes Class - Text Function')  ax.text(0, 0, 'by-Shubham Singh',        verticalalignment ='bottom',        horizontalalignment ='left',        transform = ax.transAxes,        color ='green', fontsize = 5)      ax.set(xlim =(0, 10), ylim =(0, 10))ax.set_title('matplotlib.axes.Axes.text() Example',              fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Glob() function to find files recursively in Python?

To use Glob() to find files recursively, you need Python 3.5+. The glob module supports the "**" directive(which is parsed only if you pass recursive flag) which tells python to look recursively in the directories. 
import glob
for filename in glob.iglob('src/**/*', recursive=True):
    print(filename)
You can check the filename using whatever condition you want using an if statement. For older Python versions, you can use os.walk to recursively walk the directory and search the files. 
import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        print(file)
This will match the file name to the regex you specify and print their names.
Docker – LABEL Instruction

28 Oct, 2020
Labels are used in Dockerfile to help organize your Docker Images. Labels are key-value pairs and simply adds custom metadata to your Docker Images. Some key points associated with the LABEL instructions are as follows:
To include spaces inside a label, you can use quotes.
For multi line labels, you can use backslashes.
You can use more than one labels in a Docker Image.
Docker allows you to specify multiple labels in a single line.
Labels from parent Images are inherited to your Image.
If labels with same names exist even though they have different values, the last one overrides.
General syntax of LABEL instruction is as follows:
Syntax: LABEL <key-string>=<value-string> <key-string>=<value-string> ...

In this article, we will look at different ways to use Label instruction through a simple example. To do so follow the below steps:
Look at the template for the Dockerfile below:
FROM ubuntu:latest
LABEL "website.name"="geeksforgeeks website"
LABEL "website.tutorial-name"="docker"
LABEL website="geeksforgeeks"
LABEL desc="This is docker tutorial with \
geeksforgeeks website"
LABEL tutorial1="Docker" tutorial2="LABEL INSTRUCTION"

In the above Dockerfile, we have shown different ways to use LABEL instruction.
sudo docker build -t label-demo .

sudo docker run -it label-demo bash

To check the labels of a particular Image, you can use the Docker Inspect command.
Start the Docker Container.
sudo docker start <container-id>

Execute the Inspect Command.
sudo docker inspect <container-id>

Inside the LABELS object, you can find all the labels associated with the image that you have specified inside your Dockerfile.
To conclude, in this article, we discussed how to use the LABEL instruction in your Dockerfile and create your Image. We also saw the different ways using which you can specify the LABEL Instruction. Finally, we built and ran the Docker Image and Inspected the Container.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Extract Unique values dictionary values

22 Apr, 2020
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sorted() + set comprehension + values()The combination of above functionalities can be used to perform this task. In this, we extract all the values using values() and set comprehension is used to get unique values compiled in list.
# Python3 code to demonstrate working of # Extract Unique values dictionary values# Using set comprehension + values() + sorted()  # initializing dictionarytest_dict = {'gfg' : [5, 6, 7, 8],             'is' : [10, 11, 7, 5],             'best' : [6, 12, 10, 8],             'for' : [1, 2, 5]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Extract Unique values dictionary values# Using set comprehension + values() + sorted()res = list(sorted({ele for val in test_dict.values() for ele in val}))  # printing result print("The unique values list is : " + str(res)) 
The original dictionary is : {‘gfg’: [5, 6, 7, 8], ‘best’: [6, 12, 10, 8], ‘is’: [10, 11, 7, 5], ‘for’: [1, 2, 5]}The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
 
Method #2 : Using chain() + sorted() + values()This performs the task in similar way. The difference is that the task of set comprehension is performed using chain().
# Python3 code to demonstrate working of # Extract Unique values dictionary values# Using chain() + sorted() + values()from itertools import chain  # initializing dictionarytest_dict = {'gfg' : [5, 6, 7, 8],             'is' : [10, 11, 7, 5],             'best' : [6, 12, 10, 8],             'for' : [1, 2, 5]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Extract Unique values dictionary values# Using chain() + sorted() + values()res = list(sorted(set(chain(*test_dict.values()))))  # printing result print("The unique values list is : " + str(res)) 
The original dictionary is : {‘gfg’: [5, 6, 7, 8], ‘best’: [6, 12, 10, 8], ‘is’: [10, 11, 7, 5], ‘for’: [1, 2, 5]}The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.