code-rag-bench/online-tutorials huggingface dataset:
Python - Convert Integer Matrix to String Matrix - GeeksforGeeks

30 Dec, 2020
Given a Matrix with integer values, convert each element to String.
Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]]Output : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’], [’19’, ‘4’, ‘6’]]Explanation : All elements of Matrix converted to Strings.
Input : test_list = [[4, 5, 7], [10, 8, 3]]Output : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’]]Explanation : All elements of Matrix converted to Strings.
Method #1 : Using str() + list comprehension
The combination of above methods can be used to solve this problem. In this, we perform conversion using str() and list comprehension is used to iterate for all the elements.
Python3
# Python3 code to demonstrate working of # Convert Integer Matrix to String Matrix# Using str() + list comprehension  # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]  # printing original listprint("The original list : " + str(test_list))  # using str() to convert each element to string res = [[str(ele) for ele in sub] for sub in test_list]  # printing result print("The data type converted Matrix : " + str(res))
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]

Method #2 : Using str() + map()
The combination of above functions can also be used to solve this problem. In this, we use map() to extend the string conversion to all row elements.
Python3
# Python3 code to demonstrate working of # Convert Integer Matrix to String Matrix# Using str() + map()  # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]  # printing original listprint("The original list : " + str(test_list))  # using map() to extend all elements as string  res = [list(map(str, sub)) for sub in test_list]  # printing result print("The data type converted Matrix : " + str(res))
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]

Python list-programs
Python matrix-program
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Convert set into a list
Python | Get dictionary keys as a list
Ways to filter Pandas DataFrame by column values
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
miscellaneous topics in C++ - GeeksQuiz

29 Jul, 2020
// Objects of test can only be created using new
class Test
{
private:
    ~Test() {}
friend void destructTest(Test* );
};
 
// Only this function can destruct objects of Test
void destructTest(Test* ptr)
{
    delete ptr;
}
 
int main()
{
    // create an object
    Test *ptr = new Test;
 
    // destruct the object
    destructTest (ptr);
 
    return 0;
}

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Read Text File Into List in Python?
Python Data Structures and Algorithms
How to Change Axis Scales in R Plots?
Rexx - pos String

This method returns the position of one string within another.
pos(substr,string1)

string1 − The source string.
string1 − The source string.
substr − the sub string to search for in the main string.
substr − the sub string to search for in the main string.
This method returns the position of one string within another.
/* Main program */ 
a = "Hello World" 
say pos("Hello",a)  
When we run the above program, we will get the following result.
1 

 Print
 Add Notes
 Bookmark this page
Plotly - Legends

By default, Plotly chart with multiple traces shows legends automatically. If it has only one trace, it is not displayed automatically. To display, set showlegend parameter of Layout object to True.
layout = go.Layoyt(showlegend = True)

Default labels of legends are trace object names. To set legend label explicitly set name property of trace.
In following example, two scatter traces with name property are plotted.
import numpy as np
import math #needed for definition of pi

xpoints = np.arange(0, math.pi*2, 0.05)
y1 = np.sin(xpoints)
y2 = np.cos(xpoints)
trace0 = go.Scatter(
   x = xpoints,
   y = y1,
   name='Sine'
)
trace1 = go.Scatter(
   x = xpoints,
   y = y2,
   name = 'cos'
)
data = [trace0, trace1]
layout = go.Layout(title = "Sine and cos", xaxis = {'title':'angle'}, yaxis = {'title':'value'})
fig = go.Figure(data = data, layout = layout)
iplot(fig)
The plot appears as below −

    12 Lectures 
     53 mins

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Date Class in Java

Java provides the Date class available in java. util package, this class encapsulates the current date and time.
The Date class supports two constructors as shown in the following table.
Following are the methods of the date class.
This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows −
Live Demo
import java.util.Date;
public class DateDemo {

   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display time and date using toString()
      System.out.println(date.toString());
   }
}
This will produce the following result −
on May 04 09:51:52 CDT 2009
Following are the three ways to compare two dates −
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
How to use variable number of arguments to function in JavaScript?

