code-rag-bench/online-tutorials huggingface dataset:
How to clone an element using jQuery?

To clone an element using jQuery, use the jQuery.clone() method. The clone() method clones matched DOM Elements and select the clones.
This is useful for moving copies of the elements to another location in the DOM.
You can try to run the following code to learn how to clone an element using jQuery:
Live Demo
<html>

   <head>
      <title>jQuery clone() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).clone().insertAfter(this);
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>    
</html>
Array elements that appear more than once in C?

Array is a container of elements of Same data types length needs to be defined beforehand. And an element can appear in any order and any number of times in an array. so in this program we will find elements that appear more than once in an array.
Problem description − We have given an array arr[] in which we have to find which of the element are repeating in the array an app to print them.
Let’s take an example to understand this better.
Input: arr[] = {5, 11, 11, 2, 1, 4, 2}
Output: 11 2
We have an array arr which contains some element firstly we would compare the element from the next element in the duplicate function which is used to find the repeated element in the array. In duplicate function we are using the loop to find the duplicate elements in the given array we will use if else condition to check the count of array elements from the array element occurred one time then the count will be 1 if occur more than one time then count will be incremented respectively if the count is more than 1 then the element will be printed on the screen.
Input : arr[], n the length of array.
Step 1 : For i -> 0 to n, Follow step 2,
Step 2 : For each element of the array. Do :
   Step 2.1 : For j -> i to n repeat step 2.2 - 2.3.
   Step 2.2 : if (arr[i] == arr[j]) -> print arr[i]
   Step 2.3 : else {// do nothing}
#include <stdio.h>
int main() {
   int arr[] = {21, 87, 212, 109, 41, 21};
   int n=7;
   printf("The repeat elements of the array are : ");
   int *count = (int *)calloc(sizeof(int), (n - 2));
   int i;
   for (i = 0; i < n; i++) {
      if (count[arr[i]] == 1)
         printf(" %d ", arr[i]);
      else
         count[arr[i]]++;
   }
   return 0;
}
The repeat elements of the array are : 21
How to convert a JavaScript array to C# array?

Let us say our JavaScript array is −
<script>
   var myArr = new Array(5);
   myArr[0] = "Welcome";
   myArr[1] = "to";
   myArr[2] = "the";
   myArr[3] = "Web";
   myArr[4] = "World";
</script>
Now, convert the array into a string using comma as a separator −
document.getElementById('demo1').value = myArr.join(',');
Now, take this to C# −
string[] str = demo.Split(",".ToCharArray());
The above converts the JavaScript array to C#.
Can we declare the variables of a Java interface private and protected?

Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
If the fields of the interface are private, you cannot access them in the implementing class.
If you try to declare the fields of an interface private, a compile time error is generated saying “modifier private not allowed here”.
In the following Java example, we are trying to declare the field and method of an interface private.
public interface MyInterface{
   private static final int num = 10;
   private abstract void demo();
}
On compiling, the above program generates the following error
MyInterface.java:2: error: modifier private not allowed here
   private static final int num = 10;
                          ^
MyInterface.java:3: error: modifier private not allowed here
   private abstract void demo();
^
2 errors
In general, the protected fields can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it.
Therefore, cannot declare the fields of an interface protected. If you try to do so, a compile time error is generated saying “modifier protected not allowed here”.
In the following Java example, we are trying to declare the field and method of an interface protected.
public interface MyInterface{
   protected static final int num = 10;
   protected abstract void demo();
}
MyInterface.java:2: error: modifier protected not allowed here
   protected static final int num = 10;
^
MyInterface.java:3: error: modifier protected not allowed here
   protected abstract void demo();
How to add accelerators to a menu item?

A menu is a list of options or commands presented to the user, typically menus contains items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus.
In JavaFX a menu is represented by the javafx.scene.control.Menu class, a menu item is represented by the javafx.scene.control.MenuItem class, And, the javafx.scene.control.MenuBar class represents a menu bar.
Accelerators are short cuts to menu Items. The MenuItem class contains a property named accelerator (of type KeyCombination), which associates a combination to the action of the current MenuItem.
You can set value to this property using the setAccelerator() method. Therefore, to set accelerator to a particular MenuItem, invoke the setAccelerator() method on it as shown below −
MenuItem item = new MenuItem("Exit", imgView3);
item.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCombination;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MenuItemAccelerators extends Application {
   @Override
   public void start(Stage stage) {
      //Creating image view files
      ImageView imgView1 = new ImageView("UIControls/open.png");
      imgView1.setFitWidth(20);
      imgView1.setFitHeight(20);
      ImageView imgView2 = new ImageView("UIControls/Save.png");
      imgView2.setFitWidth(20);
      imgView2.setFitHeight(20);
      ImageView imgView3 = new ImageView("UIControls/Exit.png");
      imgView3.setFitWidth(20);
      imgView3.setFitHeight(20);
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating menu Items
      MenuItem item1 = new MenuItem("Open File", imgView1);
      MenuItem item2 = new MenuItem("Save file", imgView2);
      MenuItem item3 = new MenuItem("Exit", imgView3);
      //Setting accelerators to the menu items
      item1.setAccelerator(KeyCombination.keyCombination("Ctrl+F"));
      item2.setAccelerator(KeyCombination.keyCombination("Ctrl+S"));
      item3.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(item1, item2, item3);
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      menuBar.setTranslateX(200);
      menuBar.setTranslateY(20);
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Menu Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Recursive sum of digits of a number formed by repeated appends in C++

Given two integers ‘number’ and ‘repeat’ as input. The goal is to calculate the sum of digits of the input number repeated ‘repeat’ number of times until the sum becomes a single digit. Do this till the obtained number with sum of digits becomes a single digit number. If the input number is 123 and repeat=2 than the sum of digits of 123123 will be
1+2+3+1+2+3=12 which is not a single digit number. Now the sum of digits of 12 is 1+2=3. Output will be 3
Input − number=32 repeat=3
Output − Recursive sum of digits of a number formed by repeated appends is: 6
Explanation − Sum of digits of 323232 is 3+2+3+2+3+2=15 and sum of digits of 15 is 1+5=6. 6 is a single digit number so output will be 6.
Input − number=81 repeat=4
Output − Recursive sum of digits of a number formed by repeated appends is: 9
Explanation − Sum of digits of 81818181 is 1+8+1+8+1+8+1+8=36 and sum of digits of 36 is 3+6=9. 9 is a single digit number so output will be 9.
Declare two integer type variables as number and repeat. Pass the data to the function as Recursive_Sum(number, repeat).
Declare two integer type variables as number and repeat. Pass the data to the function as Recursive_Sum(number, repeat).
Inside the function as Recursive_Sum(int number, int repeat)Declare an integer variable as total and set it with a repeat * sum(number);Return call to the function as sum(total).
Inside the function as Recursive_Sum(int number, int repeat)
Declare an integer variable as total and set it with a repeat * sum(number);
Declare an integer variable as total and set it with a repeat * sum(number);
Return call to the function as sum(total).
Return call to the function as sum(total).
Inside the function as sum(int number)Check IF number is 0 then return 0.Check IF number % 9 is 0 then return 9.ELSE, return number % 9
Inside the function as sum(int number)
Check IF number is 0 then return 0.
Check IF number is 0 then return 0.
Check IF number % 9 is 0 then return 9.
Check IF number % 9 is 0 then return 9.
ELSE, return number % 9
ELSE, return number % 9
Print the result.
Print the result.
#include <bits/stdc++.h>
using namespace std;
int sum(int number){
   if(number == 0){
      return 0;
   }
   if(number % 9 == 0){
      return 9;
   }
   else{
      return number % 9;
   }
}
int Recursive_Sum(int number, int repeat){
   int total = repeat * sum(number);
   return sum(total);
}
int main(){
   int number = 12;
   int repeat = 4;
   cout<<"Recursive sum of digits of a number formed by repeated appends is: "<<Recursive_Sum(number, repeat);
   return 0;
}
If we run the above code it will generate the following Output
Recursive sum of digits of a number formed by repeated appends is: 3
How to create a responsive form with CSS?

Following is the code to create a responsive form with CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
   font-family: Arial;
   font-size: 17px;
   padding: 8px;
}
* {
   box-sizing: border-box;
}
.Fields {
   display: flex;
   flex-wrap: wrap;
   padding: 20px;
   justify-content: space-around;
}
.Fields div {
   margin-right: 10px;
}
label {
   margin: 15px;
}
.formContainer {
   margin: 10px;
   background-color: #efffc9;
   padding: 5px 20px 15px 20px;
   border: 1px solid rgb(191, 246, 250);
   border-radius: 3px;
}
input[type="text"] {
   display: inline-block;
   width: 100%;
   margin-bottom: 20px;
   padding: 12px;
   border: 1px solid #ccc;
   border-radius: 3px;
}
label {
   margin-left: 20px;
   display: block;
}
.icon-formContainer {
   margin-bottom: 20px;
   padding: 7px 0;
   font-size: 24px;
}
.checkout {
   background-color: #4caf50;
   color: white;
   padding: 12px;
   margin: 10px 0;
   border: none;
   width: 100%;
   border-radius: 3px;
   cursor: pointer;
   font-size: 17px;
}
.checkout:hover {
   background-color: #45a049;
}
a {
   color: black;
}
span.price {
   float: right;
   color: grey;
}
@media (max-width: 657px) {
   .Fields {
      flex-direction: column-reverse;
   }
}
</style>
</head>
<body>
<h1 style="text-align: center;">Responsive Form Example</h1>
<div class="Fields">
<div>
<div class="formContainer">
<form>
<div class="Fields">
<div>
<h3>Register</h3>
<label for="fname">Full Name</label>
<input type="text" id="fname" name="firstname" />
<label for="email"> Email</label>
<input type="text" id="email" name="email" />
<label for="adr"> Address</label>
<input type="text" id="adr" name="address" />
</div>
<div>
<h3>Account Details</h3>
<label for="uname">Username</label>
<input type="text" id="uname" name="cardname" />
<label for="pass">Password</label>
<input type="text" id="pass" name="cardnumber" />
<div class="Fields">
<div>
<label for="accountAge">Account Age</label>
<input type="text" id="accountAge" name="accountAge" />
</div>
<div>
<label for="cvv">Security Question</label>
<input type="text" id="cvv" name="cvv" />
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
The above code will produce the following output on larger screens −
On smaller screen size the content will resize as follows −
What is the use of "from...import" Statement in Python?

The "from module import function" statement is used to import a specific function from a Python module. For example, if you want to import the sin function from the math library without importing any other function, you can do it as follows:
>>> from math import sin
>>> sin(0)
0.0
Note that you don't have to prefix sin with "math." as only sin has been imported and not math. Also you can alias imported functions. For example,
>>> from math import cos as cosine
>>> cosine(0)
1.0
How to create a hoverable dropdown menu with CSS?

Following is the code to create a hoverable dropdown menu with CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.menu-btn {
   background-color: #7e32d4;
   color: white;
   padding: 16px;
   font-size: 20px;
   font-weight: bolder;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   border: none;
}
.dropdown-menu {
   position: relative;
   display: inline-block;
}
.menu-content {
   display: none;
   position: absolute;
   background-color: #017575;
   min-width: 160px;
   z-index: 1;
}
.links {
   color: rgb(255, 255, 255);
   padding: 12px 16px;
   text-decoration: none;
   display: block;
   font-size: 18px;
   font-weight: bold;
   border-bottom: 1px solid black;
}
.links:hover {
   background-color: rgb(8, 107, 46);
}
.dropdown-menu:hover .menu-content {
   display: block;
}
.dropdown-menu:hover .menu-btn {
   background-color: #3e8e41;
}
</style>
</head>
<body>
<h2>Hover over the below dropdown button to open dropdown menu</h2>
<div class="dropdown-menu">
<button class="menu-btn">Open </button>
<div class="menu-content">
<a class="links" href="#">Contact Us</a>
<a class="links" href="#">Visit Us</a>
<a class="links" href="#">About Us</a>
</div>
</div>
</body>
</html>
The above code will produce the following output −
On hovering over the open button the dropdown menu will open as shown below −
How to count the total number of radio buttons in a page in Selenium with python?

We can count the total number of radio buttons in a page in Selenium with the help of find_elements method. While working on any radio buttons, we will always find an attribute type in the html code and its value should be radio.
This characteristic is only applicable to radio buttons on that particular page and to no other types of UI elements like edit box, link and so on.
To retrieve all the elements with attribute type = 'radio', we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned.
After the list of radio buttons are fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure.
Finally this length is printed on the console.
driver.find_elements_by_xpath("//input[@type='radio']")
Code Implementation for counting radio buttons.
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.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the radio buttons with type attribute in a list
chk =driver.find_elements_by_xpath("//input[@type='radio']")
# len method is used to get the size of that list
print(len(chk))
#to close the browser
driver.close()
Rust - Variables

A variable is a named storage that programs can manipulate. Simply put, a variable helps programs to store values. Variables in Rust are associated with a specific data type. The data type determines the size and layout of the variable's memory, the range of values that can be stored within that memory and the set of operations that can be performed on the variable.
In this section, we will learn about the different rules for naming a variable.
The name of a variable can be composed of letters, digits, and the underscore character.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore.
It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because Rust is case-sensitive.
Upper and lowercase letters are distinct because Rust is case-sensitive.
The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable.
The syntax for declaring a variable is given below.
let variable_name = value;            // no type specified
let variable_name:dataType = value;   //type specified

fn main() {
   let fees = 25_000;
   let salary:f64 = 35_000.00;
   println!("fees is {} and salary is {}",fees,salary);
}
The output of the above code will be fees is 25000 and salary is 35000.
By default, variables are immutable − read only in Rust. In other words, the variable's value cannot be changed once a value is bound to a variable name.
Let us understand this with an example.
fn main() {
   let fees = 25_000;
   println!("fees is {} ",fees);
   fees = 35_000;
   println!("fees changed is {}",fees);
}
The output will be as shown below −
error[E0384]: re-assignment of immutable variable `fees`
 --> main.rs:6:3
   |
 3 | let fees = 25_000;
   | ---- first assignment to `fees`
...
 6 | fees=35_000;
   | ^^^^^^^^^^^ re-assignment of immutable variable

error: aborting due to previous error(s)

The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees. This is one of the many ways Rust allows programmers to write code and takes advantage of the safety and easy concurrency.
Variables are immutable by default. Prefix the variable name with mut keyword to make it mutable. The value of a mutable variable can be changed.
The syntax for declaring a mutable variable is as shown below −
let mut variable_name = value;
let mut variable_name:dataType = value;
Let us understand this with an example

fn main() {
   let mut fees:i32 = 25_000;
   println!("fees is {} ",fees);
   fees = 35_000;
   println!("fees changed is {}",fees);
}
The output of the snippet is given below −
fees is 25000
fees changed is 35000


    45 Lectures 
     4.5 hours 

 Stone River ELearning

    10 Lectures 
     33 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Tk - Text Widget

Tk text widget is a general purpose editable text widget with features for multiple options. The syntax for text widget is shown below −
text textName options

The options available for the text widget are listed below in table −
-background color
Used to set background color for widget.
-borderwidth width
Used to draw with border in 3D effects.
-font fontDescriptor
Used to set font for widget.
-foreground color
Used to set foreground color for widget.
-relief condition
Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove.
-width number
Sets the width for widget.
-height number
Used to set height for widget.
A simple example for text widget is shown below −
#!/usr/bin/wish

grid [text .myText -background red -foreground white -relief ridge -borderwidth 8 -padx 10
   -pady 10 -font {Helvetica -18 bold} -width 20 -height 5]
.myText insert 1.0 "Hello\nWorld\n"
.myText insert end "A new line\n"
.myText tag configure para -spacing1 0.15i -spacing2 0.05i \
   -lmargin1 0.25i -lmargin2 0.2i -rmargin 0.25i
.myText tag configure hang -lmargin1 0.30i -lmargin2 0.25i
.myText tag add para 1.0 2.end
.myText tag add hang 3.0 3.end
When we run the above program, we will get the following output −
As you can see, text widgets works with the help of procedures like tag, insert, and delete. Most of the tag usages have been covered in the above example.
 Print
 Add Notes
 Bookmark this page
Regular Expression Vs Context Free Grammar - GeeksforGeeks

01 May, 2019
Regular Expressions are capable of describing the syntax of Tokens. Any syntactic construct that can be described by Regular Expression can also be described by the Context free grammar.
Regular Expression:
(a|b)(a|b|01) 
Context-free grammar:
S --> aA|bA
A --> aA|bA|0A|1A|e 
*e denotes epsilon.
The Context-free grammar form NFA for the Regular Expression using the following construction rules:
For each state there is a Non-Terminal symbol.If state A has a transition to state B on a symbol aIF state A goes to state B, input symbol is eIf A is accepting state.Make the start symbol of the NFA with the start symbol of the grammar.
For each state there is a Non-Terminal symbol.
If state A has a transition to state B on a symbol a
IF state A goes to state B, input symbol is e
If A is accepting state.
Make the start symbol of the NFA with the start symbol of the grammar.
Every Regular set can be described the Context-free grammar that’s why we are using Regular Expression. There are several reasons and they are:
Compiler Design
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Top down parsing and Bottom up parsing
Loop Optimization in Compiler Design
Backpatching in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Issues in the design of a code generator
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Matplotlib - Grids

The grid() function of axes object sets visibility of grid inside the figure to on or off. You can also display major / minor (or both) ticks of the grid. Additionally color, linestyle and linewidth properties can be set in the grid() function.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1,3, figsize = (12,4))
x = np.arange(1,11)
axes[0].plot(x, x**3, 'g',lw=2)
axes[0].grid(True)
axes[0].set_title('default grid')
axes[1].plot(x, np.exp(x), 'r')
axes[1].grid(color='b', ls = '-.', lw = 0.25)
axes[1].set_title('custom grid')
axes[2].plot(x,x)
axes[2].set_title('no grid')
fig.tight_layout()
plt.show()

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
HTML | DOM onunload Event - GeeksforGeeks

28 Jul, 2021
The onunload event in HTML occurs once the page is unloaded. for example, when the page is loading and the browser window has been closed by the user or submit a form, click on a link, etc. This event also occurs when the page is reloaded.
Supported Tags
<body>
Syntax:  
In HTML:  
<element onunload="myScript">
In JavaScript:  
object.onunload = function(){myScript};
In JavaScript, using the addEventListener() method:  
object.addEventListener("unload", myScript); 
Example: Using the addEventListener() method  
html
<!DOCTYPE html><html> <head>    <title>HTML DOM onunload Event</title></head> <body id="bID" onunload="GFGfun()">    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <h2>HTML DOM onunload Event</h2>    </center>     <script>        document.getElementById(            "bID").addEventListener("unload", GFGfun);         function GFGfun() {            alert("onunload event attribute called");        }    </script> </body> </html>
Output:  
Note: This event may not work always as expected.Supported Browsers: The browsers supported by HTML DOM onunload Event are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
How to auto-resize an image to fit a div container using CSS?
Design a web page using HTML and CSS
How to Show Images on Click using HTML ?
HTML Course | First Web Page | Printing Hello World
Express.js express.Router() Function
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference between == and .Equals method in c#

The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string.
The Equals() method compares only content.
 Live Demo
using System;
namespace ComparisionExample {
   class Program {
      static void Main(string[] args) {
         string str = "hello";
         string str2 = str;
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }
   }
}
Using Equality operator: True
Using equals() method: True
The Equality operator is used to compare the reference identity.
Let us see another example.
 Live Demo
using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         object str = "hello";
         char[] values = {'h','e','l','l','o'};
         object str2 = new string(values);
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }
   }
}
Using Equality operator: False
Using equals() method: True
The Easiest Way to Get Fake Data. This simple method covers most use... | by Preston Badeer | Towards Data Science

