code-rag-bench/online-tutorials huggingface dataset:
Python | Check if string ends with any string in given list - GeeksforGeeks

29 May, 2019
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using filter() + endswith()
The combination of the above function can help to perform this particular task. The filter method is used to check for each word and endswith method tests for the suffix logic at target list.
# Python3 code to demonstrate# Checking for string match suffix# using filter() + endswith()  # initializing string test_string = "GfG is best"  # initializing suffix listsuff_list = ['best', 'iss', 'good']  # printing original string print("The original string : " + str(test_string))  # using filter() + endswith()# Checking for string match suffixres = list(filter(test_string.endswith, suff_list)) != []  # print resultprint("Does string end with any suffix list sublist ? : " + str(res))
The original string : GfG is best
Does string end with any suffix list sublist ? : True

 
Method #2 : Using endswith()
As an improvement to the above method, it is not always necessary to include filter method for comparison. This task can be handled solely by supplying a suffix check list as an argument to endswith method as well.
# Python3 code to demonstrate# Checking for string match suffix# using endswith()  # initializing string test_string = "GfG is best"  # initializing suffix listsuff_list = ['best', 'iss', 'good']  # printing original string print("The original string : " + str(test_string))  # using endswith()# Checking for string match suffixres = test_string.endswith(tuple(suff_list))  # print resultprint("Does string end with any suffix list sublist ? : " + str(res))
The original string : GfG is best
Does string end with any suffix list sublist ? : True

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
HashSet remove() Method in Java - GeeksforGeeks

05 Oct, 2021
HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation errors before in version JDK 1 and JDK1.1. 
Note: This method returns true if the specified element is present in the HashSet otherwise it returns boolean false.
Syntax: 
HashSet.remove(Object O)
Parameters: The parameter O is of the type of HashSet and specifies the element to be removed from the HashSet.
Return Value: Boolean true and false 
Example 1:
Java
// Java code to illustrate// HashSet.remove() method// over String Elements // Importing required classesimport java.util.*; // Main class// HashSet demopublic class GFG {     // Main driver method    public static void main(String args[])    {         // Creating an empty HashSet        // Declaring object of string type        HashSet<String> set = new HashSet<String>();         // Adding custom input elements into the Set        // using add() method        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("For");        set.add("Geeks");         // Displaying the HashSet(object elements)        System.out.println("HashSet: " + set);         // Removing elements        // using remove() method        set.remove("Geeks");        set.remove("For");        set.remove("Welcome");         // Now displaying the HashSet after removal        // of elements from it        System.out.println(            "HashSet after removing elements: " + set);    }}
HashSet: [Geeks, For, Welcome, To]
HashSet after removing elements: [To]
Example 2:
Java
// Java code to illustrate remove()// method of Hashset class// over Integer Elements // Importing required classesimport java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {         // Creating an empty HashSet        // Declaring object of integer type        HashSet<Integer> set = new HashSet<Integer>();         // Adding custom input elements into the Set        // using add() method        set.add(5);        set.add(3);        set.add(1);        set.add(4);        set.add(3);         // Displaying the HashSet(object elements)        System.out.println("HashSet: " + set);         // Removing elements        // using remove() method        set.remove(3);        set.remove(1);         // Now displaying the HashSet after removal        // of elements from it        System.out.println(            "HashSet after removing elements: " + set);    }}
HashSet: [1, 3, 4, 5]
HashSet after removing elements: [4, 5]
solankimayank
Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Remove All White Space from Character String in R - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to remove all the white space from character string in R Programming Language.
We can do it in these ways:
Using gsub() function.
Using str_replace_all() function.
gsub() function is used to remove the space by removing the space in the given string.
Syntax: gsub(” “, “”, input_string)  
where
First parameter takes the space to check the string has spaceSecond parameter replaces with “No space” if there is space in the stringThird parameter is the input string.
First parameter takes the space to check the string has space
Second parameter replaces with “No space” if there is space in the string
Third parameter is the input string.
Example: R program to remove white space from character string using gsub() function.
R
# consider the stringdata = "Hello Geek welocme    to Geeksforgeeks"print("Original String:")print(data)  print("After remove white space:")  # remove white spacesprint(gsub(" ","",data))
Output:
[1] "Original String:"
[1] "Hello Geek welocme    to Geeksforgeeks"
[1] "After remove white space:"
[1] "HelloGeekwelocmetoGeeksforgeeks"
This function is used to replace white space with empty, It is similar to gsub() function. It is available in stringr package. To install this module type the below command in the terminal.
install.packages("stringr")
Here we use str_replace_all() function to remove white space in a string.
Syntax: str_replace_all(input_string,” “, “”)  
where
First parameter takes the input stringSecond parameter replaces with “No space” if there is space in the stringThird parameter is to check the string has space
First parameter takes the input string
Second parameter replaces with “No space” if there is space in the string
Third parameter is to check the string has space
Example: R program to remove white space in the character string
R
# consider the stringstring="Hello Geek welocme    to Geeksforgeeks"print("Original String:")print(string)  print("After remove white space:")  # remove white spacesprint(str_replace_all(string," ",""))
Output:
[1] "Original String:"
[1] "Hello Geek welocme    to Geeksforgeeks"
[1] "After remove white space:"
[1] "HelloGeekwelocmetoGeeksforgeeks"
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
Python program to convert URL Parameters to Dictionary items - GeeksforGeeks