To use a variable number of arguments to function, use the arguments object.
You can try to run the following code to implement arguments to a function in JavaScript
Live Demo
<html>
   <body>
      <script>
         function functionArgument(val1, val2, val3)  {
            var res = "";
            res += "Expected Arguments: " + functionArgument.length;
            res += "<br />";
            res += "Current Arguments : " + arguments.length;

            res += "<br />";
            res += "Each argument = "

            for (p = 0; p < arguments.length; p++) {
               res += "<br />";
               res += functionArgument.arguments[p];
               res += " ";
            }
            document.write(res);
         }
         functionArgument(20, 50, 80, "Demo Text!","Hello World", new Date())
      </script>
   </body>
</html>
C Program to Rotate bits of a number - GeeksforGeeks

11 Dec, 2021
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put back at left end. 
Example: Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000...11100101) becomes 00..0011100101000. Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000...11100101) by 3 becomes 101000..0011100.  
C
#include<stdio.h>#define INT_BITS 32  /*Function to left rotate n by d bits*/int leftRotate(int n, unsigned int d){   /* In n<<d, last d bits are 0. To put first 3 bits of n at      last, do bitwise or of n<<d with n >>(INT_BITS - d) */   return (n << d)|(n >> (INT_BITS - d));}  /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){   /* In n>>d, first d bits are 0. To put last 3 bits of at      first, do bitwise or of n>>d with n <<(INT_BITS - d) */   return (n >> d)|(n << (INT_BITS - d));}  /* Driver program to test above functions */int main(){  int n = 16;  int d = 2;  printf("Left Rotation of %d by %d is ", n, d);  printf("%d", leftRotate(n, d));  printf("Right Rotation of %d by %d is ", n, d);  printf("%d", rightRotate(n, d));  getchar();} 
Output : 
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
Please refer complete article on Rotate bits of a number for more details!
rotation
Bit Magic
C Programs
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Hamming code Implementation in C/C++
Write an Efficient Method to Check if a Number is Multiple of 3
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to calculate Execution Time of a Code Snippet in C++?

We can calculate the execution time of a code snippet by using following syntax −
auto start = high_resolution_clock::now(); // Start time
// Code snippet
auto stop = high_resolution_clock::now(); // Stop time
auto duration = duration_cast<microseconds>(stop - start); // Duration
The class high_resolution_clock is defined in “chrono” header file. The function now() is returning a value corresponding to the call’s point in time.
A header file is used to record the time taken by that particular code.
#include <chrono>
using namespace std::chrono;
The following is an example to calculate execution time of a code snippet.
 Live Demo
#include <iostream>
#include <chrono>
using namespace std::chrono;
using namespace std;
int sum(int x, int y) {
   int s = x + y;
   cout << "The sum of numbers : " << s;
}
int main() {
   auto start = high_resolution_clock::now();
   sum(28, 8);
   auto stop = high_resolution_clock::now();
   auto duration = duration_cast<microseconds>(stop - start);
   cout << "\nTime taken by function : "<< duration.count() << " microseconds";
   return 0;
}
The sum of numbers : 36
Time taken by function : 42 microseconds
In the above program, a function sum() is defined to calculate the sum of numbers.
int sum(int x, int y) {
   int s = x + y;
   cout << "The sum of numbers : " << s;
}
In the main() function, we recorded the time taken by the function sum() by using some predefined functions and class “chrono”.
auto start = high_resolution_clock::now();
sum(28, 8);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
Cypress - Working with XHR

XHR is XML HTTP Request. It is an Application Programming Interface (API) which is available as an object, whose methods send data between a web browser and server. An object in XHR can request data from a server in the form of a response.
Cypress can not only be used for front end automation, but also can control the network traffic by directly accessing the XHR objects. Then, it applies the assertions on the objects.It can mock or stub a response. An XHR details can be seen in the Network tab in the browser.
XHR response Header is as follows −
The response is as follows −
To make an XHR request, the cy.request() command is used. The method cy.intercept() is used to redirect the responses to the matching requests.
Given below is the command to explain the implementation of XHR request in Cypress −
cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
//aliasing request
cy.get('@c').should((response) => {
   expect(response.body).to.have.length(100)
   expect(response).to.have.property('headers')
})

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
TypeScript - Number toFixed()

This method formats a number with a specific number of digits to the right of the decimal.
number.toFixed( [digits] )