A great rule of thumb for writing code, especially in Python, is to look for a module on PyPi or just using Google, before you start writing code yourself.
If nobody else has done what you’re trying to do then you still might find articles, partial code, or general guidance.
If somebody has done it before you could find everything you need or at least examples of how others accomplished it or tried to.
In this case, generating fake data is something that many, many people have done before. A search for “fake data” on PyPi yields over 10,000 packages.
In my opinion, Faker is the best among them. The only time this package won’t solve your needs is when you need fake data in some rare format or data type. Even then, I’d still recommend using Faker and reshaping what it generates, if possible.
Here are some of the data generators available:
Name
Address
Text (paragraphs, sentences)
IP address
SSN
Birthday
User-agent string
Phone number
License plate number
Barcode
...and many more, see the full list here.
All you have to do to is install it via pip on the command line:
pip install faker
Or if you’re in a Jupyter notebook, just add the exclamation point:
!pip install faker
Now for the good stuff! Generating 1000 fake user profiles is this easy (in bold is the Faker code, the rest is Pandas).
from faker import Fakerimport pandas as pdfaker = Faker()df = pd.DataFrame()for i in range(1000):    df = df.append(faker.profile(), ignore_index=True)
And here’s a sample of what that data looks like:
If you want to get an individual field instead of a full profile, it’s just as easy:
from faker import Fakerfaker = Faker()# Get a random addressfaker.address()# Get a random person's namefaker.name()
Again, there are way more fields available, you can find them all in the documentation. You can even make your own data providers, here’s a few already contributed by the community.
Faker also supports multiple languages, running via the command line, and seeding the randomizer to get consistent results.
Hopefully, this saves you some time! I use Faker to generate data for stress tests, speed tests, and even test model pipelines for errors.
SciPy Optimizers