11 Oct, 2020
Given URL Parameters string, convert to dictionary items.
Input : test_str = ‘gfg=4&is=5’ Output : {‘gfg’: [‘4’], ‘is’: [‘5’]} Explanation : gfg’s value is 4.
Input : test_str = ‘gfg=4’ Output : {‘gfg’: [‘4’]} Explanation : gfg’s value is 4 as param.  
Method #1 : Using urllib.parse.parse_qs()
This is default inbuilt function which performs this task, it parses and the keys are formed from LHS of “=” and return list of values that are in RHS values for the parameters. Thus, import external urllib.parse(), to enable this to work.
Python3
# import moduleimport urllib.parse  # initializing stringtest_str = 'gfg=4&is=5&best=yes'  # printing original stringprint("The original string is : " + str(test_str))  # parse_qs gets the Dictionary and value listres = urllib.parse.parse_qs(test_str)  # printing resultprint("The parsed URL Params : " + str(res))
The original string is : gfg=4&is=5&best=yesThe parsed URL Params : {‘gfg’: [‘4’], ‘is’: [‘5’], ‘best’: [‘yes’]}
Method #2 : Using findall() + setdefault()
In this, we get all the parameters using findall(), and then assign keys and values using setdefault() and loop.
Python3
import re  # initializing stringtest_str = 'gfg=4&is=5&best=yes'  # printing original stringprint("The original string is : " + str(test_str))  # getting all paramsparams = re.findall(r'([^=&]+)=([^=&]+)', test_str)  # assigning keys with valuesres = dict()for key, val in params:        res.setdefault(key, []).append(val)  # printing resultprint("The parsed URL Params : " + str(res))
The original string is : gfg=4&is=5&best=yesThe parsed URL Params : {‘gfg’: [‘4’], ‘is’: [‘5’], ‘best’: [‘yes’]}
Python dictionary-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Node.js os.endianness() Method - GeeksforGeeks

13 Oct, 2021
Endianness refers to the order of bits in a sequence within a binary representation of a number.
The os.endianness() method is an inbuilt application programming interface of the os module which is used to get endianness of the CPU of the computer for which the node.js is compiled.
Syntax:
os.endianness()
Parameters: This method does not accept any parameters.
Return Value: This method returns a string value that specifies the endianness of the CPU. The returned string will be either BE (for big endian) or LE (for little endian).
LE: It is the most significant bits/values in the sequence that is stored in higher memory address.
BE: It is the most significant bits/values in the sequence that is stored in lower memory address.
Below examples illustrate the use of os.endianness() method in Node.js:
Example 1:
// Node.js program to demonstrate the   // os.endianness() method  // Allocating os moduleconst os = require('os');  // Printing os.endianness() valueconsole.log(os.endianness());
Output:
LE
Example 2:
// Node.js program to demonstrate the   // os.endianness() method  // Allocating os moduleconst os = require('os');  // Printing os.endianness() valueswitch(os.endianness()) {    case 'LE':      console.log("CPU is little endian format");      break;          case 'BE':      console.log("CPU is big endian format");      break;          default:      colsole.log("Unknown endianness");}
Output:
CPU is little endian format
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_endianness
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to list tables using SQLite3 in Python ? - GeeksforGeeks

09 May, 2021
In this article, we will discuss how to list all the tables in the SQLite database using Python. 
Database Used:
All tables which are present inside our database
1. Creating a connection object using connect() method,
sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')
2. Created one SQL query with which we will search a list of all tables which are present inside the sqlite3 database.
sql_query = """SELECT name FROM sqlite_master  
  WHERE type='table';"""