digits − The number of digits to appear after the decimal point.
A string representation of number that does not use exponential notation and has the exact number of digits after the decimal place.
var num3 = 177.234 
console.log("num3.toFixed() is "+num3.toFixed()) 
console.log("num3.toFixed(2) is "+num3.toFixed(2)) 
console.log("num3.toFixed(6) is "+num3.toFixed(6))

On compiling, it will generate the same code in JavaScript.
The code will produce the following output −
num3.toFixed() is 177 
num3.toFixed(2) is 177.23 
num3.toFixed(6) is 177.234000


    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
How to extract an HTML tag from a String using regex in Java?

The java.util.regex package of java provides various classes to find particular patterns in character sequences.
The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −
compile() − This method accepts a String representing a regular expression and returns an object of the class Pattern.
compile() − This method accepts a String representing a regular expression and returns an object of the class Pattern.
matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
The Matcher class of java.util.regex package is an engine that performs match operations. To find the matched value this you need to use two methods of this class namely −
find() − This method returns true if the match operation represented by the current object is successful else, it returns false.
find() − This method returns true if the match operation represented by the current object is successful else, it returns false.
group() − This method accepts an integer value representing a particular group and returns the sequence captured by the specified group in the match operation.
group() − This method accepts an integer value representing a particular group and returns the sequence captured by the specified group in the match operation.
Therefore, to find an HTML tag from a String −
Create a Pattern object by passing the regular expression representing the required HTML tag to it as a parameter to the compile() method of the Pattern class.
Create a Pattern object by passing the regular expression representing the required HTML tag to it as a parameter to the compile() method of the Pattern class.
Match it with the desired String using the matcher method() of the Pattern class.
Match it with the desired String using the matcher method() of the Pattern class.
Verify if a occurred using the find() method of the Matcher class.
Verify if a occurred using the find() method of the Matcher class.
In the case of a match, retrieve the matched String using the group() method of the Matcher class.
In the case of a match, retrieve the matched String using the group() method of the Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractHtmlTag {
   public static void main(String[] args) {
      String str = "Welcome to <b>Tutorialspoint<b>";
      //Creating a pattern object
      Pattern pattern = Pattern.compile("<b>(\\S+)</b>");
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      if (matcher.find()) {
         String result = matcher.group(1);
         System.out.println(result);
      }
   }
}
Tutorialspoint
Python - Split Strings on Prefix Occurrence - GeeksforGeeks

30 Sep, 2021
Given a list of Strings, perform string split on the occurrence of prefix.
Input : test_list = [“geeksforgeeks”, “best”, “geeks”, “and”], pref = “geek” Output : [[‘geeksforgeeks’, ‘best’], [‘geeks’, ‘and’]] Explanation : At occurrence of string “geeks” split is performed.
Input : test_list = [“good”, “fruits”, “goodness”, “spreading”], pref = “good” Output : [[‘good’, ‘fruits’], [‘goodness’, ‘spreading’]] Explanation : At occurrence of string “good” split is performed.  
Method #1 : Using loop + startswith()
In this, we iterate each element of List, and check if new list has to be changed using startswith() by checking for prefix, and create new list if prefix is encountered.
Python3
# Python3 code to demonstrate working of# Split Strings on Prefix Occurrence# Using loop + startswith() # initializing listtest_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"] # printing original listprint("The original list is : " + str(test_list)) # initializing prefixpref = "geek"  res = []for val in test_list:         # checking for prefix    if val.startswith(pref):                 # if pref found, start new list        res.append([val])    else:                 # else append in current list        res[-1].append(val) # printing resultprint("Prefix Split List : " + str(res))
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Method #2 : Using loop + zip_longest() + startswith()
In this, we zip all the elements with their subsequent element sublist and check for prefix using startswith(), if found, result is appended. 
Python3
# Python3 code to demonstrate working of# Split Strings on Prefix Occurrence# Using loop + zip_longest() + startswith()from itertools import zip_longest # initializing listtest_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"] # printing original listprint("The original list is : " + str(test_list)) # initializing prefixpref = "geek"  res, temp = [], [] for x, y in zip_longest(test_list, test_list[1:]):    temp.append(x)         # if prefix is found, split and start new list    if y and y.startswith(pref):        res.append(temp)        temp = []res.append(temp) # printing resultprint("Prefix Split List : " + str(res))
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
surindertarika1234
kashishsoda
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
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
How to close a browser session in Selenium with python?

