code-rag-bench/online-tutorials huggingface dataset:
How to add icon logo in title bar using HTML ?

15 Jan, 2019
Most of the websites adds icon or image logo in the title bar. The icon logo is also called as favicon. Adding favicons is also considered to be good for the SEO of the websites. The favicon is the combination of favorite icon.
The link attribute is used to add the favicon.
Syntax:
<link rel="icon" href="icon_path" type="image/icon type">
Example:
<!-- HTML code to add icon in the title bar --><!DOCTYPE html><html>    <head>        <meta charset = "utf-8" />                  <title>            GeeksforGeeks icon        </title>                  <!-- add icon link -->        <link rel = "icon" href = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png"         type = "image/x-icon">              </head>          <body>        <h1 style = "color:green;">            GeeksforGeeks        </h1>                  <p>            GeeksforGeeks icon added in the title bar        </p>    </body></html>                    
Output:
HTML-Misc
Technical Scripter 2018
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Popup Menu in Tkinter

26 Mar, 2020
Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used packages for GUI applications which comes with the Python itself.
Note: For more information, refer to Python GUI – tkinter
Menus are an important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other top-level windows.
Syntax:
menu = Menu(master, **options)
Note: For more information, refer to Python | Menu widget in Tkinter
Popup menus are context menus that appear on user interaction. This menu can be shown anywhere on the client window. below is the python code to create a popup menu using Tkinter library.
#creating popup menu in tkinterimport tkinter   class A:    #creates parent window    def __init__(self):                       self.root = tkinter.Tk()        self.root.geometry('500x500')           self.frame1 = tkinter.Label(self.root,                                    width = 400,                                    height = 400,                                    bg = '#AAAAAA')        self.frame1.pack()       #create menu    def popup(self):        self.popup_menu = tkinter.Menu(self.root,                                       tearoff = 0)                  self.popup_menu.add_command(label = "say hi",                                    command = lambda:self.hey("hi"))                  self.popup_menu.add_command(label = "say hello",                                    command = lambda:self.hey("hello"))        self.popup_menu.add_separator()        self.popup_menu.add_command(label = "say bye",                                    command = lambda:self.hey("bye"))       #display menu on right click    def do_popup(self,event):        try:            self.popup_menu.tk_popup(event.x_root,                                     event.y_root)        finally:            self.popup_menu.grab_release()       def hey(self,s):        self.frame1.configure(text = s)              def run(self):        self.popup()        self.root.bind("<Button-3>",self.do_popup)        tkinter.mainloop()  a = A()a.run()
Output:
The popup menu in above code appears on right-click.
Functions
Menu(root): creates the menu.
add_command(label, command): adds the commands on the menu, the command argument calls the function hey() when that option is clicked.
add_separator(): adds a separator.
tk_popup(x, y): posts the menu at the position given as arguments
grab_release(): releases the event grab
bind(key, event): binds the mouse event.
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Write a C program to read a data from file and display

How to read a series of items that are present in a file and display the data in columns or tabular form using C Programming
Create a file in write mode and write some series of information in the file and close it again open and display the series of data in columns on the console.
Write mode of opening the file
FILE *fp;
fp =fopen ("sample.txt", "w");
If the file does not exist, then a new file will be created.
If the file does not exist, then a new file will be created.
If the file exists, then old content gets erased & current content will be stored.
If the file exists, then old content gets erased & current content will be stored.
Read mode of opening the file
   FILE *fp
fp =fopen ("sample.txt", "r");
If the file does not exist, then fopen function returns NULL value.
If the file does not exist, then fopen function returns NULL value.
If the file exists, then data is read from the file successfully.
If the file exists, then data is read from the file successfully.
The logic used to display data on the console in tabular form is −
while ((ch=getc(fp))!=EOF){
   if(ch == ',')
      printf("\t\t");
   else
      printf("%c",ch);
}
 Live Demo
#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w");
   printf("enter the text.press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF){
      if(ch == ',')
         printf("\t\t");
      else
         printf("%c",ch);
   }
   fclose(fp);
   return 0;
}
enter the text.press cntrl Z:
Name,Item,Price
Bhanu,1,23.4
Priya,2,45.6
^Z
text on the file:
Name    Item    Price
Bhanu    1      23.4
Priya    2      45.6
Maximum Size Subarray Sum Equals k in C++