Optimizers are a set of procedures defined in SciPy that either find the minimum value of 
a function, or the root of an equation.
Essentially, all of the algorithms in Machine Learning are nothing more than a complex equation that needs to be minimized with the help of given data.
NumPy is capable of finding roots for polynomials and linear equations, but it can not find roots for non 
linear equations, like this one:
x + cos(x)
For that you can use SciPy's optimze.root function.
This function takes two required arguments:
fun - a function representing an equation.
x0 - an initial guess for the root.
The function returns an object with information regarding the solution.
The actual solution is given under attribute x 
of the returned object:
Find root of the equation x + cos(x):
Note: The returned object has much more information about 
  the solution.
Print all information about the solution (not just x which is the root)
A function, in this context, represents a curve, curves have high points and low points.
High points are called maxima.
Low points are called minima.
The highest point in the whole curve is called global maxima, whereas the rest of them are called local maxima.
The lowest point in whole curve is called global minima, whereas the rest of them are called local minima.
We can use scipy.optimize.minimize() function to minimize the function.
The minimize() function takes the following arguments:
fun - a function representing an equation.
x0 - an initial guess for the root.
method - name of the method to use. Legal values:
    'CG'
    'BFGS'
    'Newton-CG'
    'L-BFGS-B'
    'TNC'
    'COBYLA'
    'SLSQP'