3. Using Connection Object, we are creating a cursor object.
cursor = sqliteConnection.cursor()
4. Using execute() methods, we will execute the above SQL query.
cursor.execute(sql_query)
5. Finally, We will print a list of all tables which are present inside the sqlite3 database.
print(cursor.fetchall())
Below is the implementation.
Python3
# Importing Sqlite3 Moduleimport sqlite3  try:          # Making a connection between sqlite3     # database and Python Program    sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')          # If sqlite3 makes a connection with python    # program then it will print "Connected to SQLite"    # Otherwise it will show errors    print("Connected to SQLite")      # Getting all tables from sqlite_master    sql_query = """SELECT name FROM sqlite_master     WHERE type='table';"""      # Creating cursor object using connection object    cursor = sqliteConnection.cursor()          # executing our sql query    cursor.execute(sql_query)    print("List of tables\n")          # printing all tables list    print(cursor.fetchall())  except sqlite3.Error as error:    print("Failed to execute the above query", error)      finally:        # Inside Finally Block, If connection is    # open, we need to close it    if sqliteConnection:                  # using close() method, we will close         # the connection        sqliteConnection.close()                  # After closing connection object, we         # will print "the sqlite connection is         # closed"        print("the sqlite connection is closed")
Output:
Final output
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Java Long decode() method with Examples - GeeksforGeeks

05 Dec, 2018
The java.lang.Long.decode() is a built in function in java that decodes a String into a Long. It accepts decimal, hexadecimal, and octal numbers.
Syntax:
public static Long decode(String number) throws NumberFormatException 

Parameter: 
number-  the number that has to be decoded into a Long. 

Error and Exceptions:
NumberFormatException: If the String does not contain a parsable long, the program returns this error.
Returns: It returns the decoded string.
Program 1: The program below demonstrates the working of function.
// Java program to demonstrate// of java.lang.Long.decode() methodimport java.lang.Math;  class GFG {      // driver code    public static void main(String args[])    {          // demonstration of function        Long l = new Long(14);        String str = "54534";          System.out.println("Number = "                        + l.decode(str));    }}
Output:
Number = 54534 
Program 2: The program demonstrates the conversions using decode() function
// Java program to demonstrate// of java.lang.Long.decode() methodimport java.lang.Math;  class GFG {      // driver code    public static void main(String args[])    {        // demonstration of conversions        String decimal = "10"; // Decimal        String hexa = "0XFF"; // Hexa        String octal = "067"; // Octal          // convert decimal val to number using decode() method        Integer number = Integer.decode(decimal);        System.out.println("Decimal [" + decimal + "] = " + number);          number = Integer.decode(hexa);        System.out.println("Hexa [" + hexa + "] = " + number);          number = Integer.decode(octal);        System.out.println("Octal [" + octal + "] = " + number);    }}
Output:
Decimal [10] = 10
Hexa [0XFF] = 255
Octal [067] = 55
Program 3: The program demonstrates error and exceptions.
// Java program to demonstrate// of java.lang.Long.decode() methodimport java.lang.Math;  class GFG {      // driver code    public static void main(String args[])    {        // demonstration of errorand exception when        // a non-parsable Long is passed          String decimal = "1A";          // throws an error        Integer number = Integer.decode(decimal);        System.out.println("string [" + decimal + "] = " + number);    }}
Output:
 
Exception in thread "main" java.lang.NumberFormatException: For input string: "1A"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.valueOf(Integer.java:740)
    at java.lang.Integer.decode(Integer.java:1197)
    at GFG.main(File.java:16)


Java-Functions
Java-lang package
java-Long
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Python | Pokémon Training Game - GeeksforGeeks

26 Mar, 2020
Problem :You are a Pokémon trainer. Each Pokémon has its own power, described by a positive integer value. As you travel, you watch Pokémon and you catch each of them. After each catch, you have to display maximum and minimum powers of Pokémon caught so far. You must have linear time complexity. So sorting won’t help here. Try having minimum extra space complexity.Examples:Suppose you catch Pokémon of powers 3 8 9 7. Then the output should be3 33 83 93 9
Input : 
The single line describing powers of N Pokémon caught. 

Output : 
N lines stating minimum power so far and maximum power
so far separated by single space

