code-rag-bench/online-tutorials huggingface dataset:
Convert.ToSingle Method in C#

Convert a specified value to a single-precision floating-point number using the Convert.ToSingle() method in C#.
Here is our bool −
bool boolVal = false;
Now, let us use the ToSingle() method to convert the value to a single precision floating-point.
float floatVal;
floatVal = Convert.ToSingle(boolVal);
 Live Demo
using System;
public class Demo {
   public static void Main() {
      bool boolVal = false;
      float floatVal;
      floatVal = Convert.ToSingle(boolVal);
      Console.WriteLine("Converted {0} to {1}", boolVal, floatVal);
   }
}
Converted False to 0
Default values in a Map in C++ STL

01 Jun, 2022
Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ]  (e.g map<int,int> mpp;   mpp[1]; ) if the key is not present in the map , it gets added and its value is by default set to 0 (i.e value initialization gets invoked for the int) .To initialize the map with a random default value below is the approach:Approach:  
Declare a structure(say struct node) with a default value.Initialize Map with key mapped to struct node.
Declare a structure(say struct node) with a default value.
Initialize Map with key mapped to struct node.
Syntax:  
// For Structure 
struct Node {
   int value = -1;
}

// For Map with every key mapped to default value -1
Map < int, Node > M; 
Below is the illustration of the Map with a default value -1: 
CPP14
// C++ program to illustrate a Map// initialize with default value#include <bits/stdc++.h>using namespace std; // Structure Nodestruct Node {    int value = -1;}; // Driver Codeint main(){    // Map initialize with key value    // pair with each pair mapped with    // structure Node    map<int, Node> Map;     // Print the default value of 1    // store in Map    cout << Map[1].value << endl;     return 0;}
-1
 
gabaa406
chhabradhanvi
Anwesh Panda
STL
C++
Competitive Programming
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Object Oriented Programming in C++
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
How to specify the double border using CSS ?

30 Apr, 2021
The task is to specify the double border using CSS. In this article, we are going to use the border-style property to style the border.
Property used:
border-style property: This property is used to set the style of an element’s four borders.
Approach:
Create the HTML page with some elements.
Now, using the border-style property style the border with value double.
Example:
HTML
<!DOCTYPE html><html><head>    <style type="text/css">        body {            text-align: center;        }                  h1.double {            border-width: 5px;            border-style: double;            Border-color: green        }                  h1.double2 {            border-width: 10px;            border-style: double;            Border-color: green        }                  h1.double3 {            border-width: 15px;            border-style: double;            Border-color: green        }    </style></head>  <body>    <h1 class="double">GeeksForGeeks</h1>    <h1 class="double2">GeeksForGeeks</h1>    <h1 class="double3">GeeksForGeeks</h1></body>  </html>
Output:
CSS-Basics
CSS-Properties
CSS-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directory traversal tools in Python

27 Dec, 2019
os.walk() method of the OS module can be used for listing out all the directories. This method basically generates the file names in the directory tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
dirpath: A string that is the path to the directory
dirnames: All the sub-directories from root.
filenames: All the files from root and directories.
Syntax: os.walk(top, topdown=True, onerror=None, followlinks=False)
Parameters:top: Starting directory for os.walk().topdown: If this optional argument is True then the directories are scanned from top-down otherwise from bottom-up. This is True by default.onerror: It is a function that handles errors that may occur.followlinks: This visits directories pointed to by symlinks, if set to True.
Return Type: For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
Example: Suppose the directory looks like this:
We want to list out all the subdirectories and file inside the directory Tree. Below is the implementation.
# Python program to list out # all the sub-directories and files       import os     # List to store all  # directories L = []    # Traversing through Test for root, dirs, files in os.walk('Test'):         # Adding the empty directory to     # list     L.append((root, dirs, files))   print("List of all sub-directories and files:") for i in L:    print(i)
Output:
List of all sub-directories and files:
('Test', ['B', 'C', 'D', 'A'], [])
('Test/B', [], [])
('Test/C', [], ['test2.txt'])
('Test/D', ['E'], [])
('Test/D/E', [], [])
('Test/A', ['A2', 'A1'], [])
('Test/A/A2', [], [])
('Test/A/A1', [], ['test1.txt'])