Suppose we have an array called nums and a target value k, we have to find the maximum length of a subarray that sums to k. If there is not present any, return 0 instead.
So, if the input is like nums = [1, -1, 5, -2, 3], k = 3, then the output will be 4, as the subarray [1, - 1, 5, -2] sums to 3 and is the longest.
To solve this, we will follow these steps −
ret := 0
ret := 0
Define one map m
Define one map m
n := size of nums
n := size of nums
temp := 0, m[0] := -1
temp := 0, m[0] := -1
for initialize i := 0, when i < n, update (increase i by 1), do −temp := temp + nums[i]if (temp - k) is in m, then −ret := maximum of ret and i - m[temp - k]if temp is not in m, then −m[temp] := i
for initialize i := 0, when i < n, update (increase i by 1), do −
temp := temp + nums[i]
temp := temp + nums[i]
if (temp - k) is in m, then −ret := maximum of ret and i - m[temp - k]
if (temp - k) is in m, then −
ret := maximum of ret and i - m[temp - k]
ret := maximum of ret and i - m[temp - k]
if temp is not in m, then −m[temp] := i
if temp is not in m, then −
m[temp] := i
m[temp] := i
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int maxSubArrayLen(vector<int<& nums, int k) {
      int ret = 0;
      unordered_map <int, int> m;
      int n = nums.size();
      int temp = 0;
      m[0] = -1;
      for(int i = 0; i < n; i++){
         temp += nums[i];
         if(m.count(temp - k)){
            ret = max(ret, i - m[temp - k]);
         }
         if(!m.count(temp)){
            m[temp] = i;
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int< v = {1,-1,5,-2,3};
   cout << (ob.maxSubArrayLen(v, 3));
}
[1,-1,5,-2,3], 3
4
Python - Convert key-value String to dictionary - GeeksforGeeks

10 May, 2020
Sometimes, while working with Python strings, we can have problem in which we need to convert a string key-value pairs to dictionary. This can have applications in which we are working with string data and needs to be converted. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using map() + split() + loopThe combination of above functionalities can be used to perform this task. In this, we perform the conversion of key-value pair to dictionary using map and splitting key-value pairs is done using split().
# Python3 code to demonstrate working of # Convert key-value String to dictionary# Using map() + split() + loop  # initializing stringtest_str = 'gfg:1, is:2, best:3'  # printing original stringprint("The original string is : " + str(test_str))  # Convert key-value String to dictionary# Using map() + split() + loopres = []for sub in test_str.split(', '):    if ':' in sub:        res.append(map(str.strip, sub.split(':', 1)))res = dict(res)  # printing result print("The converted dictionary is : " + str(res)) 
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}

 
Method #2 : Using dict() + generator expression + split() + map()This is yet another way in which this problem can be solved. In this, we perform the task in similar way as above but in 1 liner way using dict() and generator expression.
# Python3 code to demonstrate working of # Convert key-value String to dictionary# Using dict() + generator expression + split() + map()  # initializing stringtest_str = 'gfg:1, is:2, best:3'  # printing original stringprint("The original string is : " + str(test_str))  # Convert key-value String to dictionary# Using dict() + generator expression + split() + map()res = dict(map(str.strip, sub.split(':', 1)) for sub in test_str.split(', ') if ':' in sub)  # printing result print("The converted dictionary is : " + str(res)) 
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to Find the first non-repeating character from a stream of characters?

In this section we are going to find the first unique or non-repeating character from a string or stream of characters. There are multiple ways to solve this problem. We will try to create two different program for the same stream of characters.
def firstNonRepeatingChar(str1):
   char_order = []
   counts = {}
   for c in str1:
      if c in counts:
         counts[c] += 1
      else:
         counts[c] = 1
         char_order.append(c)
   for c in char_order:
      if counts[c] == 1:
      return c
   return None

print(firstNonRepeatingChar('PythonforallPythonMustforall'))
print(firstNonRepeatingChar('tutorialspointfordeveloper'))
print(firstNonRepeatingChar('AABBCC'))
M
u
None
Above program give O(n) solution. In above program we first loop through the string once. Once we find a new character, we store it in counts object with a value of 1 and append it to char_order. When we come across a repeated character, we increment the value of counts by 1. Finally, we loop through char_order until we find a character with a value of 1 in char_order and return it.
s = "tutorialspointfordeveloper"
while s != "":
   slen0 = len(s)
   ch = s[0]
   s = s.replace(ch, "")
   slen1 = len(s)
   if slen1 == slen0-1:
      print ("First non-repeating character is: ",ch)
      break;
   else:
   print ("No Unique Character Found!")
First non-repeating character is: u
PyQt5 QSpinBox - Removing the arrow buttons - GeeksforGeeks

06 May, 2020
In this article we will see how we can remove the buttons of the spin box, basically there are two buttons in the spin box one for incrementing the value and second for decrementing the value. Below is the representation of how normal spin box looks like vs the spin box with no buttons looks like
In order to do this we will use setButtonSymbols method.
Syntax :spin_box.setButtonSymbols(QAbstractSpinBox.NoButtons)orspin_box.setButtonSymbols(2)
Argument : It takes either QAbstractSpinBox object or integer value
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 150, 40)          # removing the buttons        self.spin.setButtonSymbols(QAbstractSpinBox.NoButtons)              # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Linear search using Multi-threading - GeeksforGeeks