We can close a browser session in Selenium by the following ways −
Using the close() method.
Using the close() method.
Using the quit() method.
Using the quit() method.
Both these methods close the browser, but close() the browser in focus and quit() ends the driver session.
Code Implementation with close().
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to close the browser
driver.close()
Code Implementation with quit().
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to end the driver session
driver.quit()
Finding Armstrong numbers in a given range in JavaScript

A number is called Armstrong number if the following equation holds true for that number:
xy...z =xx +yy+...+zz, where n denotes the number of digits in the number.
153 is an Armstrong number because −
11 +55 +33 = 1 + 125 + 27 =153
We are required to write a JavaScript function that takes in two numbers, a range, and returns
all the numbers between them that are Armstrong numbers (including them, if they are Armstrong)
The code for this will be −
const isArmstrong = number => {
   let num = number;
   const len = String(num).split("").length;
   let res = 0;
   while(num){
      const last = num % 10;
      res += Math.pow(last, len);
      num = Math.floor(num / 10);
   };
   return res === number;
};
const armstrongBetween = (lower, upper) => {
   const res = [];
   for(let i = lower; i <= upper; i++){
      if(isArmstrong(i)){
         res.push(i);
      };
   };
   return res;
};
console.log(armstrongBetween(1, 400));
The output in the console −
[
   1, 2, 3, 4, 5,
   6, 7, 8, 9, 153,
   370, 371
]
Java - abs() Method

The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte.
Following are all the variants of this method −
double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)

Here is the detail of parameters −
Any primitive data type.
This method Returns the absolute value of the argument.
public class Test { 

   public static void main(String args[]) {
      Integer a = -8;
      double d = -100;
      float f = -90;

      System.out.println(Math.abs(a));
      System.out.println(Math.abs(d));     
      System.out.println(Math.abs(f));    
   }
}
This will produce the following result −
8
100.0
90.0


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Scala Map mkString() method with example

26 Jul, 2019
The mkString() method is utilized to represent the elements of the map as a string.
Method Definition: def mkString: String
Return Type: It returns the elements of the map as a string.
Example #1:
// Scala program of mkString()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 6)                  // Applying mkString method         val result = m1.mkString                  // Displays output        println(result)    }}
geeks -> 5for -> 3cs -> 6

Example #2:
// Scala program of mkString()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map("geeks" -> 5, "for" -> 3, "for" -> 3)                  // Applying mkString method         val result = m1.mkString                  // Displays output        println(result)    }}
geeks -> 5for -> 3

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala Constructors
Scala | Arrays
Inheritance in Scala
Enumeration in Scala
How to get the first element of List in Scala
Lambda Expression in Scala
PHP | DirectoryIterator isDot() Function

26 Nov, 2019
The DirectoryIterator::isDot() function is an inbuilt function in PHP which is used to check the current DirectoryIterator item is ‘.’ or ‘..’
Syntax:
bool DirectoryIterator::isDot( void )
Parameters: This function does not accept any parameters.
Return Value: This function returns TRUE if the entry is . or .., otherwise FALSE.
Below programs illustrate the DirectoryIterator::isDot() function in PHP:
Program 1:
<?php  // Create a directory Iterator$directory = new DirectoryIterator(dirname(__FILE__));  // Loop runs for each element of directoryforeach($directory as $dir) {          // Check if not a dot directory    if (!$dir->isDot()) {          // Display directory element and its permission        $perms = substr(sprintf('%o', $dir->getPerms()), -4);        echo $dir->getFilename() . " "         . " | Permission: " . $perms . "<br>";    }}  ?>
Output:
applications.html | Permission: 0666
bitnami.css | Permission: 0666
dashboard | Permission: 0777
favicon.ico | Permission: 0666
geeks.PNG | Permission: 0666
gfg.php | Permission: 0666
img | Permission: 0777
index.php | Permission: 0666
Sublime Text Build 3211 x64 Setup.exe | Permission: 0777
webalizer | Permission: 0777
xampp | Permission: 0777
Program 2:
<?php  // Create a directory Iterator$directory = new DirectoryIterator(dirname(__FILE__));  // Loop runs while directory is validwhile ($directory->valid()) {      // Check if not a dot directory    if (!$directory->isDot()) {        echo $directory->getFilename() . "<br>";    }    $directory->next();}  ?>
Output:
applications.html
bitnami.css
dashboard
favicon.ico
geeks.PNG
gfg.php
img
index.php
Sublime Text Build 3211 x64 Setup.exe
webalizer
xampp
Note: The output of this function depends on the content of server folder.
Reference: https://www.php.net/manual/en/directoryiterator.isdot.php
PHP-function
PHP-Iterators
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python – Convert Float String List to Float Values