callback - function called after each iteration of optimization.
options - a dictionary defining extra params:

Minimize the function x^2 + x + 2 with BFGS:
Insert the missing parts to print the square root of the equation:
from scipy.optimize import root
from math import cos

def eqn(x):
  return x + cos(x)

myroot = (eqn, 0)

print()

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
howdoi in Python

C:\Py3Project>howdoi create a python list
Running the above code gives us the following result −
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
c:\python3>howdoi print today's date in python
Running the above code gives us the following result −
for date in mylist :
print str(date)
c:\python3>howdoi create fibonnaci series in python
Running the above code gives us the following result −
def F(n):
   if n == 0: return 0
   elif n == 1: return 1
   else: return F(n-1)+F(n-2)
c:\python3>howdoi use calendar in javascript
Running the above code gives us the following result −
You can choose from Material UI.
http://www.material-ui.com/#/components/date-picker
http://www.material-ui.com/#/components/time-picker
c:\python3>howdoi go to north pole
Running the above code gives us the following result −
I believe the difference is because GPS uses the geographical North/South Pole rather than the magnetic ones.
The further north you are, the bigger the difference is to where you are.
The GPS satellite positions need to be absolute, and using a fluctuating point of
reference like the magnetic poles is a big no-no.
C# Equivalent to Java Functional Interfaces

