code-rag-bench/online-tutorials huggingface dataset:
EasyGUI – Code Box - GeeksforGeeks

14 Mar, 2022
Code Box : It is used to show and get the text to/from the user which is in form of code i.e not in word-wrap form, text can be edited using any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to alter the given text and a pair of “Ok”, “Cancel” button which is used confirm the text. It is similar to text box but used to show code text, below is how the enter box looks like  
 
In order to do this we will use codebox methodSyntax : codebox(message, title, text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is the editable textReturn : It returns the altered text and None if cancel is pressed  
Example : In this we will create a code box with editable text, and will show the specific text on the screen according to the altered text, below is the implementation  
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # long code texttext = """<gfg> EasyGUIis a module for very simple,very easy GUI programming in Python.EasyGUIis different from otherGUI generatorsin that EasyGUI is NOT event-driven. </gfg>"""         # creating a code boxoutput = codebox(message, title, text) # showing the outputprint("Altered Text ")print("================")print(output)
Output :  
 
Altered Text 
================
'gfg>
great
EasyGUI module
is a module for very simple,
very easy GUI programming in Python.
EasyGUI 
is different from otherGUI generators 
in that EasyGUI is NOT event-driven.

'/gfg>
Another Example : In this we will create a code box without editable text, and will show the specific text on the screen according to the altered text, below is the implementation  
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # creating a code boxoutput = codebox(message, title) # showing the outputprint("Altered Text ")print("================")print(output)
Output :  
 
Altered Text 
================
gfg
a
b
v
c
c
c


/gfg
 
sumitgumber28
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
sum() function in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Convert integer to string in Python
Print lists in Python (4 Different Ways)
What is the difference between Trim() and TrimStart() methods in C#?

A string method that removes all the leading and trailing whitespaces in a string.
For example, the string “jack sparrow“ would be returned as the following without leading and whitespaces using trim().
jack sparrow
The following is an example −
 Live Demo
using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         string str = " Amit ";
         Console.WriteLine(str);

         // trim
         Console.WriteLine("After removing leading and trailing whitespace...");
         string res = str.Trim();
         Console.WriteLine(res);

         Console.ReadKey();
      }
   }
}
Amit
After removing leading and trailing whitespace...
Amit
The TrimStart() method removes all leading occurrences of a set of characters specified in an array.
Let us see an example to remove all leading zeros −
 Live Demo
using System;
class Program {
   static void Main() {
      String str ="0009678".TrimStart(new Char[] { '0' } );
      Console.WriteLine(str);
   }
}
9678
Calculating Wind Chill Factor(WCF) or Wind Chill Index(WCI) in Python - GeeksforGeeks

07 Feb, 2018
Wind-chill or Windchill is the perceived decrease in air temperature felt by the body on exposed skin due to the flow of air. The effect of wind chill is to increase the rate of heat loss and reduce any warmer objects to the ambient temperature more quickly.Here is the standard formula that was adopted in 2001 by Canada, UK, and the US to compute and analyze the Wind Chill Index:
Twc(WCI) = 13.12 + 0.6215Ta – 11.37v+0.16 + 0.3965Tav+0.16where
Twc = Wind Chill Index (Based on Celsius temperature scale)Ta = Air Temperature (in degree Celsius)v = Wind Speed (in miles per hour)
Examples:
Input: 
Air Temperature = 28
Wind Speed = 80
Output: 30
Calculation done using the above formula:
WCI = 13.12 + 0.6215 * (28) - 
      11.37 * (80)**0.16 + 
      0.3965 * 28 * 80**0.16

Input: 
Air Temperature = 42
Wind Speed = 150
Output: 51
Calculation done using the above formula:
WCI = 13.12 + 0.6215 * (42) - 
      11.37 * (150)**0.16 + 
      0.3965 * 42 * 150**0.16

# Python program to calculate WCIimport math  # funtion to calculate WCIdef WC(temp, wi_sp):          # Calculating Wind Chill Index (Twc)    wci = 13.12+0.6215*temp- 11.37*math.pow(wi_sp, 0.16) + \          0.3965*temp*math.pow(wi_sp, 0.16)    return wci      # Taking the Air Temperature (Ta) temp = 42  # Taking the Wind Speed (v) wi_sp = 150  print("The Wind Chill Index is", int(round(WC(temp, wi_sp))))
Output:
The Wind Chill Index is 51

This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Count number of trailing zeros in Binary representation of a number using Bitset in C++