Code : Python code to implement Pokemon training game
# python code to train pokemonpowers = [3, 8, 9, 7]   mini, maxi = 0, 0   for power in powers:    if mini == 0 and maxi == 0:        mini, maxi = powers[0], powers[0]        print(mini, maxi)    else:        mini = min(mini, power)        maxi = max(maxi, power)        print(mini, maxi)        # Time Complexity is O(N) with Space Complexity O(1)
Output :
3 3
3 8
3 9
3 9
Python
Technical Scripter
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
File.ReadLines(String, Encoding) Method in C# with Examples - GeeksforGeeks

01 Jun, 2020
File.ReadLines(String, Encoding) is an inbuilt File class method that is used to read the lines of a file that has a specified encoding.
Syntax:
public static System.Collections.Generic.IEnumerable ReadLines (string path, System.Text.Encoding encoding);
Parameter: This function accepts two parameters which are illustrated below:
path: This is the specified file for reading.
encoding: This encoding is applied to the contents of the file.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method.
ArgumentNullException: The path is null.
DirectoryNotFoundException: The path is invalid.
FileNotFoundException: The file specified by the path was not found.
IOException: An I/O error occurred while opening the file.
PathTooLongException: The path exceeds the system-defined maximum length.
SecurityException: The caller does not have the required permission.
UnauthorizedAccessException: The path specifies a file that is read-only. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission.
Return Value: Returns all the lines of the specified file.
Below are the programs to illustrate the File.ReadLines(String, Encoding) method.
Program 1: Initially, a file file.txt is created with some contents shown below-
// C# program to illustrate the usage// of File.ReadLines(String, Encoding) method  // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text;  public class GFG {    public static void Main(String[] argv)    {        // Calling the ReadLines(String, Encoding) function        foreach(string line in File.ReadLines(@"file.txt", Encoding.UTF8))        {            // Printing the file contents            Console.WriteLine(line);        }    }}
Output:
GFG
gfg
Geeks
GeeksforGeeks
geeksforgeeks

Program 2: Initially, a file file.txt is created with some contents shown below-
Below code filter some contents from the file and prints them back.
// C# program to illustrate the usage// of File.ReadLines(String, Encoding) method  // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text;  public class GFG {    public static void Main(String[] argv)    {        // Calling the ReadLines(String, Encoding) function        foreach(string line in File.ReadLines(@"file.txt", Encoding.UTF8))        {            // Filtering the file contents and printing            if (line.Contains("GFG")) {                Console.WriteLine(line);            }        }    }}
Output:
GFG

CSharp-File-Handling
C#
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
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Linked List Implementation in C#
Convert String to Character Array in C#
How to cbind vectors of different length without repetition of elements of the smaller vector in R?

We can join vectors by columns using cbind and it does not matter whether these vectors are of same length or not. If the vectors are of same length then all the values of both the vectors are printed but if the length of these vectors are different then the values of the smaller vector gets repeated. But we might not want to repeat the values/elements of the smaller vector and it is possible by setting the length of the smaller vector to the length of larger vector, this will create NA values in the smaller at places where the original vector does not have any values.
x1<-c(4,7,8,12)
x2<-1:20
n<-max(length(x1),length(x2))
length(x1)<-n
cbind(x1,x2)
 x1 x2
[1,] 4 1
[2,] 7 2
[3,] 8 3
[4,] 12 4
[5,] NA 5
[6,] NA 6
[7,] NA 7
[8,] NA 8
[9,] NA 9
[10,] NA 10
[11,] NA 11
[12,] NA 12
[13,] NA 13
[14,] NA 14
[15,] NA 15
[16,] NA 16
[17,] NA 17
[18,] NA 18
[19,] NA 19
[20,] NA 20
y1<-c("A","B","C","D","E")
y2<-LETTERS[1:20]
n<-max(length(y1),length(y2))
length(y1)<-n
cbind(y1,y2)
y1 y2
[1,] "A" "A"
[2,] "B" "B"
[3,] "C" "C"
[4,] "D" "D"
[5,] "E" "E"
[6,] NA "F"
[7,] NA "G"
[8,] NA "H"
[9,] NA "I"
[10,] NA "J"
[11,] NA "K"
[12,] NA "L"
[13,] NA "M"
[14,] NA "N"
[15,] NA "O"
[16,] NA "P"
[17,] NA "Q"
[18,] NA "R"
[19,] NA "S"
[20,] NA "T"
z1<-1:20
z2<-16:20
n<-max(length(z1),length(z2))
length(z2)<-n
cbind(z1,z2)
z1 z2
[1,] 1 16
[2,] 2 17
[3,] 3 18
[4,] 4 19
[5,] 5 20
[6,] 6 NA
[7,] 7 NA
[8,] 8 NA
[9,] 9 NA
[10,] 10 NA
[11,] 11 NA
[12,] 12 NA
[13,] 13 NA
[14,] 14 NA
[15,] 15 NA
[16,] 16 NA
[17,] 17 NA
[18,] 18 NA
[19,] 19 NA
[20,] 20 NA
How to create NSIndexPath for TableView in iOS?