Equivalent of Java’s Functional Interfaces in C# is Delegates.
Let us see the implementation of functional interface in Java −
@FunctionalInterface
public interface MyInterface {
   void invoke();
}
public class Demo {
   void method(){
      MyInterface x = () -> MyFunc ();
      x.invoke();
   }
   void MyFunc() {
   }
}
The same implementation in C# delagates −
public delegate void MyInterface ();
public class Demo {
   internal virtual void method() {
      MyInterface x = () => MyFunc ();
      x();
   }
   internal virtual void MyFunc() {
   }
}
Except not working in MySQL?

You cannot use except in MySQL. You can work with NOT IN operator to get the same result. Let us first create a table −
mysql> create table DemoTable1
 (
 Number1 int
 );
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(100);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable1 values(200);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable1 values(300);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement:
mysql> select *from DemoTable1
This will produce the following output −
+---------+
| Number1 |
+---------+
|     100 |
|     200 |
|     300 |
+---------+
3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2
   (
   Number1 int
   );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(100);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable2 values(400);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2 values(300);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+---------+
| Number1 |
+---------+
|     100 |
|     400 |
|     300 |
+---------+
3 rows in set (0.00 sec)
Following is the query to learn how to use NOT IN operator in place of except −
mysql> select Number1 from DemoTable1
where Number1 not in (SELECT Number1 FROM DemoTable2);
This will produce the following output −
+---------+
| Number1 |
+---------+
|     200 |
+---------+
1 row in set (0.04 sec)
Count set bits in an integer in C++