03 Jul, 2020
Sometimes, while working with Python Data, we can have a problem in which we need to perform conversion of Float Strings to float values. This kind of problem is quite common in all domains and find application quite often. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [‘8.6’, ‘4.6’]Output : [8.6, 4.6]
Input : test_list = [‘4.5’]Output : [4.5]
Method #1 : Using list comprehension + float()The combination of above functions can be used to solve this problem. In this, we perform task of conversion using float() and list comprehension is used to perform iteration.
# Python3 code to demonstrate working of # Convert Float String List to Float Values# Using float() + list comprehension  # initializing listtest_list = ['87.6', '454.6', '9.34', '23', '12.3']  # printing original list print("The original list : " + str(test_list))  # Convert Float String List to Float Values# Using float() + list comprehensionres = [float(ele) for ele in test_list]  # printing result print("List after conversion : " + str(res))
The original list : ['87.6', '454.6', '9.34', '23', '12.3']
List after conversion : [87.6, 454.6, 9.34, 23.0, 12.3]

 
Method #2 : Using map() + float()The combination of above functions can also be used to solve this problem. In this, we perform the task of conversion using float and extension of conversion logic using map().
# Python3 code to demonstrate working of # Convert Float String List to Float Values# Using map() + float()  # initializing listtest_list = ['87.6', '454.6', '9.34', '23', '12.3']  # printing original list print("The original list : " + str(test_list))  # Convert Float String List to Float Values# Using map() + float()res = list(map(float, test_list))  # printing result print("List after conversion : " + str(res))
The original list : ['87.6', '454.6', '9.34', '23', '12.3']
List after conversion : [87.6, 454.6, 9.34, 23.0, 12.3]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Mapping key values to Dictionary

22 Apr, 2020
Sometimes, while working with Python records, we can have a problem in which we need to extract key’s value as the dictionary values required. This can have application in domains in which we require to reduce the data storage and in web development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehensionThis is one of the way in which we can solve this problem. In this, we iterate the list keys and construct dictionary of required key-value pairs using dictionary comprehension.
# Python3 code to demonstrate working of # Mapping key values to Dictionary# Using dictionary comprehension  # initializing listtest_list = [{'name' : 'Manjeet', 'age' : 23},              {'name' : 'Akshat',  'age' : 22},             {'name' : 'Nikhil', 'age' : 21}]  # printing original listprint("The original list is : " + str(test_list))  # Mapping key values to Dictionary# Using dictionary comprehensionres = {sub['name'] : sub['age'] for sub in test_list}  # printing result print("The flattened dictionary is : " + str(dict(res))) 
The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}
 
Method #2 : Using dict() + values()The combination of above functions can also be used to solve this problem. In this, we perform conversion to dictionary using dict() and extract dictionary values using values().
# Python3 code to demonstrate working of # Mapping key values to Dictionary# Using dict() + values()  # initializing listtest_list = [{'name' : 'Manjeet', 'age' : 23},              {'name' : 'Akshat',  'age' : 22},             {'name' : 'Nikhil', 'age' : 21}]  # printing original listprint("The original list is : " + str(test_list))  # Mapping key values to Dictionary# Using dict() + values()res = dict(sub.values() for sub in test_list)  # printing result print("The flattened dictionary is : " + str(dict(res))) 
The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}
Python list-programs
Python
Python Programs
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()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
SQL Full Form