The above code can be shortened using List Comprehension which is a more Pythonic way. Below is the implementation.
# Python program to list out # all the sub-directories and files             import os     # List comprehension to enter # all directories to list     L = [(root, dirs, files) for root, dirs, files, in os.walk('Test')]     print("List of all sub-directories and files:") for i in L:    print(i)
Output:
List of all sub-directories and files:
('Test', ['B', 'C', 'D', 'A'], [])
('Test/B', [], [])
('Test/C', [], ['test2.txt'])
('Test/D', ['E'], [])
('Test/D/E', [], [])
('Test/A', ['A2', 'A1'], [])
('Test/A/A2', [], [])
('Test/A/A1', [], ['test1.txt'])

Python directory-program
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
GATE | GATE-CS-2009 | Question 60

27 Jul, 2021
In the following process state transition diagram for a uniprocessor system, assume that there are always some processes in the ready state: Now consider the following statements:
I. If a process makes a transition D, it would result in 
   another process making transition A immediately.
II. A process P2 in blocked state can make transition E 
    while another process P1 is in running state.
III. The OS uses preemptive scheduling.
IV. The OS uses non-preemptive scheduling.
Which of the above statements are TRUE?
(A) I and II(B) I and III(C) II and III(D) II and IVAnswer: (C)Explanation: I is false. If a process makes a transition D, it would result in another process making transition B, not A.II is true. A process can move to ready state when I/O completes irrespective of other process being in running state or not.III is true because there is a transition from running to ready state.IV is false as the OS uses preemptive scheduling.
Watch GeeksforGeeks Video Explanation :
CPU Scheduling GATE Previous Year Questions with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0026:39 / 39:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=y1BbjvO_xog" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2016 (Set 1) | Question 45
GATE | GATE CS 1996 | Question 63
Delete a file in C#

Use File.Delete method to delete a file.
Firstly, set the path of the file you want to delete.
String myPath = @"C:\New\amit.txt";
Now, use the File.Delete method to delete the file.
File.Delete(myPath);
The following is the complete code −
 Live Demo
using System;
using System.IO;
public class Program {
   public static void Main() {
      String myPath = @"C:\New\amit.txt";
      Console.WriteLine("Deleting File");
      File.Delete(myPath);
   }
}
Deleting File
Ruby | Enumerable find_all() function

05 Dec, 2019
The find_all() of enumerable is an inbuilt method in Ruby returns the items in the enumerable which satisfies the given condition in the block. It returns an enumerator if no block is given.
Syntax: enu.find_all { |obj| block }
Parameters: The function takes a block whose condition is used to find the elements.
Return Value: It returns the items in the enum which satisfies the condition in the block. Iy t returns an enumerator if no block is given.
Example 1:
# Ruby program for find_all method in Enumerable  # Initialize enu = (1..10)  # Printsenu.find_all { |obj| obj % 2 == 1}
Output:
[1, 3, 5, 7, 9]

Example 2:
# Ruby program for find_all method in Enumerable  # Initialize enu = [1, 7, 10, 11]  # Printsenu.find_all
Output:
Enumerator: [1, 7, 10, 11]:find_all

Ruby Collections
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby For Beginners
Ruby | Array class find_index() operation
Ruby | String concat Method
Ruby | Types of Variables
Ruby | Array shift() function
Ruby on Rails Introduction
Python string length | len()

08 Jul, 2022
Python len() function returns the length of the string. 
Syntax: len(string) 
Return: It returns an integer which is the length of the string. 
len() methods with string in Python.
Python3
string = "Geeksforgeeks"print(len(string))
Output:
13
Here we are counting length of the tuples and list.
Python
# Python program to demonstrate the use of# len() method    # with tupletup = (1,2,3)print(len(tup))  # with listl = [1,2,3,4]print(len(l))
Output: 
3
4
Python3
print(len(True))
Output:
TypeError: object of type 'bool' has no len()
Python3
# Python program to demonstrate the use of# len() method    dic = {'a':1, 'b': 2}print(len(dic))  s = { 1, 2, 3, 4}print(len(s))
Output:
2
4
Python3
class Public:    def __init__(self, number):        self.number = number    def __len__(self):        return self.number      obj = Public(12)print(len(obj))
Output:
12
Time complexity : 
len() function  has time complexity of O(1). in average and amortized case
kumar_satyam
rajeev0719singh
devendrasalunke
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Setup And Use Anonsurf On kali Linux