28 Jan, 2018
Given a large file of integers, search for a particular element in it using multi-threading.
Examples:
Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 
        22, 25, 27, 30, 64, 110, 220
Output :if key = 20
Key element found

Input :1, 5, 7, 10, 12, 14, 15, 18, 20, 
       22, 25, 27, 30, 64, 110, 220
Output :if key = 202
Key not present

Prerequisite : Multi-threading
Approach :First create n threads. Then, divide array in to four parts one section for each thread and apply linear search on individual section using multhreading and check whether the key element is present or not.
Command : g++ -pthread linear_thread.cpp

C++
// CPP code to search for element in a// very large file using Multithreading#include <iostream>#include <pthread.h>using namespace std;  // Max size of array#define max 16  // Max number of threads to create#define thread_max 4  int a[max] = { 1, 5, 7, 10, 12, 14, 15,               18, 20, 22, 25, 27, 30,               64, 110, 220 };int key = 202;  // Flag to indicate if key is found in a[]// or not.int f = 0;  int current_thread = 0;  // Linear search function which will// run for all the threadsvoid* ThreadSearch(void* args){    int num = current_thread++;      for (int i = num * (max / 4);          i < ((num + 1) * (max / 4)); i++)     {        if (a[i] == key)            f = 1;    }}  // Driver Codeint main(){    pthread_t thread[thread_max];      for (int i = 0; i < thread_max; i++) {        pthread_create(&thread[i], NULL,                       ThreadSearch, (void*)NULL);    }      for (int i = 0; i < thread_max; i++) {        pthread_join(thread[i], NULL);    }      if (f == 1)        cout << "Key element found" << endl;    else        cout << "Key not present" << endl;    return 0;}
Key not present

Exercise: The above code divides array into four subarrays. Extend this to take a parameter that decides number of divisions (or threads).
cpp-multithreading
C Language
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
Load CSV data into List and Dictionary using Python - GeeksforGeeks

21 Apr, 2020
Prerequisites: Working with csv files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
CSV raw data is not utilizable in order to use that in our Python program it can be more beneficial if we could read and separate commas and store them in a data structure. We can convert data into lists or dictionaries or a combination of both either by using functions csv.reader and csv.dictreader or manually directlyand in this article, we will see it with the help of code.
Example 1: Loading CSV to list
CSV File:
# importing module import csv   # csv fileused id Geeks.csvfilename="Geeks.csv"  # opening the file using "with"# statementwith open(filename,'r') as data:   for line in csv.reader(data):            print(line)          # then data is read line by line # using csv.reader the printed # result will be in a list format # which is easy to interpret
Output:
Example 2: Loading CSV to dictionary
import csv    filename ="Geeks.csv"  # opening the file using "with" # statementwith open(filename, 'r') as data:          for line in csv.DictReader(data):        print(line)
Output:
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
loops in python
ES6 - Array Method map()