12 Jun, 2020
SQL is a declarative language laying its basics on relation algebra. It is a standardized language supported by all major commercial databases. The query optimizer is an important component of SQL which takes an input the SQL query and executes, it in the fastest way possible.
These are main classification of SQL queries:
Data Manipulation Language (DML) –It deals with the queries related to insertion, deletion and modification of rows.Data Definition Language (DDL) –It deals with the creation, deletion and modification of definitions for tables and views.
Data Manipulation Language (DML) –It deals with the queries related to insertion, deletion and modification of rows.
Data Definition Language (DDL) –It deals with the creation, deletion and modification of definitions for tables and views.
A basic SQL query has the following syntax:
SELECT (attribute list)
FROM   (table list)
[WHERE (condition)]
[GROUP BY (grouping attributes)]
[HAVING (group condition)]
[ORDER BY (attribute list)] 
where the SELECT and FROM clauses are mandatory.
The SELECT clause lists the attributes to be retrieved.The FROM Clause specifies all tablesThe WHERE clause specifies the conditions for selection of records from these tables, including join conditions.GROUP BY specifies grouping attributesHAVING specifies a condition for retrieval of groups.
The SELECT clause lists the attributes to be retrieved.
The FROM Clause specifies all tables
The WHERE clause specifies the conditions for selection of records from these tables, including join conditions.
GROUP BY specifies grouping attributes
HAVING specifies a condition for retrieval of groups.
Various aggregator functions COUNT, SUM, MIN, MAX, and AVG can be in conjunction with grouping. ORDER BY specifies an order for displaying the result of a query.
Characteristics :
Tables, also called as relations are represented by a name, not exceeding 20 characters in length.
The table names as well as the column fields should have unique names.
While table definition, the field list is separated using commas, and each field name consists of a data type followed by length attribute enclosed in brackets.
SQL statements must end with a semicolon.
Advantages :
High performance.
Easily compatible with most of the databases like MS Access, MS SQL server.
Good flexibility in terms of creation of new Data Base tables and deletion of redundant tables.
Can handle large records and multiple transactions.
Easily accessible in the form of an open-source programming language.
High Security: Tables, procedures and views can easily be protected using permissions
Easy to learn and understand data
Disadvantages :
Complex interface to understand and deal with it.
Higher cost required to set up.
It is a platform dependent and compound based language.
Extra space is required for each record storage.
Partial control given to databases, due to hidden permissions.
Picked
DBMS
Full Form
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
make - Unix, Linux Command

make - utility for building and maintaining groups of programs.
make [ -f makefile ] [ options ] ... [ targets ] ... 

make [ -f makefile ] [ options ] ... [ targets ] ... 
make The purpose of the make utility is to determine automatically which pieces of a large program need to be recompiled, and issue the commands to recompile them.
you can use make with any programming language whose compiler can be run with a shell command. In fact, make is not limited to programs. You can use it to describe any task 
where some files must be updated automatically from others whenever the others change.
To prepare to use make, you must write a file called the makefile that describes the relationships among files in your program, and the states the commands for updating 
each file. In a program, typically the executable file is updated from object files, which are in turn made by compiling source files.
Example-1:
To Build your programs:
$ make
output:
 gcc -c -Wall test1.c
 gcc -c -Wall test2.c
 gcc -Wall test1.o test2.o -o test 

Note: make reads makefile present in current directory and executes based on statements in makefile

Example-2:
To clean all the object files:
$ make clean
output:
 rm -rf *.o test

Example-3:
 To forcibly build all programs, use -B option:
$ make -B
output:
 gcc -c -Wall test.c
 gcc -c -Wall anotherTest.c
 gcc -Wall test.o anotherTest.o -o test

Example-4:
To run make in debug mode, use the -d option :
$ make -d
output:
Copyright (C) 2006 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.This program built for x86_64-pc-linux-gnuReading makefiles...Reading makefile `Makefile'...Updating makefiles....Considering target file `Makefile'.Looking for an implicit rule for `Makefile'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.o'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.c'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.cc'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.C'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.cpp'.Trying pattern rule with stem `Makefile'.--More--
Example-5:
To build programs present in different directory:
$ make -C /home/testdir/
output:
make: Entering directory `/home/himanshu/practice/make-dir'make: Nothing to be done for `all'.make: Leaving directory `/home/himanshu/practice/make-dir'
Example-6:
To use other file instead of default makefile, use -f option :
$ make -f my_makefile
output:
gcc -c -Wall test1.c
gcc -c -Wall test2.c
gcc -Wall test1.o test2.o -o test
How to Convert Character to Factor in R?