Index path is generally a set of two values representing row and section of a table view. Index path can be created in objective C as well as Swift as both are native language of iOS Development.
IndexPathForRow is a class method in iOS. To create a index path we need to be sure about the section and row we need to create. Below are the methods of creating an Indexpath.
To create an IndexPath in objective C we can use.
NSIndexPath *myIP = [NSIndexPath indexPathForRow: Int inSection:Int] ;
Example
NSIndexPath *myIP = [NSIndexPath indexPathForRow: 5 inSection: 2] ;
To create an IndexPath in Swift we can use.
IndexPath(row: rowIndex, section: sectionIndex)
Example
IndexPath(row: 2, section: 4)
Both of these are generally used in Cell for row at method, which can be used as
let cell = tblView.cellForRow(at: IndexPath(row: 5, section: 2)
How to display text Right-to-Left Using HTML?

To display text Right-to-Light (rtl) in HTML, use the CSS property direction. Use it with the style attribute. The style attribute specifies an inline style for an element.
You can use the following property values to set direction with the CSS property direction −
Use the style attribute with the CSS property direction to display text Right-to-Left. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to display text right-to-left using HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Text Direction</title>
</head>

<body>
   <p style = "direction: rtl;">
      Displayed from right to left
   </p>
</body>
</html>
Set the width of an element to 50% in Bootstrap 4

To set the width of an element to 50%, use the .w-50 class in Bootstrap.
You can try to run the following code to set element’s width −
Live Demo 
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/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.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h3>Set element width</h3>
         <div class = "w-100 bg-danger">Normal width</div>
         <div class = "w-50 bg-success">Width is 50%</div>
      </div>
   </body>
</html>
How to find available WiFi networks using Python? - GeeksforGeeks

10 Mar, 2022
WiFi (Wireless Fidelity) is a wireless technology that allows devices such as computers (laptops and desktops), mobile devices (smartphones and wearables), and other equipment (printers and video cameras) to interface with the Internet. We can find out the names of the WiFi names with the help of Python. We need to have the basics of networking to help us know what we need and what we do not need.
subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. We do not need to use pip to install it as the subprocess module comes preinstalled.
With the subprocess module, we need to use the check_output() method. We will pass a list of the things we will need to know about the WiFi networks. We will need netsh, wlan, show and network. These parameters are passed for storing the outputs in them and then converting it to strings to display the outputs. 
Syntax: subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Parameters:
args: The arguments used to launch the process. This may be a list or a string.
stdin: Value of standard input stream to be passed as pipe(os.pipe()).
stdout: Value of output obtained from standard output stream.
stderr: also known as standard error, is the default file descriptor where a process can write error messages. Basically the value of the error(if any)
shell: It is a boolean parameter.If True the commands get executed through a new shell environment.
universal_newlines: It is a boolean parameter .If true files containing stdout and stderr are opened in universal newline mode.
Returns: Information about the networks
Now here is the code for it
Python3
# importing the subprocess moduleimport subprocess  # using the check_output() for having the network term retrievaldevices = subprocess.check_output(['netsh','wlan','show','network'])  # decode it to stringsdevices = devices.decode('ascii')devices= devices.replace("\r","")  # displaying the informationprint(devices)
Output:
adnanirshad158
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Total digits | Practice | GeeksforGeeks

Given a number n, count the total number of digits required to write all numbers from 1 to n.

Example 1:
Input: n = 13
Output: 17 
Explanation: There are total 17 
digits required to write all 
numbers from 1 to 13.

Example 2:
Input: n = 4
Output: 4
Explanation: There are total 4 
digits required to write all
numbers from 1 to 4.


Your Task:  
You dont need to read input or print anything. Complete the function totalDigits() which takes n as input parameter and returns the total number of digits required to write all numbers from 1 to n.

Expected Time Complexity: O(logn)
Expected Auxiliary Space: O(1)

Constraints:
1<= n <=100000
+1
shashwatsatna4 months ago
		long long int count=0;
        for(int i=1;i<=n;i++){
            count+=log10(i)+1;
        }
        return count;
+1
badgujarsachin837 months ago
class Solution {
  public:
    long long int totalDigits(long long int n){
        // code here
        long long int count=0;
        for(int i=1;i<=n;i++){
            string ans=to_string(i);
            count+=ans.length();
        }
        return count;
    }
};
0
badgujarsachin837 months ago
0
Pazhanivel K10 months ago
Pazhanivel K
Easy java olution
class Solution {    static long totalDigits(long n){        // code here         String s;        long count=0;        for(int i=1;i<=n;i++)        {        s=Integer.toString(i);        count=count+s.length();        }    return count;    }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Online XML Editor

Editable XML Code
123456789101112131415<?xml version="1.0"?><Company>  <Employee>      <FirstName>Tanmay</FirstName>      <LastName>Patil</LastName>      <ContactNo>1234567890</ContactNo>      <Email>tanmaypatil@xyz.com</Email>      <Address>           <City>Bangalore</City>           <State>Karnataka</State>           <Zip>560212</Zip>      </Address>  </Employee></Company>X
Privacy Policy
Cookies Policy
Terms of Use
How to find the correlation matrix by considering only numerical columns in an R data frame?

While we calculate correlation matrix for a data frame, all the columns must be numerical, if that is not the case then we get an error Error in cor(“data_frame_name”) : 'x' must be numeric. To solve this problem, either we can find the correlations among variables one by one or use apply function.
Consider the below data frame −
set.seed(99)
x1<-rnorm(20)
x2<-rpois(20,5)
x3<-rpois(20,2)
x4<-LETTERS[1:20]
x5<-runif(20,2,10)
x6<-sample(letters[1:3],20,replace=TRUE)
df<-data.frame(x1,x2,x3,x4,x5,x6)
df
   x1    x2    x3    x4 x5 x6
1 0.2139625022 7 4 A 6.423159 a
2 0.4796581346 5 1 B 7.176488 a
3 0.0878287050 7 2 C 2.372402 c
4 0.4438585075 8 3 D 6.599771 a
5 -0.3628379205 5 2 E 5.122577 c
6 0.1226740295 8 3 F 3.133224 c
7 -0.8638451881 4 2 G 2.482256 a
8 0.4896242667 4 4 H 4.532982 c
9 -0.3641169125 5 0 I 2.670717 c
10 -1.2942420067 2 3 J 8.597253 a
11 -0.7457690454 6 0 K 2.699053 a
12 0.9215503620 7 2 L 8.743498 b
13 0.7500543504 6 2 M 3.427915 c
14 -2.5085540159 10 2 N 5.928563 a
15 -3.0409340953 4 2 O 3.544168 a
16 0.0002658005 7 0 P 3.710395 c
17 -0.3940189942 2 2 Q 9.609634 c
18 -1.7450276608 5 0 R 5.886087 b
19 0.4986314508 8 2 S 5.507034 c
20 0.2709537888 4 3 T 2.137873 b
Finding the correlation matrix for columns in df −
cor(df)
Error in cor(df) : 'x' must be numeric
Here, the error means all the columns are not numeric.
str(df)
'data.frame': 20 obs. of 6 variables:
$ x1: num 0.214 0.4797 0.0878 0.4439 -0.3628 ...
$ x2: int 7 5 7 8 5 8 4 4 5 2 ...
$ x3: int 4 1 2 3 2 3 2 4 0 3 ...
$ x4: Factor w/ 20 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10 ...
$ x5: num 6.42 7.18 2.37 6.6 5.12 ...
$ x6: Factor w/ 3 levels "a","b","c": 1 1 3 1 3 3 1 3 3 1 ...
Now to find the correlation matrix for all the numeric columns, we can do the following −
cor(df[sapply(df,is.numeric)])
      x1    x2    x3    x5
x1 1.00000000 0.14685889 0.23107456 0.04232205
x2 0.14685889 1.00000000 -0.02664914 -0.14822679
x3 0.23107456 -0.02664914 1.00000000 0.18971761
x5 0.04232205 -0.14822679 0.18971761 1.00000000
How to get an attribute value from a href link in selenium?

We can get an attribute value from a href link in Selenium. To begin with, we have to first identify the element having an anchor tag with the help of any of the locators like css, id, class, and so on.
Next, we shall use the getAttribute method and pass href as a parameter to the method. Let us investigate an element with an anchor tag having the href attribute. Here, the value of href should contain /about/about_team.htm.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class HrefValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_team.htm");
      // identify element
      WebElement l = driver.findElement(By.linkText("Team"));
      // href value from getAttribute()
      String v = l.getAttribute("href");
      System.out.println("Href value of link: "+ v);
      driver.close();
   }
}
C# Program to Convert the Octal String to an Integer Number - GeeksforGeeks

22 Jun, 2020
Given an octal number as input, we need to write a program to convert the given octal number into equivalent integer. To convert an octal string to an integer, we have to use Convert.ToInt32() function to convert the values.
Examples:
Input : 202
Output : 130

Input : 660
Output : 432

Convert the item to an integer using base value 8 by using a foreach loop .
Program 1:
// C# program to convert an array // of octal strings to integersusing System;using System.Text;  class Prog {      static void Main(string[] args)    {        string[] str = { "121", "202", "003" };        int num1 = 0;        try {              // using foreach loop to access each items            // and converting to integer numbers            foreach(string item in str)            {                num1 = Convert.ToInt32(item, 8);                Console.WriteLine(num1);            }        }        catch (Exception ex) {            Console.WriteLine(ex.ToString());        }    }}
Output:
81
130
3

Program 2:
// C# program to convert an array // of octal strings to integersusing System;using System.Text;  namespace geeks {  class Prog {      static void Main(string[] args)    {        string[] str = { "111", "543", "333", "607", "700" };        int num2 = 0;        try {              // using foreach loop to access each items            // and converting to integer numbers            foreach(string item in str)            {                num2 = Convert.ToInt32(item, 8);                Console.WriteLine(num2);            }        }        catch (Exception ex) {            Console.WriteLine(ex.ToString());        }    }}}
Output:
73
355
219
391
448

C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
GATE | GATE-CS-2017 (Set 2) | Question 57 - GeeksforGeeks

29 Sep, 2021
The next state table of a 2 bit saturating up-counter is given below.
The counter is built as synchronous sequential circuit using T flip-flops. The value for T1 and T0 are(A) T1 = Q0Q1T0 = Q’0Q’1(B) T1 = Q’1Q0T0 = Q’1 + Q’0(C) T1 = Q1 + Q0T0 = Q’1 + Q’0(D) T1 = Q’1Q0T0 = Q1 + Q0Answer: (B)Explanation:  
Using above excitation table,
T1 = Q’1Q0 = 0100T0 = Q’1 + Q’0 = 1110
Therefore Option B
Another Solution
T1 and T2 are filled by using the property that output of T FF will change when T=1 and will not change when T=0Thus
T1(Q1,Q2) = Q1’ Q2
T2(Q1,Q2) = Q1’Q2’ + Q1’Q2 + Q1Q2’
	= Q1’ + Q1Q2’
	= Q1’ + Q2’

This solution is contributed by Abhishek Kumar.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersSequential Circuits : GATE PYQs on Counters with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:38 / 30:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GpghiunxSIk" 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-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1997 | Question 25
Python program to calculate square of a given number - GeeksforGeeks

12 Oct, 2021

Given a number, the task is to write a Python program to calculate square of the given number.
Examples:
Input: 4
Output: 16

Input: 3
Output: 9

Input: 10
Output: 100
We will provide the number, and we will get the square of that number as output. We have three ways to do so:
Multiplying the number to get the square (N * N)
Using Exponent Operator
Using math.pow() Method
Method 1: Multiplication
In this approach, we will multiply the number with one another to get the square of the number.
Example:
Python3
 

 
 










# Declaring the number.
n = 4
 
# Finding square by multiplying them
# with each other
square = n * n
 
# Printing square
print(square)






Output:
16
Method 2: Using Exponent Operator
In this approach, we use the exponent operator to find the square of the number.
Exponent Operator: **
Return: a ** b will return a raised to power b as output.
Example:
Python3
 

 
 










# Declaring the number.
n = 4
 
# Finding square by using exponent operator
# This will yield n power 2 i.e. square of n
square = n ** 2
 
# Printing square
print(square)






Output:
16
Method 3: Using pow() Method
In this approach, we will use the pow() method to find the square of the number. This function computes x**y and returns a float value as output.
Syntax: float pow(x,y)
Parameters :
x : Number whose power has to be calculated.
y : Value raised to compute power. 
Return Value : Returns the value x**y in float.
Example:
Python3
 

 
 










# Declaring the number.
n = 4
 
# Finding square by using pow method
# This will yield n power 2 i.e. square of n
square = pow(n, 2)
 
# Printing square
print(square)






Output:
16.0
snehashishghosh21

Picked


Technical Scripter 2020


Python


Python Programs


Technical Scripter

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
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 check whether a number is Prime or not
Find maximum element of ArrayList with Java Collections

In order to compute maximum element of ArrayList with Java Collections, we use the Collections.max() method. The java.util.Collections.max() returns the maximum element of the given collection. All elements must be mutually comparable and implement the comparable interface. They shouldn’t throw a ClassCastException.
Declaration −The Collections.max() method is declared as follows −
public static <T extends Object & Comparable> T max(Collection c)
where c is the collection object whose maximum is to be found.
Let us see a program to find the maximum element of ArrayList with Java collections −
 Live Demo
import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<Integer> list = new ArrayList<Integer>();
      try {
         list.add(14);
         list.add(2);
         list.add(73);
         System.out.println("Maximum element : " + Collections.max(list));
      }
      catch (ClassCastException | NoSuchElementException e) {
         System.out.println("Exception caught : " + e);
      }
   }
}
Maximum element : 73
JavaScript String - sup() Method