17 Oct, 2021
Anonsurf is one of the good anonymizing tools of Linux distribution. It helps us make our network tunnel secure. This tool uses TOR iptables to anonymize our network system. 
First of all, you can make a separate directory for this tool for your convenience and git clone the following URL or you can simply run this command in the terminal:
For a separate directory:
mkdir Anonsurf && cd Anonsurf
Clone the URL in your terminal:
git clone https://github.com/Und3rf10w/kali-anonsurf.git
Now change the directory and go to the kali-anonsurf run the installer script:
sudo ./installer.sh
Example 1: Now run this command for anonsurf start.
sudo anonsurf
Example 2: To start this tool just simply run this command, a pop-up will show on your screen.
anonsurf start
If you want to kill all the background processes, you can choose yes or just go ahead. It will clear the miscellaneous space from your disk.
Example 3: If this tool isn’t running and you are running the stop command a pop up will show as shown in figure
anonsurf stop
Example 4: You can restart it again if you face any problem during the task.
anonsurf restart
Example 5: Change id
This tool connects our system with the tor browser and if we want to change or IP address then we can use this command, in the following images you can see our system is connected with tor or not.
anonsurf changeid
Before:
After:
Example 6: You can check what is current IP address is after connecting with tor network.
anonsurf myip
Example 7: Change status
This helps us to check that our tool is still running or not, you can find details of browser download/upload speed.
anonsurf status
That’s all was overview for this tool now you can explore yourself many things. After finishing your work you can stop it by stop command.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
wxPython – Change font colour of RadioBox

01 Sep, 2021
In this article we are going to learn how can we change the foreground colour of Radio Box present in the frame. In order to do that we are going to use SetForegroundColour() method. SetForegroundColour() function takes wx.Colour argument which will be used as foreground colour for Radio Box. 
Syntax: wx.RadioBox.SetForegroundColour(self, colour)Parameters 
Code Example:  
Python3
import wx  class FrameUI(wx.Frame):     def __init__(self, parent, title):        super(FrameUI, self).__init__(parent, title = title, size =(300, 200))         # function for in-frame components        self.InitUI()     def InitUI(self):        # parent panel for radio box        pnl = wx.Panel(self)         # list of choices        lblList = ['Radio One', 'Radio Two']         # create radio box containing above list        self.rbox = wx.RadioBox(pnl, label ='RadioBox', pos =(80, 10), choices = lblList,                                          majorDimension = 1, style = wx.RA_SPECIFY_ROWS)         # change foreground colour for radio box        self.rbox.SetForegroundColour((0, 0, 255, 255))         # set frame in centre        self.Centre()        # set size of frame        self.SetSize((400, 250))        # show output frame        self.Show(True)  # wx App instanceex = wx.App()# Example instanceFrameUI(None, 'RadioButton and RadioBox')ex.MainLoop()
Output Window:  
 
abhishek0719kadiyan
Python wxPython-RadioBox
Python-gui
Python-wxPython
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
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
How to count the number of words in a string in PHP ?

27 May, 2020
Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:
Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.
Syntax:
str_word_count(string, return, char)