We are given an integer number let’s say, num and the task is to firstly calculate the binary digit of a number and then calculate the total set bits of a number.
Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0’s and 1’s. So, the digit 1 is known as set bit in the terms of the computer.
Input − int number = 50
Output − Count of total set bits in a number are − 3
Explanation − Binary representation of a number 50 is 110010 and if we calculate it in 8-digit number then two 0’s will be appended in the beginning. So, the total set bits in a number are 3.
Input − int number = 10
Output − Count of total set bits in a number are − 2
Explanation − Binary representation of a number 10 is 00001010 and if we calculate it in 8-digit number then four 0’s will be appended in the beginning. So, the total set bits in a number are 2.
Input the number in a variable of integer type
Input the number in a variable of integer type
Declare a variable count to store the total count of set bits of type unsigned int
Declare a variable count to store the total count of set bits of type unsigned int
Start loop FOR from i to 1<<7 and i > 0 and i to i / 2
Start loop FOR from i to 1<<7 and i > 0 and i to i / 2
Inside the loop, check num & 1 == TRUE then print 1 else print 0
Inside the loop, check num & 1 == TRUE then print 1 else print 0
Start loop while to calculate the total count of bits till number isn’t 0
Start loop while to calculate the total count of bits till number isn’t 0
Inside the loop, set count = count + number & 1 and also set number >>=1
Inside the loop, set count = count + number & 1 and also set number >>=1
Print the count
Print the count
 Live Demo