This method causes a string to be displayed as a superscript, as if it were in a <sup> tag.
Its syntax is as follows −
string.sup( )

Returns the string with <sup> tag.
Try the following example.
<html>
   <head>
      <title>JavaScript String sup() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String("Hello world");
         alert(str.sup());
      </script>      
   </body>
</html>
<sup>Hello world</sup>


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
TypeScript - String substring()

This method returns a subset of a String object.
string.substring(indexA, [indexB])

indexA − An integer between 0 and one less than the length of the string.
indexA − An integer between 0 and one less than the length of the string.
indexB − (optional) An integer between 0 and the length of the string.
indexB − (optional) An integer between 0 and the length of the string.
The substring method returns the new sub-string based on given parameters.
var str = "Apples are round, and apples are juicy."; 
console.log("(1,2): "    + str.substring(1,2)); 
console.log("(0,10): "   + str.substring(0, 10)); 
console.log("(5): "      + str.substring(5));

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
(1,2): p 
(0,10): Apples are 
(5): s are round, and apples are juicy.


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
R - For Loop

A For loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The basic syntax for creating a for loop statement in R is −
for (value in vector) {
   statements
}

R’s for loops are particularly flexible in that they are not limited to integers, or even numbers in the input. We can pass character vectors, logical vectors, lists or expressions.
v <- LETTERS[1:4]
for ( i in v) {
   print(i)
}
When the above code is compiled and executed, it produces the following result −
[1] "A"
[1] "B"
[1] "C"
[1] "D"


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
Get names of all keys in the MongoDB collection?