Example:
PHP
<?php// PHP program to count number of// words in a string     $str = "  Geeks for Geeks  ";     // Using str_word_count() function to// count number of words in a string$len = str_word_count($str);  // Printing the resultecho $len; ?>
3
Approach 2: Here the idea is to use trim(), preg_replace(), count() and explode() method. 
Step 1: Remove the trailing and leading white spaces using the trim() method and remove the multiple whitespace into a single space using preg_replace() method.
Step 2: Convert the string into an array using the explode() method.
Step 3: Now count() method counts the number of elements in an array.
Step 4: Resultant is the number of words in a string.
Example:
PHP
<?php// PHP program to count number// of words in a string     // Function to count the wordsfunction get_num_of_words($string) {      $string = preg_replace('/\s+/', ' ', trim($string));      $words = explode(" ", $string);      return count($words);}  $str = "  Geeks  for    Geeks  ";     // Function call $len = get_num_of_words($str);  // Printing the resultecho $len; ?>
3
Approach 3: Here the idea is to use trim(), substr_count(), and str_replace() method. 
Step 1: Remove the trailing and leading white spaces using the trim() method.
Step 2: Convert the multiple white spaces into single space using the substr_count() and str_replace() method.
Step 3: Now counts the number of word in a string using substr_count($str, ” “)+1 and return the result.
Example:
PHP
<?php// PHP program to count number// of word in a string     // Function to count the wordsfunction get_num_of_words($string) {    $str = trim($string);      while (substr_count($str, "  ") > 0) {        $str = str_replace("  ", " ", $str);    }      return substr_count($str, " ")+1;}  $str = "  Geeks  for    Geeks  ";    // Function call $len = get_num_of_words($str);  // Printing the resultecho $len; ?>
3
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the day of the week in JavaScript?

To get the day of the week, use the JavaScript getDay() method. JavaScript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
You can try to run the following code to get the day of the week in JavaScript −
Live Demo
<html>
   <head>
      <title>JavaScript getDay Method</title>
   </head>
   <body>
      <script>
         var dt = new Date("December 25, 1995 23:15:00");
         document.write("Day of the week: " + dt.getDay() );
      </script>
   </body>
</html>
Day of the week: 1
How abstraction is achieved using interfaces in Java?

Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.
Since all the methods of the interface are abstract and the user doesn’t know how a method is written except the method signature/prototype. Using interfaces, you can achieve (complete) abstraction.
An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
To create an object of this type you need to implement this interface, provide a body for all the abstract methods of the interface and obtain the object of the implementing class.
The user who want to use the methods of the interface, he only knows the classes that implement this interface and their methods, information about the implementation is completely hidden from the user, thus achieving 100% abstraction.
 Live Demo
interface Person{
   void dsplay();
}
class Student implements Person{
   public void dsplay() {
      System.out.println("This is display method of the Student class");
   }
}
class Lecturer implements Person{
   public void dsplay() {
      System.out.println("This is display method of the Lecturer class");
   }
}
public class AbstractionExample{
   public static void main(String args[]) {
      Person person1 = new Student();
      person1.dsplay();
      Person person2 = new Lecturer();
      person2.dsplay();
   }
}
This is display method of the Student class
This is display method of the Lecturer class
C++ Algorithm Library - fill_n() Function

The C++ function std::algorithm::fill_n() assigns value to the first n elements of the sequence pointed by first.
Following is the declaration for std::algorithm::fill_n() function form std::algorithm header.
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val);

first − Output iterators to the initial positions.
first − Output iterators to the initial positions.
n − Number of elements to fill.
n − Number of elements to fill.
val − Value to be used to fill the range.
val − Value to be used to fill the range.
Returns an iterator pointing to the element that follows the last element filled.
Throws an exception if either element assignment or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear.
The following example shows the usage of std::algorithm::fill_n() function.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   vector<int> v(5, 1);

   fill_n(v.begin() + 2, 3, 4);

   cout << "Vector contains following elements" << endl;

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector contains following elements
1
1
4
4
4

 Print
 Add Notes
 Bookmark this page
Java Examples - Printing Array using Method

How to use  method overloading for printing different types of array ?
This example displays the way of using overloaded method for printing types of array (integer, double and character).
public class MainClass {
   public static void printArray(Integer[] inputArray) {
      for (Integer element : inputArray){
         System.out.printf("%s ", element);
         System.out.println();
      }
   }
   public static void printArray(Double[] inputArray) {
      for (Double element : inputArray){
         System.out.printf("%s ", element);
         System.out.println();
      }
   }
   public static void printArray(Character[] inputArray) {
      for (Character element : inputArray){
         System.out.printf("%s ", element);
         System.out.println();
      }
   }
   public static void main(String args[]) {
      Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
      Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
      Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
      
      System.out.println("Array integerArray contains:");
      printArray(integerArray);
      
      System.out.println("\nArray doubleArray contains:");
      printArray(doubleArray);
      
      System.out.println("\nArray characterArray contains:");
      printArray(characterArray);
   }
}
The above code sample will produce the following result.
Array integerArray contains:
1 
2 
3 
4 
5 
6 