19 Dec, 2021
The as.factor() method in R Programming Language is used to convert the character vector to factor class.
Syntax:
as.factor(char-vec)
where char-vec is the character vector
The class indicative of the data type of the vector can be obtained using the class() method. Upon conversion, the data type is returned as a factor. 
class(fac-vec)
where char-vec is the character vector
Example:
R
# declaring a character vectorstr_vec < - c("Geeks", "For", "Geeks", "Programming", "Coding")print("Original String")print(str_vec)  # getting the class of vectorclass(str_vec)  str_mod < - as.factor(str_vec)print("Modified String")print(str_mod)  # getting the class of vectorclass(str_mod)
Output
[1] "Original String"
[1] "Geeks"       "For"         "Geeks"       "Programming" "Coding"    
[1] "character"
[1] "Modified String"
[1] Geeks       For         Geeks       Programming Coding    
Levels: Coding For Geeks Programming
[1] "factor"
Similarly, a dataframe column can be converted to factor type, by referring to the particular data column using df$col-name command in R. 
Example:
R
# declaring a character vectordata_frame < - data.frame(col1=c(1: 5),                          col2=c("Geeks", "For", "Geeks",                                 "Programming", "Coding")                          )print("Original Class")  # getting the class of vectorclass(data_frame$col2)  # modifying the col2 of data framedata_frame$col2 < - as.factor(data_frame$col2)  print("Modified Class")class(data_frame$col2)
Output
[1] "Original Class" 
[1] "character" 
[1] "Modified Class" 
[1] "factor"
Picked
R Factor-Programs
R-Factors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
Program to count number of elements present in a set of elements with recursive indexing in Python

Suppose we have a list of numbers called A and another number k, we have to make a new set
of possible elements {A[k], A[A[k]], A[A[A[k]]], ... } stopping before it's out of index. We have to
find the size of this set, otherwise -1 when there is a cycle.
So, if the input is like A = [1,2,3,4,5,6,7], k = 1, then the output will be 6 as A[1] = 2, A[2] = 3,
A[3] = 4, A[4] = 5, A[5] = 6, A[6] = 7, So the set is {2,3,4,5,6,7}, size of set is 6.
To solve this, we will follow these steps −
seen := a new set
while k < size of A, doif A[k] in seen, thenreturn -1insert A[k] into seenk := A[k]
if A[k] in seen, thenreturn -1
return -1
insert A[k] into seen
k := A[k]
return size of seen
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, A, k):
      seen = set()
      while k < len(A):
         if A[k] in seen:
            return -1
         seen.add(A[k])
         k = A[k]
      return len(seen)
ob = Solution()
print(ob.solve([1,2,3,4,5,6,7], 1))
[1,2,3,4,5,6,7], 1
6
Redis - List Blpop Command

Redis BLPOP command is used to remove and get the first element in a list, or block until one is available. BLPOP command just returns the first element, if available, or blocks the client for specific time to execute any command.
String reply, the value of element stored at the key or nil.
Following is the basic syntax of Redis BLPOP command.
redis 127.0.0.1:6379> BLPOP LIST1 LIST2 .. LISTN TIMEOUT

redis 127.0.0.1:6379> BLPOP list1 100 

The above example will block the client for 100 seconds to execute any command. If any data comes in the specified key list1, then it returns; otherwise after 100 seconds nil value is returned.
How to become a 4 star coder on codechef in only 3 contests ?

03 May, 2020
Many people messaged me how you achieved 4 stars in only 3 contests in a month interval.That sounds amazing! But the reality is I am doing coding since 8 months and I have practiced on many platforms before jumping to the contests.I personally don’t know anyone who just started coding and became a 4 star or so in a very short period. People usually practice a lot before coming in the competitive scenario.
There is no such shortcut or trick ( PS- if you know such trick than please share XD ) .You have to grind hard for improvement and don’t get depressed by seeing others results, they don’t show the complete truth.Many people will suggest you to do participate in contests, I also agree that its a good practice but I will recommend you to first practice before directly jumping in to contests .
As this is my first post and I don’t want it to be to long (it is already too long XD), so that’s it for this time. Comment down if you want me to write on other such stuff and feel free to message me if you have doubts regarding such things.
Career-Advices
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is a target type of lambda expression in Java?