The syntax to get names of all keys in the collection is as follows:
var yourVariableName1=db.yourCollectionName.findOne();

for(var yourVariableName 2 in yourVariableName1) { print(yourVariableName); }
To understand the above syntax, let us create a collection with documents. The collection name
we are creating is “studentGetKeysDemo”.
The following is the query to create documents:
>db.studentGetKeysDemo.insert({"StudentId":1,"StudentName":"Larry","StudentAge":23,"StudentAddress":"US",
... "StudentHobby":["Cricket","Football","ReadingNovel"],
   "StudentMathMarks":89,"StudentDOB":ISODate('1998-04-06')});
The following is the output:
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method. The query is as follows:
> db.studentGetKeysDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6c12dd68174aae23f5ef5f"),
   "StudentId" : 1,
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentAddress" : "US",
   "StudentHobby" : [
      "Cricket",
      "Football",
      "Reading Novel"
   ],
   "StudentMathMarks" : 89,
   "StudentDOB" : ISODate("1998-04-06T00:00:00Z")
}
Here is the query to get names of all keys from the collection “studentGetKeysDemo”:
> var allKeys=db.studentGetKeysDemo.findOne();
> for(var myKey in allKeys){print(myKey);}
The following is the output displaying all the keys:
_id
StudentId
StudentName
StudentAge
StudentAddress
StudentHobby
StudentMathMarks
StudentDOB