map() method creates a new array with the results of calling a provided function on every element in this array.
array.map(callback[, thisObject]);   

callback − Function that produces an element of the new Array from an element of the current one.
callback − Function that produces an element of the new Array from an element of the current one.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns the created array.
var numbers = [1, 4, 9]; 
var roots = numbers.map(Math.sqrt); 
console.log("roots is : " + roots );    
roots is : 1,2,3 


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
strings.Contains Function in Golang with Examples - GeeksforGeeks

31 Dec, 2021
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false.
Syntax: 
func Contains(str, substr string) bool
Here, str is the original string and substr is the string that you want to check. Let us discuss this concept with the help of an example:
Example 1: 
Go
// Golang program to illustrate// the strings.Contains() Functionpackage main   import (    "fmt"    "strings")   func main() {       // using the function    fmt.Println(strings.Contains("GeeksforGeeks", "for"))    fmt.Println(strings.Contains("A computer science portal", "science"))   }
Output:
true
true
Explanation: In the above example, we check the presence of sub-string ‘for’ and ‘science’ in different strings. Since strings.Contains() function returns boolean value, it returns true in both the cases.
Example 2: Following example illustrates how the user can print the desired result instead of a boolean output: 
Go
// Golang program to illustrate// the strings.Contains() Functionpackage main   import (    "fmt"    "strings")   func main() {    input := "Golang"       str := "This is a Golang program"       if strings.Contains(str, input) {        fmt.Println("Yes")    }}
Output: 
Yes
Explanation: In the above example, we take a sub-string as ‘input’ and the main string as ‘str’. Then, we check if ‘Golang’ is present in the main string. If so, ‘Yes’ is returned as the output as shown above. 
lxy560zahwm90n5ebjfi8cqx251rqm1qx0yjn4v9
Golang-String
Picked
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
Arrays in Go
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
How to Parse JSON in Golang?
C# - Reading Lines From a File Until the End of File is Reached - GeeksforGeeks

27 Dec, 2021
Given a file, now our task is to read lines from the file until the end of the file using C#. Before reading the lines from a file we must have some data, so first we need an empty file in our path and then insert lines in our file and then we read lines from a file. So to do this task we use two basic operations that are reading and writing. The file becomes a stream when we open the file for writing and reading, here the stream means a sequence of bytes that is used for communication. So to our task, we use:
Path: For reading a file from any source we have to need the location/path. A Path is a string that includes a file path in a system.
 @"c:\folder\file_name.txt"
We will check if the file exists in the path or not by using File.Exists(path) method
StreamWriter: StreamWriter is used to write a stream of data/lines to a file.
StreamWriter sw = new StreamWriter(myfilepath)
StreamReader: StreamReader is used to read a stream of data/lines from a file.
StreamReader sr = new StreamReader(myfilepath)
Peek: Used to read the data/lines from the file till the end of the file.
StreamReaderObject.Peek()
So all are placed in try() block to catch the exceptions that occur.
Example: Consider the path and file are: 
C#
// C# program to read lines from a file// until the end of file is reachedusing System;using System.IO; class GFG{     public static void Main(){         // File name is data    // File path is the following path    string myfilepath = @"c:\sravan\data.txt";    try    {                 // Check if file exists or not        if (File.Exists(path))        {            File.Delete(path);        }                 // Write data into file using StreamWriter through the path        using (StreamWriter sw = new StreamWriter(myfilepath))        {            sw.WriteLine("hello");            sw.WriteLine("geeks for geeks");            sw.WriteLine("welcome to c#");                  }                 // Read the file present in the path        using (StreamReader sr = new StreamReader(myfilepath))        {                         // Iterating the file            while (sr.Peek() >= 0)            {                                 // Read the data in the file until the peak                Console.WriteLine(sr.ReadLine());            }        }    }         // Caught the exception    catch (Exception e)    {        Console.WriteLine("The process failed: {0}", e.ToString());    }    Console.Read();}
Output:
hello
geeks for geeks
welcome to c#
See the file data is inserted:
 