#include<iostream>
using namespace std;
//Count total set bits in a number
unsigned int bits(unsigned int number){
   unsigned int count = 0;
   unsigned i;
   //display the total 8-bit number
   cout<<"8-bit digits of "<<number<<" is: ";
   for (i = 1 << 7; i > 0; i = i / 2){
      (number & i)? cout<<"1": cout<<"0";
   }
   //calculate the total set bits in a number
   while (number){
      count += number & 1;
      number >>= 1;
   }
   cout<<"\nCount of total set bits in a number are: "<<count;
}
int main(){
   int number = 50;
   bits(number);
   return 0;
}
If we run the above code it will generate the following output −
8-bit digits of 50 is: 00110010
Count of total set bits in a number are: 3
Check if one list is subset of other in Python

In text analytics and various other fields of data analytics it is often needed to find if a given list is already a part of a bigger list. In this article we will see the python programs to implement this requirement.
We use a for loop to check if every element of the smaller list is present in the bigger list. The all function ensures each evaluation returns true.
 Live Demo
Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]

# Given list and sublist
print("Given list ",Alist)
print("Given sublist",Asub_list)

# With all
if (all(x in Alist for x in Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

# Checkign again
Asub_list = ['Wed',5,9]
print("New sublist",Asub_list)
if (all(x in Alist for x in Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")
Running the above code gives us the following result −
Given list ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of bigger list
New sublist ['Wed', 5, 9]
Sublist is not part of bigger list
In this approach we convert the lists into set and use the subset functions to validate if the small list is part of the bigger list or not.
 Live Demo
Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]

# Given list and sublist
print("Given list ",Alist)
print("Given sublist",Asub_list)

# With all
if(set(Asub_list).issubset(set(Alist))):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

# Checkign again
Asub_list = ['Wed',5,9]
print("New sublist",Asub_list)
if(set(Asub_list).issubset(set(Alist))):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")
Running the above code gives us the following result −
Given list ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of bigger list
New sublist ['Wed', 5, 9]
Sublist is not part of bigger list
The intersection function find the common elements between two sets. In this approach we convert the lists into sets and apply the intersection function. If the result of intersection is same as the sublist then we conclude the sublist is part of thelist.
 Live Demo
Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]

# Given list and sublist
print("Given list ",Alist)
print("Given sublist",Asub_list)

# With all
if(set(Alist).intersection(Asub_list)== set(Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

# Checkign again
Asub_list = ['Wed',5,9]
print("New sublist",Asub_list)
if(set(Alist).intersection(Asub_list)== set(Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")
Running the above code gives us the following result −
Given list ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of bigger list
New sublist ['Wed', 5, 9]
Sublist is not part of bigger list
C# | Get the minimum value in the SortedSet - GeeksforGeeks

01 Feb, 2019
SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Min Property is used to get minimum value in the SortedSet<T>, as defined by the comparer.
Properties:
In C#, SortedSet class can be used to store, remove or view elements.
It maintains ascending order and does not store duplicate elements.
It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order.
Syntax:
mySet.Min

Here, mySet is the object of the SortedSet.
Return Value: Minimum value in the SortedSet.
Below programs illustrate the use of SortedSet<T>.Min Property:
Example 1:
// C# code to get the minimum value// in the SortedSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a SortedSet of integers        SortedSet<int> mySet = new SortedSet<int>();          // Inserting elements into SortedSet        for (int i = 0; i < 10; i++) {            mySet.Add(i);        }          // Displaying the minimum value in the SortedSet        Console.WriteLine("The minimum element in SortedSet is : " + mySet.Min);    }}
The minimum element in SortedSet is : 0

Example 2:
// C# code to get the minimum value// in the SortedSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a SortedSet of strings        SortedSet<string> mySet = new SortedSet<string>();          // Inserting elements into SortedSet        mySet.Add("A");        mySet.Add("B");        mySet.Add("C");        mySet.Add("D");        mySet.Add("E");        mySet.Add("F");          // Displaying the minimum value in the SortedSet        Console.WriteLine("The minimum element in SortedSet is : " + mySet.Min);    }}
The minimum element in SortedSet is : A

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1.min?view=netcore-2.1
CSharp-Generic-Namespace
CSharp-Generic-SortedSet
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
Trapping Rain Water in Python

Suppose we have an array of n non-negative integers. These are representing an elevation map where the width of each bar is 1, we have to compute how much water it is able to trap after raining. So the map will be like −
Here we can see there are 6 blue boxes, so the output will be 6.
To solve this, we will follow these steps −
Define a stack st, water := 0 and i := 0
Define a stack st, water := 0 and i := 0
while i < size of heightif is stack is empty or height[stack top] >= height[i], then push i into stack,
increase i by 1otherwisex := stack top element, delete top from stackif stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x])
while i < size of height
if is stack is empty or height[stack top] >= height[i], then push i into stack,
increase i by 1
if is stack is empty or height[stack top] >= height[i], then push i into stack,
increase i by 1
otherwisex := stack top element, delete top from stackif stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x])
otherwise
x := stack top element, delete top from stack
x := stack top element, delete top from stack
if stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x])
if stack is not empty, then
temp := min of height[stack top element] and height[i]
temp := min of height[stack top element] and height[i]
dest := i – stack top element – 1
dest := i – stack top element – 1
water := water + dist * (temp – height[x])
water := water + dist * (temp – height[x])
return water
return water
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def trap(self, height):
      stack = []
      water = 0
      i=0
      while i<len(height):
         if len(stack) == 0 or height[stack[-1]]>=height[i]:
            stack.append(i)
            i+=1
         else:
            x = stack[-1]
            stack.pop()
            if len(stack) != 0:
               temp = min(height[stack[-1]],height[i])
               dist = i - stack[-1]-1
               water += dist*(temp - height[x])
      return water