Array doubleArray contains:
1.1 
2.2 
3.3 
4.4 
5.5 
6.6 
7.7 

Array characterArray contains:
H 
E 
L 
L 
O 

 Print
 Add Notes
 Bookmark this page
Convert string to integer in Python - GeeksforGeeks

29 Apr, 2020
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.
Below is the list of possible ways to convert an integer to string in python:
1. Using int() function
Syntax: int(string)
Example:
num = '10'  # check and print type num variableprint(type(num))   # convert the num into string converted_num = int(num)  # print type of converted_numprint(type(converted_num))  # We can check by doing some mathematical operationsprint(converted_num + 20)
As a side note, to convert to float, we can use float() in Python
num = '10.5'  # check and print type num variableprint(type(num))   # convert the num into string converted_num = float(num)  # print type of converted_numprint(type(converted_num))  # We can check by doing some mathematical operationsprint(converted_num + 20.5)
2. Using float() function
We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer)
Syntax: float(string)
Example:
a = '2'b = '3'  # print the data type of a and bprint(type(a))print(type(b))  # convert a using floata = float(a)  # convert b using intb = int(b)  # sum both integerssum = a + b  # as strings and integers can't be added# try testing the sumprint(sum)
Output:
class 'str'
class 'str'
5.0
Note: float values are decimal values that can be used with integers for computation.
python-basics
Python-datatype
python-string
Python
Write From Home
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 infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
Similarities and Difference between Java and C++
matplotlib.pyplot.magnitude_spectrum() in Python

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The magnitude_spectrum() function in pyplot module of matplotlib library is used to plot the magnitude spectrum. Generally, it compute the magnitude spectrum of sequence and plotting is done.
Syntax: magnitude_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is a sequence of data.
Fs : This parameter is a scalar. Its default value is 2.
window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()
sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’.
pad_to : This parameter contains the integer value to which the data segment is padded.
Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0
Returns: This returns the following:
spectrum :This returns the angle spectrum in radians.
freqs :This returns the frequencies corresponding to the elements in spectrum.
line : This returns the line created by this function.
The resultant is (spectrum, freqs, line)
Below examples illustrate the matplotlib.pyplot.magnitude_spectrum() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np   np.random.seed(10**5)   dt = 0.0001Fs = 1 / dtgeeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90,                    7.80, 15.00, 22.80, 34.90, 57.30])  nse = np.random.randn(len(geeks))r = np.exp(-geeks / 0.05)   s = 0.1 * np.sin(2 * np.pi * geeks) + nse   # plot magnitude_spectrumplt.magnitude_spectrum(s, Fs = Fs)plt.title('matplotlib.pyplot.magnitude_spectrum() function Example',                                                  fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np   np.random.seed(0)   dt = 0.01Fs = 1 / dtt = np.arange(0, 10, dt)nse = np.random.randn(len(t))r = np.exp(-t / 0.05)   cnse = np.convolve(nse, r)*dtcnse = cnse[:len(t)]s = 0.1 * np.sin(2 * np.pi * t) + cnse   # plot simple spectrumplt.subplot(2, 1, 1)plt.plot(t, s)plt.title('matplotlib.pyplot.magnitude_spectrum() function Example',                                                  fontweight ="bold")  plt.subplot(2, 1, 2)plt.magnitude_spectrum(s, Fs = Fs)  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQLite - PRIMARY KEY

A primary key is a field in a table which uniquely identifies the each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).
Note: You would use these concepts while creating database tables.
Here is the syntax to define ID attribute as a primary key in a COMPANY table.
CREATE TABLE COMPANY(
   ID   INT       PRIMARY KEY     ,
   NAME          TEXT     NOT NULL,
   AGE  INT              NOT NULL UNIQUE,
   ADDRESS  CHAR (25) ,
   SALARY   REAL  ,       
   
);

To create a PRIMARY KEY constraint on the "ID" column when COMPANY table already exists, use the following SQLite syntax −
ALTER TABLE COMPANY ADD PRIMARY KEY (ID);