rajeev0719singh
CSharp-File-Handling
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
GATE-CS-2015 (Set 1) - GeeksforGeeks

11 Oct, 2021
She enjoyed herself immensely at the party.
(2, 14)
(3, 13)
(4, 12)
(5, 11) 

Probability = Favorable Outcomes/Total Outcomes
Probability = 4/20 = 0.20

Therefore option A is correct
Statements:
1. Each step is 3/4 foot high.
2. Each step is 1 foot wide.
Flippancy     ---> lack of respect or seriousness.
Acquiescence  ---> the reluctant acceptance of 
                   something without protest.
Wheedle      --->  use endearments or flattery to 
                   persuade someone to do something or 
Profligate   ---> recklessly extravagant 
Q.No. Marks Answered-Correctly Answered-Wrongly Not-Attempted
 1      2         21                17               6 
 2      3         15                27               2    
 3      1         11                29               4
 4      2         23                18               3
 5      5         31                12               1 
Total marks = 2*21 + 3*15 + 1*11 + 2*23  + 5*31
            = 299
Average marks =  299/44 = 6.795 
Statement: 
There has been a significant drop in the water level 
in the lakes supplying water to the city.

Course of action:
1. The water supply authority should impose a partial 
   cut in supply to tackle the situation.
2. The government should appeal to all the residents 
   through mass media for minimal use of water.
3. The government should ban the water supply in lower 
   areas
1. p + m + c = 27/20 
2. p + m + c = 13/20
3. (p) × (m) × (c) = 1/10 
1 - (1 - m) (1 - p) (1 - c) = 0.75               -------(1)
(1 - m)pc +  (1 - p)mc + (1 - c)mp + mpc = 0.5   -------(2)
(1 - m)pc +  (1 - p)mc + (1 - c)mp  = 0.4        -------(3)

From last 2 equations, we can derive mpc = 0.1

After simplifying equation 1, we get.
p + c + m - (mp + mc + pc) + mpc = 0.75        
p + c + m - (mp + mc + pc) = 0.65         -------(4)

After simplifying equation 3, we get
pc + mc + mp - 3mpc = 0.4

Putting value of mpc, we get
pc + mc + mp = 0.7

After putting above value in equation 4, we get
 p + c + m - 0.7 = 0.65
 p + c + m = 1.35 = 27/20 
See GATE Corner for all papers, notes and other important information.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Get Hired With GeeksforGeeks and Win Exciting Rewards!
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
Spring - REST Controller
How to add help in the PowerShell function?

When we write a program, people from a non-programming background often expect to get much possible help related to the program. When we write the function and we declare the parameters, people who are unaware of what kind of input the parameter need, generally search for the help first using the Get-Help command and then they find only the parameters but not the description of it. For example,
function TestFunct{
   param(
      #16 Digit Application ID
      [parameter(Mandatory=$true)]
      [String]$AppID,
      #Date in the Unix Format - 2020-10-31T17:12:10+0530
      [String]$Date
   )
}
In the above example, there are two parameters specified and when the user gets help with the function, it doesn’t specify the comments where the parameter description is given. For example,
PS C:\> help TestFunct -Parameter *
-AppID <string>

   Required?                   true
   Position?                   0
   Accept pipeline input?      false
   Parameter set name          (All)
   Aliases                     None
   Dynamic?                    false

-Date <string>

   Required?                   false
   Position?                   1
   Accept pipeline input?      false
   Parameter set name          (All)
   Aliases                     None
   Dynamic?                    false
To add the description from the comment, we need to add the comment-based help and need to use SYNOPSIS from the comment-based help.
Example
function TestFunct{
   <#
      .SYNOPSIS
      This is test function for parameter based help
   #>
   param(
      #16 Digit Application ID
      [parameter(Mandatory=$true)]
      [String]$AppID,
      #Date in the Unix Format - 2020-10-31T17:12:10+0530
      [String]$Date
   )
}
Now when we check the parameter, we get the comment based description.
PS C:\> help TestFunct -Parameter *
-AppID <String>
   16 Digit Application ID

   Required?                      true
   Position?                      1
   Default                        value
   Accept pipeline input?         false
   Accept wildcard characters?    false