Given an integer num as input. The goal is to find the number of trailing zeroes in the binary representation of num using bitset.
A bitset stores the bits 0s and 1s in it. It is an array of bits.
For Example
num = 10
Count of number of trailing zeros in Binary representation of a number using
Bitset are: 1
The number 10 in binary is represented as 1010 so trailing zeroes in it is
1.
num = 64
Count of number of trailing zeros in Binary representation of a number using Bitset are: 6
The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6.
Approach used in the below program is as follows −
In this approach we are using bitset. We will set the bitset with num using |. Now traverse bitset using for loop, as soon as the first 1 is encountered then break the loop otherwise increment count for trailing zeroes.
Take an integer num as input.
Take an integer num as input.
Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset.
Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset.
Take the initial count as 0.
Take the initial count as 0.
Take a bitset arr.
Take a bitset arr.
Set it with num as arr |=num.
Set it with num as arr |=num.
Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop.
Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop.
Return count as result at the end of loop.
Return count as result at the end of loop.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int trailing_zeroes(int num){
   int count = 0;
   bitset<64> arr;
   arr |= num;
   for (int i = 0; i < 64; i++){
      if (arr[i] == 0){
         count++;
      } else {
         break;
      }
   }
   return count;
}
int main(){
   int num = 6;
   cout<<"Count of number of trailing zeros in Binary representation of a number using Bitset are: "<<trailing_zeroes(num);
   return 0;
}
If we run the above code it will generate the following output −
Count of number of trailing zeros in Binary representation of a number using Bitset are: 1
Assigning function to a variable in C++ - GeeksforGeeks

19 Apr, 2022
In C++, assigning a function to a variable and using that variable for calling the function as many times as the user wants, increases the code reusability. Below is the syntax for the same:
Syntax:
C++
// Syntax: // Below function is assigned to// the variable funauto fun = [&]() {    cout << "inside function"         << " variable";};
Program 1: Below is the C++ program to implement a function assigned to a variable:
C++
// C++ program to implement function// assigned to a variable #include <iostream>using namespace std; // Driver Codeint main(){    // Below function i.e., is    // assigned to the variable fun    auto fun        = [&]() {              cout << "Inside Function Variable";          };     // Call the function using variable    fun();     return 0;}
Inside Function Variable
Program 2: Below is the C++ program to implement a parameterized function assigned to a variable:
C++
// C++ program to implement parameterized// function assigned to a variable#include <iostream>using namespace std; // Driver Codeint main(){    // Passing i and j as 2 parameters    auto fun = [&](int i, int j) {        cout << "Parameterized Function";    };     // Call the function using variable    fun(4, 5);     return 0;}
Output:
Parameterized Function
Program 3: Below is the C++ program to implement a function assigned to a variable that returns a value:
C++
// C++ program to implement the function// assigned to a variable returning// some values#include <iostream>using namespace std; // Driver Codeint main(){    // Function taking 2 parameters    // and returning sum    auto sum = [&](int a, int b) {        return a + b;    };     // Call the function using variables    cout << "The sum is: "         << sum(4, 5);     return 0;}
The sum is: 9
rkbhola5
CPP-Basics
CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
How to Run R scripts in Jupyter. A short tutorial on how to install the... | by Angelica Lo Duca | Towards Data Science

The Jupyter Notebook is a Web application which permits to create live code in different languages. Usually, developers exploit the Jupyter Notebook to write code in Python. However, Jupyter also supports other programming languages, including Java, R, Julia, Matlab, Octave, Scheme, Processing, Scala and many others.
Jupyter does not provide any compiler or interpreter. Instead, it is a process which communicates with the actual compiler/interpreter. In practice, it sends the code to the compiler/interpreter and gets back the result.
In order to run a code snippet (in a given language) in a Jupyter cell, it is sufficient to install the corresponding kernel for that language.
In this tutorial, I illustrate how to install the Jupyter Kernel for the R software.
Firstly, I need to install the R software on your computer. I can download the R software from its official Web site. Once installed, I can open a terminal and launch R, simply by typing R on the console, followed by the Enter command.
Note: if you use Mac OS, you need to run the R software from the directory where R is installed. Typically, the directory is
/Library/Frameworks/R.framework/Versions/<version>/Resources/bin
where <version> indicates the R version. I can run R by typing the following command on the console:
./R
Once launched the R console, I must download the devtools package through the following command:
install.packages("devtools")
I select the mirror number (e.g. Italy is 48) and I press Enter.
Once the installation is complete, I can install the IRKernel from Github. I run the following command:
devtools::install_github("IRkernel/IRkernel")
It may happen that the previous command fails. In this case, I can force installation, through the following command:
devtools::install_github("IRkernel/IRkernel", force=TRUE)
After that I install the IRkernel:
IRkernel::installspec()
Now I can quit R by typing
quit()
and I can run Jupyter. When Jupyter opens in the browser, I can click on New, on the top right corner and select R as kernel. Happy Enjoyment :)
In this tutorial, I have illustrated how to install the R Kernel in Jupyter. The procedure is quite simple and fast.
If you still experience problems for installation, check out my Youtube tutorial on the installation.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github.
Passing Arrays as Function Arguments in C