For defining a PRIMARY KEY constraint on multiple columns, use the following SQLite syntax −
CREATE TABLE COMPANY(
   ID   INT       PRIMARY KEY     ,
   NAME          TEXT     NOT NULL,
   AGE  INT              NOT NULL UNIQUE,
   ADDRESS  CHAR (25) ,
   SALARY   REAL  ,       
   
);

To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when COMPANY table already exists, use the following SQLite syntax −
ALTER TABLE COMPANY 
   ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);

You can clear the primary key constraints from the table, Use syntax −
ALTER TABLE COMPANY DROP PRIMARY KEY ;
Add packages to Anaconda environment in Python

21 Aug, 2021
Let’s see some methods that can be used to install packages to Anaconda environment. 
There are many ways one can add pre-built packages to anaconda environment. So, let’s see how to direct the path in anaconda and install them. 
Using pip command : 
Open Anaconda Command prompt as administratorUse cd\ to come out of set directory or path.Run pip install command. 
Open Anaconda Command prompt as administrator
Use cd\ to come out of set directory or path.
Run pip install command. 
pip install numpy
pip install scikit-learn
  Using git : 
Download git filesClone or download git hub files in some directory.Open Anaconda Command prompt as administrator.Use cd C:\Users\... to locate downloaded site.Then run pip install setup.py.
Download git files
Clone or download git hub files in some directory.
Open Anaconda Command prompt as administrator.
Use cd C:\Users\... to locate downloaded site.
Then run pip install setup.py.
  Using wheel :  
Download wheel package.Download binary files or .whl file from authentic website.Open Anaconda Command prompt as administrator.Use cd C:\Users\... to locate downloaded site.Then run pip install ___.whl
Download wheel package.
Download binary files or .whl file from authentic website.
Open Anaconda Command prompt as administrator.
Use cd C:\Users\... to locate downloaded site.
Then run pip install ___.whl
Using Conda forge Command : This type of installation will guarantee that package will be downloaded to the system. Because this type of installation resolves environments, package-package conflicts, etc.  
Self Upgrade related packages to the downloading package.Open Anaconda Command prompt as administrator.Then run conda install -c conda-forge ____
Self Upgrade related packages to the downloading package.
Open Anaconda Command prompt as administrator.
Then run conda install -c conda-forge ____
conda install -c conda-forge opencv 
surindertarika1234
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Closest Pair to Kth index element in Tuple

10 Jun, 2020
Sometimes, while working with Python records, we can have a problem in which we need to find the tuple nearest to certain tuple, query on a particular index. This kind of problem can have application in data domains such as web development. Let’s discuss certain ways in which this task can be performed.
Input :test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]tup = (17, 23)K = 2
Output : (19, 23)Input :test_list = [(3, 4, 9), (5, 6, 7)]tup = (1, 2, 5)K = 3Output : (5, 6, 7)
Method #1 : Using enumerate() + loopThe combination of above functions offer brute force way to solve this problem. In this, we use enumerate() to monitor index and abs() to keep the minimum difference updated checked for each element over a loop.
# Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple# Using enumerate() + loop  # initializing listtest_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]  # printing original listprint("The original list is : " + str(test_list))  # initializing tupletup = (17, 23)  # initializing K K = 1  # Closest Pair to Kth index element in Tuple# Using enumerate() + loopmin_dif, res = 999999999, Nonefor idx, val in enumerate(test_list):    dif = abs(tup[K - 1] - val[K - 1])    if dif < min_dif:        min_dif, res = dif, idx  # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res])) 
The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
The nearest tuple to Kth index element is : (19, 23)

 
Method #2 : Using min() + lambdaThe combination of above functions offer shorthand to solve this problem. In this, we use min() to find minimum element difference and lambda function is used to perform iterations and computations.
# Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple# Using min() + lambda  # initializing listtest_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]  # printing original listprint("The original list is : " + str(test_list))  # initializing tupletup = (17, 23)  # initializing K K = 1  # Closest Pair to Kth index element in Tuple# Using min() + lambdares = min(range(len(test_list)), key = lambda sub: abs(test_list[sub][K - 1] - tup[K - 1]))  # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res])) 
The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
The nearest tuple to Kth index element is : (19, 23)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sum 2D array in Python using map() function