-Date <String>
   Date in the Unix Format - 2020-10-31T17:12:10+0530

   Required?                      false
   Position?                      2
   Default                        value
   Accept pipeline input?         false
   Accept wildcard characters?    false
How to use break and continue statements in Java?

The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
The syntax of a break is a single statement inside any loop −
break;
Live Demo
public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
            break;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}
This will produce the following result −
10
20
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to the update statement.
In a while loop or do/while loop, control immediately jumps to the Boolean expression.
The syntax of a continue is a single statement inside any loop −
continue;
Live Demo
public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
            continue;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}
This will produce the following result −
10
20
40
50
Bootstrap 4 .flex-grow-0|1 class

Use the .flex-grow-0|1 class in Bootstrap to allow a singly lex item to take up rest of the space in the flex.
For example, the following takes rest of the space in the right −
The above is set by adding flex-grow class for the last flex-item −
<div class="d-flex mb-3">
  <div class="p-2 bg-danger">P</div>
  <div class="p-2 bg-info">Q</div>
  <div class="p-2 flex-grow-1 bg-secondary">R</div>
</div>
Let us see the following example to implement flex-grow-0|1 class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container mt-3">
    <div class="d-flex mb-3">
      <div class="p-2 bg-danger">P</div>
      <div class="p-2 bg-info">Q</div>
      <div class="p-2 flex-grow-1 bg-secondary">R</div>
    </div>
    <div class="d-flex mb-3">
      <div class="p-2 bg-success">P</div>
      <div class="p-2 flex-grow-1 bg-primary">Q</div>
      <div class="p-2 bg-info">R</div>
    </div>
  </div>

</body>
</html>
How to get and set form element values with jQuery?

To get a form value with jQuery, you need to use the val() function. To set a form value with jQuery, you need to use the val() function, but to pass it a new value.
You can try to run the following code to learn how to get and set form element values with jQuery −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
         
             $("#buttonSet").click(function () {
                 $("#txtBox").val("Amit");
                 $("input:radio").val(["male"]);
                 $("#buttonGet").removeAttr('disabled');
            });
             $("#buttonGet").click(function () {
                $("#result").html(
                    $("#txtBox").val() + "<br/>" +
                    $("input:radio[name=rd]:checked").val()
                );
            });
         });
      </script>
   </head>
   <body>
      Name <br />
      <input id="txtBox" type="text" />
      <br /><br />
      Gender <br />
      <input type="radio"  name="rd" value="male"/> Male
      <input type="radio"  name="rd" value="female"/> Female
      <br /><br />
      <input id="buttonSet" type="button" value="Set Values" />
      <input id="buttonGet" type="button" value="Get Values" disabled="disabled" />
      <p id="result"></p>
   </body>
</html>
Creation of virtual environments using Python

A Python package of a specific version may be needed while developing Python based applications. However if this version of same package is installed for system wide use, it might be conflicting with other application’s requirements. Hence it is desired to have side-by-side environments for each purpose to resolve compatibility issues.
Virtual Environments allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally.
The venv module in standard library of Python is used to create virtual environment. A virtual environment is a directory in file system having its own copy of Python interpreter and other scripts. Following command creates a virtual environment in the named directory.
C:\python37>python -m venv e:\testenv
You will find a new directory created as specified. The above can optionally use following switches
The 'scripts' folder under the ENV_DIR (in this case testenv) contains local copy of Python interpreter, pip installer and scripts to activate and deactivate the environment.
activate
activate.bat
activate.ps1
deactivate.bat
easy_install-3.7.exe
easy_install.exe
pip.exe
pip3.7.exe
pip3.exe
python.exe
pythonw.exe
In order to start Python in the isolated environment, it must be activated first. For this purpose, 'activate.bat' must be invoked from command line.
E:\testenv>scripts\activate