A functional Interface for which a lambda expression has invoked is called target type of lambda expression. It means that if a lambda expression has invoked for some "X" interface then "X" is the target type of that lambda expression. Hence, we conclude that lambda expressions can be used only in those situations where java compiler can determine the Target Type.
In the below example, the target type of lambda expression is BiFunction. An instance of a class is automatically created that implements the functional interface and lambda expression provides an implementation of the abstract method declared by the functional interface.
interface BiFunction {
   R apply(K k , V v);
}
public class LambdaTypeInferenceTest {
   public static void main(String[] args) {
      BiFunction result = (n1, n2) ->
      { return n1 + n2;}; // lambda expression
         Integer n1 = 10;
         Integer n2 = 20;
         System.out.println("The addition of n1 and n2 is: "+ result.apply(n1, n2));
   }
}
The addition of n1 and n2 is: 30
C/C++ Program for the n-th Fibonacci number?

The Fibonacci sequence is a series where the next term is the sum of the previous two terms.The first two terms of the Fibonacci sequence is 0 followed by 1. 
In this problem, we will find the nth number in the Fibonacci series. For this we will calculate all the numbers and print the n terms.
Input:8
Output:0 1 1 2 3 5 8 13
0+1=1
1+1=2
1+2=3
2+3=5
Using For loop to sum of previous two terms for next term
#include<iostream>
using namespace std;
int main() {
   int t1=0,t2=1,n,i,nextTerm;
   n = 8;
   for ( i = 1; i <= n; ++i) {
      if(i == 1) {
         cout << " " << t1 ;
         continue;
      }
      if(i == 2) {
         cout << " " << t2 << " " ;
         continue;
      }
      nextTerm = t1 + t2 ;
      t1 = t2 ;
      t2 = nextTerm ;
      cout << nextTerm << " ";
   }
}
0 1 1 2 3 5 8 13
Python list | pop()

22 Jun, 2022
Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.
Syntax:
list_name.pop(index)
Parameter: 
index (optional) – The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed.
Returns: The last value or the given index value from the list.
Exception: When the index is out of range, it returns IndexError.
Python3
# Python3 program for pop() method list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last element from the listprint(list1.pop()) # Print list after removing last elementprint("New List after pop : ", list1, "\n") list2 = [1, 2, 3, ('cat', 'bat'), 4] # Pop last three elementprint(list2.pop())print(list2.pop())print(list2.pop()) # Print listprint("New List after pop : ", list2, "\n")
Output: 
6
New List after pop :  [1, 2, 3, 4, 5] 

4
('cat', 'bat')
3
New List after pop :  [1, 2] 
Python3
# Python3 program showing pop() method# and remaining list after each pop list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last# element from the listprint(list1.pop(), list1) # Pops and removes the 0th index# element from the listprint(list1.pop(0), list1)
Output:
6 [1, 2, 3, 4, 5]
1 [2, 3, 4, 5]
Python3
# Python3 program for error in pop() method list1 = [ 1, 2, 3, 4, 5, 6 ]print(list1.pop(8))
Output: 
Traceback (most recent call last):
  File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in 
    print(list1.pop(8))
IndexError: pop index out of range
A list of the fruit contains fruit_name and property saying its fruit. Another list consume has two items juice and eat. With the help of pop() and append() we can do something interesting. 
Python3
# Python3 program demonstrating# practical use of list pop() fruit = [['Orange','Fruit'],['Banana','Fruit'], ['Mango', 'Fruit']]consume = ['Juice', 'Eat']possible = [] # Iterating item in list fruitfor item in fruit :         # Iterating use in list consume    for use in consume :                 item.append(use)        possible.append(item[:])        item.pop(-1)print(possible)
Output: 
[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'],
 ['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'],
 ['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]
Time Complexity : 
Complexity of all above examples is constant O(1) in both average and amortized case 
nidhi_biet
pavelu786
AmiyaRanjanRout
simmytarika5
devendrasalunke
Python-Built-in-functions
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.