In this tutorial, we are going to find the sum of a 2D array using map function in Python.
The map function takes two arguments i.e., function and iterable. It passes every element of the iterable to the function and stores the result in map object. We can covert the map object into an iterable.
Let's see how to find the sum of the 2D array using the map function.
Initialize the 2D array using lists.
Initialize the 2D array using lists.
Pass the function sum and 2D array to the map function.
Pass the function sum and 2D array to the map function.
Find the sum of resultant map object and print it.
Find the sum of resultant map object and print it.
See the code below.
 Live Demo
# initializing the 2D array
array = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
]
# passing the sum, array to function
result = list(map(sum, array))
# see the result values
# it contains sum of every sub array
print(result)
If you run the above code, you will get the following output.
[6, 15, 24]
Now, find the sum of the result using the same sum function.
# finding the sum of result
print(sum(result))
If you add the above code snippet the above program and run it, you will get the following output.
45
If you have any doubts in the tutorial, mention them in the comment section.
Program for Celsius To Fahrenheit conversion

24 May, 2022
Given a Temperature ‘n’ in Celsius scale, your task is to convert it into Fahrenheit scale.Examples: 
Input : 0
Output : 32

Input : -40
Output : -40
Formula for converting Celsius scale to Fahrenheit scale 
 T(°F) = T(°C) × 9/5 + 32
C
C++
Java
Python3
C#
PHP
Javascript
/* Program to convert temperature from Celsius to Fahrenheit*/#include <stdio.h> //function for conversionfloat celsius_to_fahrenheit(float c){ return ((c * 9.0 / 5.0) + 32.0);} int main() {     float c = 20.0;        // passing parameter to function and printing the value      printf("Temperature in Fahrenheit : %0.2f",celsius_to_fahrenheit(c));    return 0;}
// CPP program to convert Celsius// scale  to Fahrenheit scale#include <bits/stdc++.h>using namespace std; // function to convert Celsius// scale to Fahrenheit scalefloat Cel_To_Fah(float n){    return ((n * 9.0 / 5.0) + 32.0);} // driver codeint main(){    float n = 20.0;    cout << Cel_To_Fah(n);    return 0;}
// Java program to convert Celsius// scale to Fahrenheit scaleclass GFG{// function to convert Celsius// scale to Fahrenheit scalestatic float Cel_To_Fah(float n){    return ((n * 9.0f / 5.0f) + 32.0f);} // Driver codepublic static void main(String[] args) {    float n = 20.0f;    System.out.println(Cel_To_Fah(n));}} // This code is contributed by Anant Agarwal.
# Python code to convert Celsius scale# to Fahrenheit scaledef Cel_To_Fah(n):         # Used the formula    return (n*1.8)+32 # Driver Coden = 20print(int(Cel_To_Fah(n))) # This code is contributed by Chinmoy Lenka
// C# program to convert Celsius// scale to Fahrenheit scaleusing System; class GFG  {     // function to convert Celsius// scale to Fahrenheit scalestatic float Cel_To_Fah(float n){    return ((n * 9.0f / 5.0f) + 32.0f);} // Driver codepublic static void Main(){    float n = 20.0f;    Console.Write(Cel_To_Fah(n));}} // This code is contributed by Nitin Mittal.
<?php// PHP program to convert Celsius// scale to Fahrenheit scale // function to convert Celsius// scale to Fahrenheit scalefunction Cel_To_Fah($n){    return (($n * 9.0 / 5.0) + 32.0);}     // Driver Code    $n = 20.0;    echo Cel_To_Fah($n);     // This code is contributed by nitin mittal?>
<script> // Javascript program to convert Celsius// scale to Fahrenheit scale // function to convert Celsius// scale to Fahrenheit scalefunction Cel_To_Fah(n){    return ((n * 9.0 / 5.0) + 32.0);} // driver code     let n = 20.0;    document.write(Cel_To_Fah(n));  // This code is contributed by Mayank Tyagi </script>
Output: 
68
Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.
nitin mittal
mayanktyagi1709
sonawanejaydeep11
rkbhola5
rohitsingh07052
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Python set operations (union, intersection, difference and symmetric difference)

18 Dec, 2017
This article demonstrates different operations on Python sets.Examples:
Input :
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}