(testenv) E:\testenv>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Name of the virtual environment appears in parentheses to the left of DOS prompt. Now you can Python in virtual environment.
If any package is installed using pip3 utility in virtual environment's scripts folder, it will be locally installed and will not be available for system wide use.
Deactivate virtual environment
To return to normal environment, the virtual environment should be disable using 'deactivate.bat' in scripts folder.
>>> quit()

(testenv) E:\testenv>scripts\deactivate
E:\testenv>
For Python versions before 3.3, use virtualenv which must be installed separately.
The venv module defined EnvironmentBuilder class for programmatically creating virtual environment.
Setting Y-axis in Matplotlib using Pandas

To set Y-Axis in matplotlib using Pandas, we can take the following steps −
Create a dictionary with the keys, x and y.
Create a dictionary with the keys, x and y.
Create a data frame using Pandas.
Create a data frame using Pandas.
Plot data points using Pandas plot, with ylim(0, 25) and xlim(0, 15).
Plot data points using Pandas plot, with ylim(0, 25) and xlim(0, 15).
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = dict(
   x=np.linspace(0, 10, 10),
   y=np.linspace(0, 10, 10)*2
)
df = pd.DataFrame(d)
df.plot(kind="bar", ylim=(0, 25), xlim=(0, 15))
plt.show()
Generate a QR code in Node.js

07 Jun, 2022
In this article, we will discuss how to generate a QR code using Node.js. A QR code is a monochromatic matrix with embedded data that is used in manufacturing industries in order to label the products. Nowadays QR codes are being used for payments in UPI-based apps, some chatting apps like WhatsApp, and in the play store. These are some most common examples, but we can use QR code in our apps for a far better purpose. If we are creating a website using MEAN/MERN Stack or any JavaScript related technology, We can generate QR codes in order to build advanced apps.
Let’s set up our workspace by executing these commands:
Creating directory:
npm init -y
mkdir src
cd src
nano app.js
Installing package: We need to install an npm package in order to work ahead.
npm install qrcode
There are two ways we can use this library to generate QR codes. The first one is used for development and testing. Another one is used for deployment.
Let’s create the data that we want to hide in a QR code:
let data = {
    name:"Employee Name",
    age:27,
    department:"Police",
    id:"aisuoiqu3234738jdhf100223"
}
We need to convert data into a String format using JSON.stringify() method so that further operations can be performed easily.
// Converting into String data
let stringdata = JSON.stringify(data)
Two methods of qrcode package are used for encoding the data. The first method will print the code in the terminal itself. But this method will be useless for deployment. But it is good for testing purposes.
1. toString(text, [options], [cb(error, string)])
// Print the QR code to terminal
QRCode.toString(stringdata,{type:'terminal'}, function (err, url) {
   if(err) return console.log("error occurred")
   console.log(url)
 })
2. toDataURL(text, [options], [cb(error, url)])
// Get the base64 url
QRCode.toDataURL(stringdata, function (err, url) {
    if(err) return console.log("error occurred")
    console.log(url)
})
There is one additional toCanvas() method but its functionalities can be used within toDataURL() method.
Index.js
Javascript
// Require the packageconst QRCode = require('qrcode') // Creating the datalet data = {    name:"Employee Name",    age:27,    department:"Police",    id:"aisuoiqu3234738jdhf100223"} // Converting the data into String formatlet stringdata = JSON.stringify(data) // Print the QR code to terminalQRCode.toString(stringdata,{type:'terminal'},                    function (err, QRcode) {     if(err) return console.log("error occurred")     // Printing the generated code    console.log(QRcode)})   // Converting the data into base64QRCode.toDataURL(stringdata, function (err, code) {    if(err) return console.log("error occurred")     // Printing the code    console.log(code)})
Run index.js file using the following command:
node index.js
Output:
mridulmanochagfg
nikhatkhan11
Node.js-Misc
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PATCH method – Python requests