ob = Solution()
print(ob.trap([0,1,0,2,1,0,1,3,2,1,2,1]))
[0,1,0,2,1,0,1,3,2,1,2,1]
6
Python | Filter tuples according to list element presence - GeeksforGeeks

11 Nov, 2019
Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have application in many domains working with data. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionUsing list comprehension is brute force method to perform this task in a shorthand. In this, we just check for each tuple and check if it contains any element from the target list.
# Python3 code to demonstrate working of# Filter tuples according to list element presence# using list comprehension  # initialize list of tupletest_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]  # initialize target list tar_list = [6, 10]  # printing original tuples listprint("The original list : " + str(test_list))  # Filter tuples according to list element presence# using list comprehensionres = [tup for tup in test_list if any(i in tup for i in tar_list)]  # printing resultprint("Filtered tuple from list are : " + str(res))
The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]

 
Method #2 : Using set() + list comprehensionAbove approach can be optimized by converting the containers to a set() reducing duplicates and performing a & operation to fetch the desired records.
# Python3 code to demonstrate working of# Filter tuples according to list element presence# using set() + list comprehension  # initialize list of tupletest_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]  # initialize target list tar_list = [6, 10]  # printing original tuples listprint("The original list : " + str(test_list))  # Filter tuples according to list element presence# using set() + list comprehensionres = [tup for tup in test_list if (set(tar_list) & set(tup))]  # printing resultprint("Filtered tuple from list are : " + str(res))
The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not