If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters.
Formal parameters as a pointer −
void myFunction(int *param) {
   .
   .
   .
}
Formal parameters as a sized array −
void myFunction(int param[10]) {
   .
   .
   .
}
Formal parameters as an unsized array −
void myFunction(int param[]) {
   .
   .
   .
}
Now, consider the following function, which takes an array as an argument along with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows −
double getAverage(int arr[], int size) {

   int i;
   double avg;
   double sum = 0;

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }

   avg = sum / size;

   return avg;
}
Now, let us call the above function as follows −
#include <stdio.h>
 
/* function declaration */
double getAverage(int arr[], int size);

int main () {

   /* an int array with 5 elements */
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   /* pass pointer to the array as an argument */
   avg = getAverage( balance, 5 ) ;
 
   /* output the returned value */
   printf( "Average value is: %f ", avg );
    
   return 0;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000

As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no bounds checking for formal parameters.
 Print
 Add Notes
 Bookmark this page
How to have logarithmic bins in a Python histogram?

We can set the logarithmic bins while plotting histogram using plt.hist(bin="").
Create an array x, where range is 100.
Create an array x, where range is 100.
Plot a histogram using plt.hist() method. We can pass logarithmic bins using logarithmic bins that returns numbers spaced evenly on a log scale.
Plot a histogram using plt.hist() method. We can pass logarithmic bins using logarithmic bins that returns numbers spaced evenly on a log scale.
Get the current axes, creating one if necessary and set the X-axis scale.
Get the current axes, creating one if necessary and set the X-axis scale.
To show the figure, use plt.show() method.
To show the figure, use plt.show() method.
from matplotlib import pyplot as plt
import numpy as np

x = np.array(range(100))

plt.hist(x, bins=np.logspace(start=np.log10(10), stop=np.log10(15), num=10))
plt.gca().set_xscale("log")
plt.show()
How to invert the elements of a boolean array in Python? - GeeksforGeeks

17 Dec, 2020

Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0. 
Input : A=[true , true , false]
Output: A= [false , false , true]
Input: A=[0,1,0,1] 
Output: A=[1,0,1,0]
Method 1:
You can use simple if else method to invert the array. In the implementation shown below method you just need to check the value of each index in array if the value is true change it to false else change it to true. This is one of the simplest method you can use to invert elements of a boolean array.
Program:
Python3
 

 
 










a1 = ((0, 1, 0, 1)) 
a = list(a1) 
  
for x in range(len(a)): 
    if(a[x]): 
        a[x] = 0
    else: 
        a[x] = 1
  
print(a) 






Output:
[1, 0, 1, 0]
Method 2:
You can also use an inbuilt function of numpy library to invert the whole array.
Syntax:
np.invert(boolean[] a)
Program:
Python
 

 
 










import numpy as np 
  
  
a = np.array((True, True, False, True, False)) 
b = np.invert(a) 
print(b) 






Output:
[False False  True False  True]
Method 3:
We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all  0 bits to 1 and 1 to 0 to obtain the complement binary number. 
So in the boolean array for True or 1 it will result in -2 and for False or 0 it will result as  -1. And again by using if..else we can convert the array into or required answer.
Program:
Python3
 

 
 










a1 = ((0, 1, 0, 1)) 
a = list(a1) 
  
for x in range(len(a)): 
    # using Tilde operator(~) 
    a[x] = ~a[x] 
  
print(a) 






Output:
[-1, -2, -1, -2]

Picked


Python-datatype


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Callbacks in C - GeeksforGeeks

05 Mar, 2019
A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time [Source : Wiki]. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function.
In C, a callback function is a function that is called through a function pointer.
Below is a simple example in C to illustrate the above definition to make it more clear:
// A simple C program to demonstrate callback#include<stdio.h>  void A(){    printf("I am function A\n");}  // callback functionvoid B(void (*ptr)()){    (*ptr) (); // callback to A}  int main(){    void (*ptr)() = &A;          // calling function B and passing    // address of the function A as argument    B(ptr);     return 0;}
I am function A

In C++ STL, functors are also used for this purpose.
This article is contributed by Ranju Kumari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Subhajit Mandal
CPP-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
Function Pointer in C
rand() and srand() in C/C++
Substring in C++
fork() in C
Converting Strings to Numbers in C/C++
std::string class in C++
Enumeration (or enum) in C
Assembly - MOVS Instruction

The MOVS instruction is used to copy a data item (byte, word or doubleword) from the source string to the destination string. The source string is pointed by DS:SI and the destination string is pointed by ES:DI.
The following example explains the concept −
section	.text
   global _start        ;must be declared for using gcc
	
_start:	                ;tell linker entry point
   mov	ecx, len
   mov	esi, s1
   mov	edi, s2
   cld
   rep	movsb
	
   mov	edx,20	        ;message length
   mov	ecx,s2	        ;message to write
   mov	ebx,1	        ;file descriptor (stdout)
   mov	eax,4	        ;system call number (sys_write)
   int	0x80	        ;call kernel
	
   mov	eax,1	        ;system call number (sys_exit)
   int	0x80	        ;call kernel
	
section .data
s1 db 'Hello, world!',0 ;string 1
len equ $-s1

section	 .bss
s2 resb	20              ;destination
When the above code is compiled and executed, it produces the following result −
Hello, world!


    46 Lectures 
     2 hours 

 Frahaan Hussain

    23 Lectures 
     12 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to set the number of ticks in plt.colorbar in Matplotlib?

To set the number of ticks in a colorbar, we can take the following steps−
Create random data using numpy
Display the data as an image, i.e., on a 2D regular raster.
Make a colorbar using colorbar() method with an image scalar mappable object.
Set the ticks and tick labels of the colorbar using set_ticks() and set_ticklabels() methods.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
im = plt.imshow(data, cmap="copper")
cbar = plt.colorbar(im)
cbar.set_ticks([0.2, 0.4, 0.6, 0.8])
cbar.set_ticklabels(["A", "B", "C", "D"])
plt.show()
Are static local variables allowed in Java?

11 May, 2020
Unlike C/C++, static local variables are not allowed in Java. For example, following Java program fails in compilation with error “Static local variables are not allowed”
class Test {   public static void main(String args[]) {      System.out.println(fun());   }     static int fun()   {     static int x= 10;  //Error: Static local variables are not allowed     return x--;   }} 
In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
KarthickManickam
java-basics
Java-Output
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to bind the Escape key to close a window in Tkinter?

Tkinter Events are very useful for making an application interactive and functional. It provides a way to interact with the internal functionality of the application and helps them to rise whenever we perform a Click or Keypress event.
In order to schedule the events in tkinter, we generally use the bind('Button', callback) method. We can bind any key to perform certain tasks or events in the application. To bind the Esc key such that it will close the application window, we have to pass the Key and a callback event as the parameter in the bind(key, callback) method.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

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

# Define the style for combobox widget
style = ttk.Style()
style.theme_use('xpnative')

# Define an event to close the window
def close_win(e):
   win.destroy()
# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Times New Roman italic', 18), background="black", foreground="white")
label.place(relx=.5, rely=.5, anchor=CENTER)
ttk.Label(win, text="Now Press the ESC Key to close this window", font=('Aerial 11')).pack(pady=10)

# Bind the ESC key with the callback function
win.bind('<Escape>', lambda e: close_win(e))

win.mainloop()
Running the above code will display a window which can be closed immediately by pressing the "Esc" Key.
Now press the <Esc> key to close the window.
Python Program to Concatenate Two Dictionaries Into One

When it is required to concatenate two dictionaries into a single entity, the ‘update’ method can be used.
A dictionary is a ‘key-value’ pair.
Below is a demonstration for the same −
 Live Demo
my_dict_1 = {'J':12,'W':22}
my_dict_2 = {'M':67}
print("The first dictionary is :")
print(my_dict_1)
print("The second dictionary is :")
print(my_dict_2)
my_dict_1.update(my_dict_2)
print("The concatenated dictionary is :")
print(my_dict_1)
The first dictionary is :
{'J': 12, 'W': 22}
The second dictionary is :
{'M': 67}
The concatenated dictionary is :
{'J': 12, 'W': 22, 'M': 67}
Two dictionaries are defined, and are displayed on the console. 
The ‘update’ method is called on the first dictionary by passing second dictionary as parameter. 
This would help concatenate the dictionary. 
This is displayed on the console.
Overview of Benchmark Testing in Golang

25 Aug, 2020
In automation testing, most of the frameworks support only one among functionality testing and benchmark testing. But the Golang testing package provides many functionalities for a different type of testing including benchmark testing.
B is a type(struct) passed to Benchmark functions to manage benchmark timing and to specify the number of iterations to run. Basically benchmark test suite of the testing package gives the benchmark reports likes time consumed, number of iteration/request(i.e. execution of function) of the tested function.
Syntax:
func BenchmarkXxx(*testing.B)

All of the benchmark function is executed by go test command. BenchmarkResult contains the results of a benchmark run.
type BenchmarkResult struct {
    N         int           // The number of iterations.
    T         time.Duration // The total time taken.
    Bytes     int64         // Bytes processed in one iteration.
    MemAllocs uint64        // The total number of memory allocations; added in Go 1.1
    MemBytes  uint64        // The total number of bytes allocated; added in Go 1.1

    // Extra records additional metrics reported by ReportMetric.
    Extra map[string]float64 // Go 1.13
}

Example:
File: main.go
Go
package main  // function which return "geeks"func ReturnGeeks() string{    return "geeks";}  // main function of packagefunc main() {    ReturnGeeks()}
Test file: pkg_test.go
Go
package main  import (    "testing")  // function to Benchmark ReturnGeeks()func BenchmarkGeeks(b *testing.B) {    for i := 0; i < b.N; i++ {        ReturnGeeks()    }}
Command: 
go test -bench=.

where -bench=. is flag need to run the default benchmark test. You can manipulate different flags while testing.
Output:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Go Variables
Loops in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
time.Parse() Function in Golang With Examples
Golang | Goroutine vs Thread
Frequent Item set in Data set (Association Rule Mining)

09 Jun, 2022
Association Mining searches for frequent items in the data-set. In frequent mining usually the interesting associations and correlations between item sets in transactional and relational databases are found. In short, Frequent Mining shows which items appear together in a transaction or relation. Need of Association Mining: Frequent mining is generation of association rules from a Transactional Dataset. If there are 2 items X and Y purchased frequently then its good to put them together in stores or provide some discount offer on one item on purchase of other item. This can really increase the sales. For example it is likely to find that if a customer buys Milk and bread he/she also buys Butter. So the association rule is [‘milk]^[‘bread’]=>[‘butter’]. So seller can suggest the customer to buy butter if he/she buys Milk and Bread.
Support : It is one of the measure of interestingness. This tells about usefulness and certainty of rules. 5% Support means total 5% of transactions in database follow the rule.
 
Support(A -> B) = Support_count(A ∪ B)
Confidence: A confidence of 60% means that 60% of the customers who purchased a milk and bread also bought butter.
 
Confidence(A -> B) = Support_count(A ∪ B) / Support_count(A)
If a rule satisfies both minimum support and minimum confidence, it is a strong rule. 
Support_count(X) : Number of transactions in which X appears. If X is A union B then it is the number of transactions in which A and B both are present.
Maximal Itemset: An itemset is maximal frequent if none of its supersets are frequent.
Closed Itemset:An itemset is closed if none of its immediate supersets have same support count same as Itemset.
K- Itemset:Itemset which contains K items is a K-itemset. So it can be said that an itemset is frequent if the corresponding support count is greater than minimum support count.
Example On finding Frequent Itemsets – Consider the given dataset with given transactions. 
Lets say minimum support count is 3
Relation hold is maximal frequent => closed => frequent
1-frequent: {A} = 3; // not closed due to {A, C} and not maximal {B} = 4; // not closed due to {B, D} and no maximal {C} = 4; // not closed due to {C, D} not maximal {D} = 5; // closed item-set since not immediate super-set has same count. Not maximal 
2-frequent: {A, B} = 2 // not frequent because support count < minimum support count so ignore {A, C} = 3 // not closed due to {A, C, D} {A, D} = 3 // not closed due to {A, C, D} {B, C} = 3 // not closed due to {B, C, D} {B, D} = 4 // closed but not maximal due to {B, C, D} {C, D} = 4 // closed but not maximal due to {B, C, D} 
3-frequent: {A, B, C} = 2 // ignore not frequent because support count < minimum support count {A, B, D} = 2 // ignore not frequent because support count < minimum support count {A, C, D} = 3 // maximal frequent {B, C, D} = 3 // maximal frequent 
4-frequent: {A, B, C, D} = 2 //ignore not frequent </
kshitijjain2
simmytarika5
data mining
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery lose focus event

29 Jul, 2020
Lose focus event can occur mainly through focusout() and blur() method. Both of them lose focus when the method gets triggered. These events differ slightly from each other but all of them serve the main purpose of losing focus.Focusout() is often used in combination with focusin() and blur() is often used in combination with focus().
Note that focusout() method also gets triggered when child elements lose focus.
Syntax:
$(selector).focusout(function)
or
$(selector).blur(function)
Here, function is the parameter, which is optional and occurs when focusout() and blur() method get triggered.
Example 1: This example shows the use of focusout() to lose focus.
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script>          <script>        $(document).ready(function () {            $("div").focusin(function () {                $(this).css("background-color", "#008000");            });            $("div").focusout(function () {                $(this).css("background-color", "#FFFFFF");            });        });    </script></head>  <body>    <h1 style="color:green;">        GeeksforGeeks    </h1>      <div style="border: 1px dashed green;padding:10px;">        Course: <input type="text"><br>    </div>      <p>        Clicking outside the input text field enables         triggering of focusout event.    </p></body>  </html>
Output:
Normal Output:
When clicked inside the input text-field:
When clicked outside the text field, it gets back to normal:
Example 2: This example shows the use of blur() to lose focus.
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script>          <script>        $(document).ready(function () {            $("input").blur(function () {                alert("Losefocus event occurs");            });        });    </script></head>  <body>    <h1 style="color:Green;">        GeeksforGeeks    </h1>          <div style="border: 1px dashed green;padding:10px;">        Course: <input type="text"><br>      </div>          <p>        Clicking outside the input text field         enables triggering of blur event.    </p></body>  </html>
Output:Normal Output
When clicked inside the input text-field
When clicked outside the text field, it displays this pop-up
jQuery-Events
Picked
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
C++ program to create one rectangle class and calculate its area

Suppose we have taken length and breadth of two rectangles, and we want to calculate their area using class. So we can make a class called Rectangle with two attributes l and b for length and breadth respectively. And define another function called area() to calculate area of that rectangle.
So, if the input is like (10,9), (8,6), then the output will be 90 and 48 as the length and breadth of first rectangle is 10 and 9, so area is 10 * 9 = 90, and for the second one, the length and breadth is 8 and 6, so area is 8 * 6 = 48.
To solve this, we will follow these steps −
Define rectangle class with two attributes l and b
Define rectangle class with two attributes l and b
define input() function to take input for l and b
define input() function to take input for l and b
define area() function to return l * b, which is the area of that rectangle
define area() function to return l * b, which is the area of that rectangle
Let us see the following implementation to get better understanding −
#include <iostream>
using namespace std;
class Rectangle{
    private:
        int l, b;
    public:
        void input(int len, int bre){
            l = len;
            b = bre;
        }
        int area(){
            return l * b;
        }
};
int main(){
    Rectangle r1, r2;
    r1.input(10, 9);
    r2.input(8, 6);
    cout << "Area of r1: " << r1.area() << endl;
    cout << "Area of r2: " << r2.area() << endl;
}

(10, 9), (8, 6)
Area of r1: 90
Area of r2: 48
How to Join Strings in Golang?. There are multiple ways to join or... | by Shubham Chadokar | Towards Data Science

There are multiple ways to join or concat strings in the golang.
Let’s start with the easy one.
Originally published at https://schadokar.dev.
package mainimport ( "fmt")func main() { str1 := "Hello" // there is a space before World str2 := " World!"fmt.Println(str1 + str2)}
Output
Hello World!
The fmt package has Sprint, Sprintf and Sprintln function which can format the strings using the default or custom formats.
All the Sprint function are variadic functions.
Variadic functions can be called with any number of trailing arguments.
Sprint formats using the default formats and returns the resulting string.
Sprint accepts an empty interface. It means it can take n elements of any type. If no element of type string is passed then the resulting string will add a Space between the elements.
package mainimport ( "fmt")func main() {   num := 26   str := "Feb"   boolean := true   withStr := fmt.Sprint(num, str, boolean)   fmt.Println("With string: ", withStr)   withOutStr := fmt.Sprint(num, boolean)   fmt.Println("Without string: ", withOutStr)}
Output
With string: 26Febtrue Without string: 26 true
Sprintf formats according to a format specifier and returns the resulting string.
Format Specifiers
%v	the value in a default format %s	the uninterpreted bytes of the string or slice
Check all the available format specifier in the fmt package.
You can use the Sprintf function to create the connection string of the DB.
For example we will create a Postgres Connection URL.
Connection URL format: postgres://username:password@hostname/databasename
package mainimport ( "fmt")func main() {   dbname := "testdb"   username := "admin"   password := "test1234"   hostname := "localhost"   connectionURL := fmt.Sprintf("postgres://%s:%s@%v/%v", username, password, hostname, dbname)   fmt.Println(connectionURL)}
Output
postgres://admin:test1234@localhost/testdb
Sprintln formats the elements or arguments using the default formats. Spaces are added between the elements and a new line is added in the end.
package mainimport ( "fmt")func main() { str1 := "Hello" str2 := "Gophers!" msg := fmt.Sprintln(str1, str2) fmt.Println(msg)}
Output
Hello Gophers!
The golang standard library has provided a Join function in the strings package.
The Join function takes an array of strings and a separator to join them.
func Join(elems []string, sep string) string
The example has an array of weekdays. The Join function will return a string of weekdays separated by , .
Using Join you can convert an array of string to a string.
package mainimport ( "fmt" "strings")func main() {    weekdays := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}    // there is a space after comma    fmt.Println(strings.Join(weekdays, ", "))}
Output
Monday, Tuesday, Wednesday, Thursday, Friday
Originally published at https://schadokar.dev.
You can read my latest golang tutorial on my blog.
Design counter for given sequence - GeeksforGeeks

11 Dec, 2020
Prerequisite – CountersProblem – Design synchronous counter for sequence: 0 → 1 → 3 → 4 → 5 → 7 → 0, using T flip-flop.
Explanation – For given sequence, state transition diagram as following below:
State transition table logic:
State transition table for given sequence:
T flip-flop – If value of Q changes either from 0 to 1 or from 1 to 0 then input for T flip-flop is 1 else input value is 0.
Draw input table of all T flip-flops by using the excitation table of T flip-flop. As nature of T flip-flop is toggle in nature. Here, Q3 as Most significant bit and Q1 as least significant bit.
Find value of T3, T2, T1 in terms of Q3, Q2, Q1 using K-Map (Karnaugh Map):
Therefore,
T3 = Q2 
Therefore,
T2 = Q1 
Therefore,
T1 = Q2’ 
Now, you can design required circuit using expressions of K-maps:
sachinsinghbisht5
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
4-bit binary Adder-Subtractor
IEEE Standard 754 Floating Point Numbers
Difference between RAM and ROM
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Analog to Digital Conversion
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
time.Time.MarshalJSON() Function in Golang with Examples - GeeksforGeeks

28 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The MarshalJSON() function in Go language is used to implement the json.Marshaler interface. And the time here is a quoted-string which is in RFC 3339 format along with the sub-second precision attached if available. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) MarshalJSON() ([]byte, error)

Here, “t” is the stated time and two values of type “byte” and “error” are returned as output in this method.
Return value: It returns a byte slice that represents JSON encoding and it also returns an error occurred but if there are no errors then “nil” is returned.
Example 1:
// Golang program to illustrate the usage of// Time.MarshalJSON() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Defining t for MarshalJSON method    t := time.Date(2014, 11, 10, 14, 30, 12, 05, time.UTC)      // Calling MarshalJSON() method    encoding, error := t.MarshalJSON()      // Prints JSON's encoding    fmt.Printf("JSON's encoding: %v\n", encoding)      // Prints error    fmt.Printf("Error occurred: %v\n", error)}
Output:
JSON’s encoding: [34 50 48 49 52 45 49 49 45 49 48 84 49 52 58 51 48 58 49 50 46 48 48 48 48 48 48 48 48 53 90 34]Error occurred: <nil>
Example 2:
// Golang program to illustrate the usage of// Time.MarshalJSON() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Defining t for MarshalJSON method    t := time.Date(2022, 45, 67, 88, 67, 76, 903, time.UTC)      // Calling MarshalJSON() method    encoding, error := t.MarshalJSON()      // Prints JSON's encoding    fmt.Printf("JSON's encoding: %v\n", encoding)      // Prints error    fmt.Printf("Error occurred: %v\n", error)}
Output:
JSON’s encoding: [34 50 48 50 53 45 49 49 45 48 57 84 49 55 58 48 56 58 49 54 46 48 48 48 48 48 48 57 48 51 90 34]Error occurred: <nil>
Here, the “t” stated in the above code has values that are outside usual range but they are normalized while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Time Durations in Golang
Strings in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Defer Keyword in Golang
Loops in Go Language
Class and Object in Golang
Data Structures | Tree Traversals | Question 4 - GeeksforGeeks

28 Jun, 2021
What does the following function do for a given binary tree?
int fun(struct node *root){   if (root == NULL)      return 0;   if (root->left == NULL && root->right == NULL)      return 0;   return 1 + fun(root->left) + fun(root->right);}
(A) Counts leaf nodes(B) Counts internal nodes(C) Returns height where height is defined as number of edges on the path from root to deepest node(D) Return diameter where diameter is number of edges on the longest path between any two nodes.Answer: (B)Explanation: The function counts internal nodes.1) If root is NULL or a leaf node, it returns 0.2) Otherwise returns, 1 plus count of internal nodes in left subtree, plus count of internal nodes in right subtree.
See the following complete program.
#include <stdio.h>  struct node{  int key;  struct node *left, *right;};  int fun(struct node *root){   if (root == NULL)      return 0;   if (root->left == NULL && root->right == NULL)      return 0;   return 1 + fun(root->left) + fun(root->right);}  /* Helper function that allocates a new node with the   given key and NULL left and right pointers. */struct node* newNode(int key){  struct node* node = (struct node*)                       malloc(sizeof(struct node));  node->key = key;  node->left = NULL;  node->right = NULL;    return(node);}  /* Driver program to test above functions*/int main(){    /* Constructed binary tree is            1          /   \        2      3      /  \    /    4     5  8  */  struct node *root = newNode(1);  root->left        = newNode(2);  root->right       = newNode(3);  root->left->left  = newNode(4);  root->left->right = newNode(5);  root->right->left = newNode(8);    printf("%d", fun(root));    getchar();  return 0;}
Quiz of this Question
Data Structures
Data Structures-Tree Traversals
Tree Traversals
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count number of times each Edge appears in all possible paths of a given Tree
Data Structures | Linked List | Question 5
Data Structures | Linked List | Question 6
Difference between Singly linked list and Doubly linked list
Advantages and Disadvantages of Linked List
FIFO vs LIFO approach in Programming
C program to implement Adjacency Matrix of a given Graph
Data Structures | Graph | Question 9
Introduction to Data Structures
Data Structures | Stack | Question 1
Convert PDF to CSV using Python - GeeksforGeeks

02 Feb, 2021
Python is a high-level, general-purpose, and very popular programming language. Python programming language (the latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java.
In this article, we will learn how to convert a PDF File to CSV File Using Python. Here we will discuss various methods for conversion. For all methods, we are using an input PDF file.
Method 1:
Here will use the pdftables_api Module for converting the PDF file into any other format. The pdftables_api module is used for reading the tables in a PDF. It also allows us to convert PDF Files into another format.
Installation:
Open Command Prompt and type "pip install git+https://github.com/pdftables/python-pdftables-api.git"
It will install the pdftables_api Module
After Installation, you need an API KEY.
Go to PDFTables.com and signup, then visit the API Page to see your API KEY.
Approach:
Verify the API key.
For Converting PDF File Into CSV File we will use csv() method.
Syntax:
pdftables_api.Client('API KEY').csv(pdf_path, csv_path)
Below is the Implementation:
PDF File Used:
PDF FILE
Python3
# Import Moduleimport pdftables_api  # API KEY VERIFICATIONconversion = pdftables_api.Client('API KEY')  # PDf to CSV # (Hello.pdf, Hello)conversion.csv(pdf_file_path, output_file_path)
Output:
CSV FILE
Method 2:
Here will use the tabula-py Module for converting the PDF file into any other format. The tabula-py is a simple Python wrapper of tabula-java, which can read tables in a PDF. You can read tables from a PDF and convert them into a pandas DataFrame. tabula-py also enables you to convert a PDF file into a CSV, a TSV, or a JSON file.
Installation:
pip install tabula-py
Before we start, first we need to install java and add a java installation folder to the PATH variable.
Install java click here
Add java installation folder (C:\Program Files (x86)\Java\jre1.8.0_251\bin) to the environment path variable
Approach:
Read PDF file using read_pdf() method.
Then we will convert the PDF files into a CSV file using the to_csv() method.
Syntax:
read_pdf(PDF File Path, pages = Number of pages, **agrs)
Below is the Implementation:
PDF File Used:
PDF FILE
Python3
# Import Module import tabula  # Read PDF File# this contain a listdf = tabula.read_pdf(PDF File Path, pages = 1)[0]  # Convert into Excel Filedf.to_csv('Excel File Path')
Output:
CSV FILE
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
How to create MongoDB stored procedure?

The following is the syntax to create MongoDB stored procedure −
db.system.js.save
(
   {
      _id:"yourStoredProcedueName",
      value:function(argument1,....N)
      {
         statement1,
         .
         .
         N
      }
   }
);
Now implement the above syntax. The query to create a stored procedure is as follows −
> db.system.js.save
(
   {
      _id:"addTwoValue",
      value:function(a,b)
      {
         return a+b
      }
   }
);
The following is the output −
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "addTwoValue" })
Now you can call the stored procedure using eval(). The query is as follows −
> db.eval("return addTwoValue(100,25)");
125