24 Oct, 2021
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PATCH request to a specified URL using requests.patch() method. Before checking out the PATCH method, let’s figure out what a Http PATCH request is –  
PATCH is a request method supported by HTTP used by the World Wide Web. It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent. 
Python’s requests module provides in-built method called patch() for making a PATCH request to a specified URI.Syntax –  
requests.patch(url, params={key: value}, args)
Example – Let’s try making a request to httpbin’s APIs for example purposes.  
Python3
import requests # Making a PATCH requestr = requests.patch('https://httpbin.org / patch', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.content)
save this file as request.py and through terminal run,  
python request.py
Output –  
 
The PATCH method is a request method supported by the HTTP protocol for making partial changes to an existing resource. The PATCH method provides an entity containing a list of changes to be applied to the resource requested using the HTTP URI. The list of changes are supplied in the form of a PATCH document. If the requested resource does not exist then the server may create the resource depending on the PATCH document media type and permissions. The changes described in the PATCH document must be semantically well defined but can have a different media type than the resource being patched. Frameworks such as XML, JSON can be used in describing the changes in the PATCH document. 
The main difference between the PUT and PATCH method is that the PUT method uses the request URI to supply a modified version of the requested resource which replaces the original version of the resource whereas the PATCH method supplies a set of instructions to modify the resource. If the PATCH document is larger than the size of the new version of the resource sent by the PUT method then the PUT method is preferred. 
sweetyty
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program for How to check if a given number is Fibonacci number?

06 Dec, 2018
Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ..
Examples :
Input : 8
Output : Yes

Input : 34
Output : Yes

Input : 41
Output : No

Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not.A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki).
// Java program to check if x is a perfect square  class GFG {    // A utility method that returns true if x is perfect square    static boolean isPerfectSquare(int x)    {        int s = (int)Math.sqrt(x);        return (s * s == x);    }      // Returns true if n is a Fibonacci Number, else false    static boolean isFibonacci(int n)    {        // n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both        // is a perfect square        return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);    }      // Driver method    public static void main(String[] args)    {        for (int i = 1; i <= 10; i++)            System.out.println(isFibonacci(i) ? i + " is a Fibonacci Number"                                              : i + " is a not Fibonacci Number");    }}// This code is contributed by Nikita Tiwari
1 is a Fibonacci Number
2 is a Fibonacci Number
3 is a Fibonacci Number
4 is a not Fibonacci Number
5 is a Fibonacci Number
6 is a not Fibonacci Number
7 is a not Fibonacci Number
8 is a Fibonacci Number
9 is a not Fibonacci Number
10 is a not Fibonacci Number

Please refer complete article on How to check if a given number is Fibonacci number? for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a Data Frame into a Numeric Matrix in R Programming – data.matrix() Function

16 Jun, 2020
data.matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
Syntax: data.matrix(df)
Parameters:df: Data frame to be converted.
Example 1:
# R program to convert a data frame# into a numeric matrix    # Creating a dataframe df1 = data.frame(   "Name" = c("Amar", "Akbar", "Ronald"),   "Language" = c("R", "Python", "C#"),   "Age" = c(26, 38, 22) )   # Printing data frameprint(df1)  # Converting into numeric matrixdf2 <- data.matrix(df1)df2
Output:
    Name Language Age
1   Amar        R  26
2  Akbar   Python  38
3 Ronald       C#  22
     Name Language Age
[1, ]    2        3  26
[2, ]    1        2  38
[3, ]    3        1  22

Example 2:
# R program to convert a data frame# into a numeric matrix    # Creating a dataframe df <- data.frame(sample(LETTERS[1:4], 8,                  replace = T), cbind(1:4, 1:8))colnames(df) <- c("x", "y", "z")  # Printing data frameprint(df)  # Converting into numeric matrixdf2 <- data.matrix(df)df2
Output:
  x y z
1 A 1 1
2 D 2 2
3 C 3 3
4 A 4 4
5 B 1 5
6 B 2 6
7 A 3 7
8 C 4 8
     x y z
[1, ] 1 1 1
[2, ] 4 2 2
[3, ] 3 3 3
[4, ] 1 4 4
[5, ] 2 1 5
[6, ] 2 2 6
[7, ] 1 3 7
[8, ] 3 4 8

R DataFrame-Function
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.