Output :
 Union : [0, 1, 2, 3, 4, 5, 6, 8]
 Intersection : [2, 4]
 Difference : [8, 0, 6]
 Symmetric difference : [0, 1, 3, 5, 6, 8]

In Python, below quick operands can be used for different operations.
| for union.& for intersection.– for difference^ for symmetric difference
# Program to perform different set operations# as we do in  mathematics  # sets are defineA = {0, 2, 4, 6, 8};B = {1, 2, 3, 4, 5};  # unionprint("Union :", A | B)  # intersectionprint("Intersection :", A & B)  # differenceprint("Difference :", A - B)  # symmetric differenceprint("Symmetric difference :", A ^ B)
Output:
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))

python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.str.isdigit()

23 Aug, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.isdigit() method is used to check if all characters in each string in series are digits. Whitespace or any other character occurrence in the string would return false. If the number is in decimal, then also false will be returned since this is a string method and ‘.’ is a special character and not a decimal in strings.
Syntax: Series.str.isdigit()
Return Type: Boolean series, Null values might be included too depending upon caller series.
To download the CSV used in code, click here.
In the following examples, the data frame used contains data on some NBA players. The image of data frame before any operations is attached below.
Example:In this example, .isdigit() method is applied on the Age column. Before doing any operations, null rows are removed using .dropna() to avoid errors.Since the Age column is imported as Float dtype, it is first converted into string using .astype() method. After that the isdigit() is applied twice, first on the original series and after that ‘.’ is removed using str.replace() method to see the output after removing special characters.
# importing pandas moduleimport pandas as pd  # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # removing null values to avoid errorsdata.dropna(inplace = True)  # converting dtype to stringdata["Age"]= data["Age"].astype(str)  # removing '.'data["Age new"]= data["Age"].str.replace(".", "")  # creating bool series with original columndata["bool_series1"]= data["Age"].str.isdigit()  # creating bool series with new columndata["bool_series2"]= data["Age new"].str.isdigit()  # displaydata.head(10)
Output:As shown in output image, the Boolean series was false until decimal was present in string. After removing it, the new series has True for all values.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.width() function in Python

20 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set or return the line thickness. Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned.
Syntax :
turtle.width(width=None)
turtle.pensize(width=None)

Note: This method has Aliases: pensize and width and requires only one argument “width — positive number”.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle     # forward turtle by 100turtle.forward(100)  # set turtle width to 4turtle.width(4)  # forward turtle by 100# in right directionturtle.right(90)turtle.forward(100)
Output :
Example 2 :
Python3
# import packageimport turtle   # loop for patternfor i in range(15):      # set turtle width  turtle.width(15-i)      # motion for pattern  turtle.forward(50+15*i)  turtle.right(90)
Output :
In this above example, we decrease the size of the turtle at every move so the size of the line of the outer lines is smaller than that of the inner lines.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
numpy string operations | find() function

23 Jan, 2019
numpy.core.defchararray.find(arr, sub, start=0, end=None) is another function for doing string operations in numpy.It returns the lowest index in the string where substring sub is found for each element in arr within the range start to end.It returns -1 otherwise.
Parameters:arr : array_like of str or unicode.sub : [str or unicode] The substring which to be searched.start : [ int, optional] The starting location in each string.end : [ int, optional] The ending location in each string.
Returns : [ndarray] Output array of ints.
Code #1 :
# Python program explaining# numpy.char.find() method   # importing numpy as geekimport numpy as geek  # input arrays  in_arr = geek.array(['aAaAaA', 'baA', 'abBABba'])print ("Input array : ", in_arr)   # output arrays out_arr = geek.char.find(in_arr, sub ='A')print ("Output array: ", out_arr) 
Input array :  ['aAaAaA' 'baA' 'abBABba']
Output array:  [1 2 3]


 Code #2 :
# Python program explaining# numpy.char.find() method   # importing numpy as geekimport numpy as geek  # input arrays  in_arr = geek.array(['aAaAaA', 'aA', 'abBABba'])print ("Input array : ", in_arr)   # output arrays out_arr = geek.char.find(in_arr, sub ='a', start = 3, end = 7)print ("Output array: ", out_arr) 
Input array :  ['aAaAaA' 'aA' 'abBABba']
Output array:  [ 4 -1  6]

Python numpy-String Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.