code-rag-bench/online-tutorials huggingface dataset:
p5.js | noiseSeed() Function - GeeksforGeeks

29 Jan, 2020
The noiseSeed() function is used to set a seed value for the noise() function. The noise() function, by default returns a number that is semi-random, meaning that the noise value would be the same for a coordinate only until the program is running. Running the program for the next time would yield a different value.
These noise values can be made constant by setting a non-changing seed value in the program so that it returns the same values every time when the program is run.
Syntax:
noiseSeed( seed )
Parameters: This function accepts a single parameter as mentioned above and described below:
seed: This parameter holds a number which represents the seed value.
Return Value: This function does not return any value.
Below example illustrates the noiseSeed() function in p5.js:
Example:
let x_coordinate = 0.0;let plot_y = 0.0;   function setup() {    createCanvas(400, 200);}   function draw() {       // Specifying a noise seed value    noiseSeed(100);       if (x_coordinate < 10) {                  // Get noise with x coordinate        x_noise = noise(x_coordinate);             // Output the noise along with        // its corresponding coordinate        coord_text = "Noise for x coordinate "            + x_coordinate + " is " + x_noise;                  text(coord_text, 10, plot_y);           // Increment the x coordinate        x_coordinate++;           // Increase the y coordinate        // for plotting        plot_y = plot_y + 15;    }}
Output: The values are constant every time the program is run.
Running the program for the first time:
Running the program for the second time:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/noiseSeed
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Python | Pandas dataframe.set_value() - GeeksforGeeks

24 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.set_value() function put a single value at passed column and index. It takes the axis labels as input and a scalar value to be placed at the specified index in the dataframe. Alternative to this function is .at[] or .iat[].
Syntax:DataFrame.set_value(index, col, value, takeable=False)Parameters :index : row labelcol : column labelvalue : scalar valuetakeable : interpret the index/col as indexers, default False
Return : frame : DataFrame If label pair is contained, will be reference to calling DataFrame, otherwise a new object
Example #1: Use set_value() function to set the value in the dataframe at a particular index.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2],                   "B":[3, 2, 4, 3, 4],                    "C":[2, 2, 7, 3, 4],                   "D":[4, 3, 6, 12, 7]})  # Print the dataframedf
Lets use the dataframe.set_value() function to set value of a particular index.
# set value of a cell which has index label "2" and column label "B"df.set_value(2, 'B', 100)
Output : Example #2: Use set_value() function to set value of a non-existent index and column in the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2],                   "B":[3, 2, 4, 3, 4],                    "C":[2, 2, 7, 3, 4],                    "D":[4, 3, 6, 12, 7]})  # Print the dataframedf
Lets use the dataframe.set_value() function to set value of a particular index.
# set value of a cell which has index label "8" and column label "8"df.set_value(8, 8, 1000)
Output :
Notice, for the non-existent row and column in the dataframe, a new row and column has been inserted.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
Moment.js isAfter() Function

29 Jul, 2020
You can check whether a date is after a particular date in Moment.js using the isAfter() function that checks if a moment is after another moment. The first argument will be parsed as a moment, if not already so.
Syntax:
moment().isAfter(Moment|String|Number|Date|Array);
moment().isAfter(Moment|String|Number|Date|Array, String);

Parameter: It can be either Moment|String|Number|Date|Array.
Returns: True or False
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
// Requiring moduleconst moment = require('moment');  var bool1 = moment('2010-10-20')    .isAfter('2010-10-21'); //falseconsole.log(bool1);  var bool2 = moment('2019-10-20')    .isAfter('2010-12-31', 'year'); //trueconsole.log(bool2);
Steps to run the program:
The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false
true

The project structure will look like this:
Make sure you have installed moment module using the following command:npm install moment
npm install moment
Run index.js file using below command:node index.jsOutput:false
true

node index.js
Output:
false
true

Example 2: Filename: index.js
// Requiring moduleconst moment = require('moment');  function checkIsAfter(date1, date2) {    return moment(date1).isAfter(date2);}  var bool = checkIsAfter('2010-10-20', '2010-10-21'); console.log(bool);
Run index.js file using below command:
node index.js
Output:
false

Reference: https://momentjs.com/docs/#/query/is-after/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File flush() method in Python

29 Sep, 2021
Python allows users to manage files by using the concept of file handling. A user can open, read, write, manipulate files and can perform many other file handling operations to a file. One of these file handling operations is the file flush() method in Python.  
The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method. Syntax: 
fileObject.flush()
This method does not require any parameters and it does not return anything.Example 1: Now let us look at the below example which illustrates the use of flush() method. Before going through the program a text file gfg.txt is created having the below content.  
 
Python
# opening the file in read modefileObject = open("gfg.txt", "r") # clearing the input bufferfileObject.flush() # reading the content of the filefileContent = fileObject.read() # displaying the content of the fileprint(fileContent) # closing the filefileObject.close()
Output: 
Geeks 4 geeks!
In the above program, the gfg.txt is opened in read mode then the flush() method only clears the internal buffer of the file, it does not affect the content of the file. So, the contents of the file can be read and displayed.Example 2: Now let us look at another example which demonstrates the use of the flush() method. 
Python
# program to demonstrate the use of flush() # creating a filefileObject = open("gfg.txt", "w+") # writing into the filefileObject.write("Geeks 4 geeks !") # closing the filefileObject.close()   # opening the file to read its contentfileObject = open("gfg.txt", "r") # reading the contents before flush()fileContent = fileObject.read() # displaying the contentsprint("\nBefore flush():\n", fileContent)   # clearing the input bufferfileObject.flush() # reading the contents after flush()# reads nothing as the internal buffer is clearedfileContent = fileObject.read() # displaying the contentsprint("\nAfter flush():\n", fileContent) # closing the filefileObject.close()
Output: 
Before flush():
Geeks 4 geeks!

After flush():
In this program initially, we create gfg.txt file and write Geeks 4 geeks! as content in it and then we close the file. After that we read and display the contents of the file and then the flush() method is called which clears the input buffer of the file so the fileObject reads nothing and fileContent remains an empty variable. Hence nothing is displayed after flush() method.
simmytarika5
Picked
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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 | Get unique values from a list
Python | datetime.timedelta() function
turtle.getscreen() function in Python

23 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to Return the TurtleScreen object, the turtle is drawing on.  It doesn’t require any argument. So TurtleScreen-methods can be called for that object.
Syntax :
turtle.getscreen()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle    # get turtle screen object# and store it sc=turtle.getscreen()  # print the turtle screen objectprint(sc)
Output :
<__main__.Screen object>

Example 2 :
Python3
# import packageimport turtle    # get turtle screen object# and store it sc=turtle.getscreen()  # use it for turtle screen methodssc.setup(400,400)sc.bgcolor("blue")
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Replace all occurrences of a substring in a string - GeeksforGeeks

28 Apr, 2020
Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other.
Input : test_str = “geeksforgeeks”s1 = “geeks”s2 = “abcd”Output : test_str = “abcdsforabcds”Explanation : We replace all occurrences of s1 with s2 in test_str.
Input : test_str = “geeksforgeeks”s1 = “for”s2 = “abcd”Output : test_str = “geeksabcdgeeks”
We use maketrans() and translate(). This is inbuild way to perform this task. This function maintains the table internally and performs the task of swapping.
# Python3 code to demonstrate working of # Swap Binary substring# Using translate()  # initializing stringtest_str = "geeksforgeeks"  # printing original stringprint("The original string is : " + test_str)  # Swap Binary substring# Using translate()temp = str.maketrans("geek", "abcd")test_str = test_str.translate(temp)  # printing result print("The string after swap : " + str(test_str)) 
The original string is : geeksforgeeks
The string after swap : accdsforaccds

Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
Maximum Depth of Binary Tree in Python

Suppose we have one binary tree. We have to find the maximum depth of that tree. The maximum depth of a tree is the maximum number of nodes that are traversed to reach the leaf from the root using the longest path. Suppose the tree is like below. The depth will be 3 here.
To solve this, we will follow these steps.
Here we will use the recursive approach. The method is solve(root, depth = 0)
if the root is empty, then return depth
otherwise return max of solve(left, depth + 1) and solve(left, depth + 1)
Let us see the following implementation to get a better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
         else:
            temp.left = TreeNode(0)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         if data is not None:
            temp.right = TreeNode(data)
         else:
            temp.right = TreeNode(0)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def maxDepth(self, root):
      """
      :type root: TreeNode
      :rtype: int
      """
      return self.solve(root)
   def solve(self,root,depth = 0):
      if root == None:
         return depth
      return max(self.solve(root.left,depth+1),self.solve(root.right,depth+1))
tree1 = make_tree([1,2,2,3,4,None,3])
ob1 = Solution()
print(ob1.maxDepth(tree1))
tree1 = make_tree([1,2,2,3,4,None,3])
3
The margin Shorthand Property in CSS

The CSS margin shorthand property is used to define the margin area for an element. It sets values in clock-wise direction, i.e. margin-top, margin-right, margin-bottom and then margin-left.
The syntax of CSS margin property is as follows −
Selector {
   margin: /*value*/
}
The following examples illustrate CSS margin shorthand property −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: 7% auto -3% 25%;
   width: 40px;
   height: 40px;
   padding: 0.9rem;
   box-shadow: inset 0 0 50px turquoise;
   border: thin solid;
}
div > div {
   border-top-right-radius: 100px;
   border-bottom-right-radius: 500px;
   border-top-left-radius: 30px;
   box-shadow: inset 0 0 6px navy;
}
div > div > div {
   padding: 0.3em;
   margin: 2px -40px;
   box-shadow: inset 0 0 16px orange;
   border-radius: 50%;
}
#one {
   padding: 50px;
   border-radius: 10px;
}
</style>
</head>
<body>
<div id="one">
<div>
<div></div>
</div>
</div>
</body>
</html>
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
article {
   margin: 2em 1em;
   background-color: bisque;
}
span {
   margin: -23% 83%;
   border-left: dashed;
   background-image: linear-gradient(to right, lightgreen, forestgreen);
   font-size: 1.4em;
   font-style: italic;
}
</style>
</head>
<body>
<h2>What is Spring Framework?</h2>
<article>
Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.<span> Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB.</span>
</article>
</body>
</html>
How to correctly use WITH ROLLUP in MySQL?

The syntax is as follows to use WITH ROLLUP −
select yourColumnName1,sum(yourColumnName2) from yourTableName
 group by yourColumnName1 with rollup;
Let us first create a table −
mysql> create table DemoTable1622
    -> (
    -> EmployeeCountryName varchar(20),
    -> EmployeeSalary int
    -> );
Query OK, 0 rows affected (0.44 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1622 values('US',4500);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1622 values('UK',1500);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1622 values('AUS',1700);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1622 values('UK',1900);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1622 values('US',3900);
Query OK, 1 row affected (0.42 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1622;
This will produce the following output −
+---------------------+----------------+
| EmployeeCountryName | EmployeeSalary |
+---------------------+----------------+
| US                  |           4500 |
| UK                  |           1500 |
| AUS                 |           1700 |
| UK                  |           1900 |
| US                  |           3900 |
+---------------------+----------------+
5 rows in set (0.00 sec)
Here is the query to correctly use WITH ROLLUP in MySQL −
mysql> select EmployeeCountryName,sum(EmployeeSalary) from DemoTable1622
    -> group by EmployeeCountryName with rollup;
This will produce the following output −
+---------------------+---------------------+
| EmployeeCountryName | sum(EmployeeSalary) |
+---------------------+---------------------+
| AUS                 |                1700 |
| UK                  |                3400 |
| US                  |                8400 |
| NULL                |               13500 |
+---------------------+---------------------+
4 rows in set (0.02 sec)
Java BeanUtils - Comparing Beans

In Apache Commons Beanutils, you can compare the JavaBean objects by using the BeanComparator class based on a specified shared property value. This can be done by using the org.apache.commons.beanutils.BeanComparator comparator.
The below example shows how to compare the two different beans. We will be creating two objects and set the first object to "BMW" and the other object to "AUDI". Then, we will compare the objects by using the BeanComparator by calling its compare() method.
Note: For BeanComparator, commons-collection and commons-logging jar files need to be included.
package com.javadb.apachecommons.beanutils;
import org.apache.commons.beanutils.BeanComparator;

public class BeanComparatorExample {
    public static void main(String[] args) {
        Car car1 = new Car();
        car1.setBrand("BMW");
        
        Car car2 = new Car();
        car2.setBrand("AUDI");
        
        BeanComparator comparator = new BeanComparator("brand");
        
        System.out.println("The value after comparing two beans is: " + comparator.compare(car1, car2));
    }
}
Now we will create one more class with the below code and save it as Car.java.
package com.javadb.apachecommons.beanutils;

public class Car {
    private String brand;
	
    public String getBrand() {
        return brand;
    }
    
    public void setBrand(String brand) {
        this.brand = brand;
    }
}
Save the above first code as BeanComparatorExample.java.
Save the above first code as BeanComparatorExample.java.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.

    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
Build a Vertical Navigation Bar with CSS

To build a vertical navigation bar, you can try to run the following code.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ul {
            list-style-type: none;
            margin: 5;
            padding: 5;
         }
         li a {
            display: block;
            width: 70px;
            background-color: orange;
         }
      </style>
   </head>
   <body>
      <ul>
         <li><a href = "#home">Home</a></li>
         <li><a href = "#company">Company</a></li>
         <li><a href = "#product">Product</a></li>
         <li><a href = "#services">Services</a></li>
         <li><a href = "#contact">Contact</a></li>
      </ul>
   </body>
</html>
Strictly increasing or decreasing array - JavaScript

In Mathematics, a strictly increasing function is that function in which the value to be plotted always increase. Similarly, a strictly decreasing function is that function in which the value to be plotted always decrease.
We are required to write a JavaScript function that takes in an array of numbers and returns true if it’s either strictly increasing or strictly decreasing, otherwise returns false.
Following is the code −
const arr = [12, 45, 6, 4, 23, 23, 21, 1];
const arr2 = [12, 45, 67, 89, 123, 144, 2656, 5657];
const sameSlope = (a, b, c) => (b - a < 0 && c - b < 0) || (b - a > 0 && c
- b > 0);
const increasingOrDecreasing = (arr = []) => {
   if(arr.length <= 2){
      return true;
   };
   for(let i = 1; i < arr.length - 1; i++){
      if(sameSlope(arr[i-1], arr[i], arr[i+1])){
         continue;
      };
      return false;
   };
   return true;
};
console.log(increasingOrDecreasing(arr));
console.log(increasingOrDecreasing(arr2));
Following is the output in the console −
false
true
Use UNION ALL to insert records in two tables with a single query in MYSQL

Here is the query to create first table.
mysql> create table DemoTable1
   -> (
   -> StudentName varchar(20),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.67 sec)
To understand the above concept, let us create second table.
mysql> create table DemoTable2
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values('Chris');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2;
This will produce the following output −
+-------+
| Name  |
+-------+
| Chris |
+-------+
1 row in set (0.00 sec)
Here is the query to select and insert records with a single MySQL query −
mysql> insert into DemoTable1
   -> select Name,89 from DemoTable2
   -> union all
   -> select Name,98 from DemoTable2;
Query OK, 2 rows affected (0.15 sec)
Records: 2  Duplicates: 0  Warnings: 0
Now you can select records from the first table −
mysql> select * from DemoTable1;
This will produce the following output −
+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           89 |
| Chris       |           98 |
+-------------+--------------+
2 rows in set (0.00 sec)
How to set your python path on Linux?

To set the PYTHONPATH on Linux to point Python to look in other directories for the module and package imports, export the PYTHONPATH variable as follows:
$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
How to get a number of vowels in a string in JavaScript?

Vowels in English language are a,e,i,o and u. Make sure that, in any string these vowels can be both cases ( either small or capital). 
The following example, using a user defined function called 'noOfVowels()', reads an input string and compares that string with another string which contains only vowels( 'aAeEiIoOuU'). It takes the help of indexOf() method to proceed the task. 
The indexOf() method displays index of a character whenever the character is common to both the strings, in unmatched case it displays '-1' as the output. Here it compares each and every character of the input string to the vowel string and whenever vowels got matched, it internally increments a user defined variable called "vowelsCount", which is initially 0. Eventually, the value in the "vowelsCount" is displayed as the output.
Live Demo
<html>
<body>
<script>
   function noOfVowels(string) {
      var listOfVowels = 'aAeEiIoOuU';
      var vowelsCount = 0;
      for(var i = 0; i < string.length ; i++) {
         if (listOfVowels.indexOf(string[i]) !== -1) {
            vowelsCount += 1;
        }
      }
   return vowelsCount;
   }
   document.write(noOfVowels("Tutorix is one of the best e-platforms"));
</script>
</body>
</html>
12
Python | Get matching substrings in string - GeeksforGeeks

25 Jun, 2019
The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionUsing list comprehension is the naive and brute force method to perform this particular task. In this method, we try to get the matching string using the “in” operator and store it in new list.
# Python3 code to demonstrate working of# Get matching substrings in string# Using list comprehension  # initializing string test_str = "GfG is good website"  # initializing potential substringstest_list = ["GfG", "site", "CS", "Geeks", "Tutorial" ]  # printing original string print("The original string is : " + test_str)  # printing potential strings listprint("The original list is : " + str(test_list))  # using list comprehension# Get matching substrings in stringres = [sub for sub in test_list if sub in test_str]  # printing result print("The list of found substrings : " + str(res))
The original string is : GfG is good website
The original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial']
The list of found substrings : ['GfG', 'site']

 
Method #2 : Using filter() + lambdaThis task can also be performed using the filter function which performs the task of filtering out the resultant strings that is checked for existence using the lambda function.
# Python3 code to demonstrate working of# Get matching substrings in string# Using lambda and filter()  # initializing string test_str = "GfG is good website"  # initializing potential substringstest_list = ["GfG", "site", "CS", "Geeks", "Tutorial" ]  # printing original string print("The original string is : " + test_str)  # printing potential strings listprint("The original list is : " + str(test_list))  # using lambda and filter()# Get matching substrings in stringres = list(filter(lambda x:  x in test_str, test_list))  # printing result print("The list of found substrings : " + str(res))
The original string is : GfG is good website
The original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial']
The list of found substrings : ['GfG', 'site']

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
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
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
How to print without newline in Python?
Java Program to Print any Statement without Using the Main Method - GeeksforGeeks

17 Nov, 2020
As we know that the static block executes before the main method, hence we can place the statement that we want to execute in the static block, But in case of JDK7, and the above versions of the JDK, the code would not execute as compiler firstly looks for the main method before any other thing. Also, it depends on the IDE being used to run the program, ie the program might get executed successfully on some IDE, and might not on some IDE’s. Also, we can abnormally exit our program in the static block so that the JVM will not check the main method, but as discussed it depends on IDE, whether the program will run or not.
Example: Below is the code implementation of the above approach.
Java
// Java Program printing the statement without using main// method.  class PrintWithoutMain {      // static block    static    {        // prints "Hello World!!" to the console        System.out.println("Hello World!!");          // exit from the program        System.exit(1);    }}
Output
Hello World!!
The above code does not compile before and on JDK7. Also, one might get the error like below if run the above code on some IDE like Intellij or Netbeans or console. 
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
getmaxy() function in C - GeeksforGeeks

25 Jan, 2018
The header file graphics.h contains getmaxy() function which returns the maximum Y coordinate for current graphics mode and driver.Syntax :
int getmaxy();

Below is the implementation of getmaxy() function:
// C Implementation for getmaxy()#include <graphics.h>#include <stdio.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;    char arr[100];      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // sprintf stands for “String print”.    // Instead of printing on console, it    // store output on char buffer which    // are specified in sprintf    sprintf(arr, "Maximum Y coordinate for current "        "graphics mode And driver = %d", getmaxy());      // outtext function displays text at    // current position.    outtext(arr);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Converting Strings to Numbers in C/C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
std::string class in C++
fork() in C
Different methods to reverse a string in C/C++
Kill a Process by name using Python - GeeksforGeeks

30 Jun, 2021
A process is identified on the system by what is referred to as a process ID and no other process can use that number as its process ID while that first process is still running. Imagine you are a system administrator of a company and you start an application from your menu and you start using that application suddenly you notice that the application stopped working or die unexpectedly. You again try to start that application but it turns out that application never shut down completely. Since you are an administrator you type a command to Process ID and kill that process immediately. Imagine this scenario the employees of your company came to you every day complaining about the same situation since they don’t know what is PID and how to kill a process. So you came up with the idea of writing a script in Python which take input only the name of application or process and shut it down completely. You gave this script to your employees so every time this happens they don’t need to complain to you or know what is process id or how to kill the process, just enter the name, and everything will be taken care of. 
Functions used: 
os.popen(): This method is used to opens a pip to and from command. In the image below you can see that the process firefox is running 
os.kill(): This method in Python is used to send a specified signal to the process with specified process id. 
Below is the implementation.
In the image below you can see that the process firefox is running.  
Python3
import os, signal  def process():         # Ask user for the name of process    name = input("Enter process Name: ")    try:                 # iterating through each instance of the process        for line in os.popen("ps ax | grep " + name + " | grep -v grep"):            fields = line.split()                         # extracting Process ID from the output            pid = fields[0]                         # terminating process            os.kill(int(pid), signal.SIGKILL)        print("Process Successfully terminated")             except:        print("Error Encountered while running script")  process()
Output: 
In the image above you can see that all the instance of firefox has been terminated. The one that you seeing in the image is the instance that is being called by grep command. You can now check that your firefox browser has been shut completely. 
varshagumber28
Python os-module-programs
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
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
Python | Pandas Series.str.translate() - GeeksforGeeks

29 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.translate() is one of most important and complex string method. It uses a translate table to translate the caller series of string according to the translate table. If there are more than one values to be translated, a dictionary is passed to maketrans function to create a translate table.
Syntax: Series.str.translate(table, deletechars=None)
Parameters:table: Translation table made of dictionary in Python3 and lists in Python2.deletechars: String type, characters to be deleted. This Parameter works properly in Python2 only(till pandas v0.23)
Return type: Series of strings with translated values
To download the data set used in following example, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1:In this example, a translation table is created through a dictionary. The dictionary has a, b and c as its keys and X, Y and Z as values respectively. Translation table is created to replace a, b and c with X, Y and Z respectively. This table is passed to str.translate() method to make changes accordingly.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # creating dictionary for trans tabletrans_dict ={"a": "X", "b": "Y", "c": "Z"}  # creating translate table from dictionarytrans_table ="abc".maketrans(trans_dict)  # translating through passed transtabledata["Name"]= data["Name"].str.translate(trans_table)  # displaydata
Output:As shown in the output images, the changes were made and letters were replaced successfully.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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()
Change matplotlib line style in mid-graph - GeeksforGeeks

12 Nov, 2020
Prerequisite: Matplotlib
In this article we will learn how to change line style in mid-graph using matplotlib in Python.
Matplotlib: It is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002.
Line style: Line style is a feature that describes in which fashion or style line is drawn. Following image shows the key that has to provided as input parameter and what line style it will produce:
Approach:
Import the matplotlib.pyplot library and other for data (optional)Import or create some dataDraw a graph plot with different line style is middle.
Import the matplotlib.pyplot library and other for data (optional)
Import or create some data
Draw a graph plot with different line style is middle.
Example 1:
In this example we will use simple steps mentioned above and form a graph with two different line styles.
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.linspace(0, 10, 100)y = 3 * x + 2  below = y < 15above = y >= 15  # Plot lines below as dotted-------plt.plot(x[below], y[below], '--')  # Plot lines above as solid________plt.plot(x[above], y[above], '-')  plt.show()
Output :
Example 2 :
In this example we will use simple steps mentioned above and form a graph with two different line styles in one sine function.
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.linspace(0, 10, 100)y = np.sin(x)  below = y < .5above = y >= .5  # Plot lines below as dotted-------plt.plot(x[below], y[below], '--')  # Plot lines above as solid_______plt.plot(x[above], y[above], '-')  plt.show()
Output :
Example 3 :
This is similar to above example with extra cosine function to show different feature of line styles in mid graph.
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x)  below = abs(y1-y2) < .2above = abs(y1-y2) >= .2  # Plot lines below as dotted-------plt.plot(x[below], y1[below], 'r--')  # Plot lines below as dotted-------plt.plot(x[below], y2[below], 'g--')  # Plot lines above as solid_______plt.plot(x[above], y1[above], 'r-')  # Plot lines above as solid_______plt.plot(x[above], y2[above], 'g-')  plt.show()
Output :
Python-matplotlib
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 | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Program to find number of boxes that form longest chain in Python?

Suppose we have a list of boxes, here each entry has two values [start, end] (start < end). We can join two boxes if the end of one is equal to the start of another. We have to find the length of the longest chain of boxes.
So, if the input is like blocks = [ [4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ], then the output will be 4, as we can form the chain: [1, 2], [2, 4], [4, 5], [5, 6]
To solve this, we will follow these steps:
if boxes are empty, thenreturn 0
if boxes are empty, then
return 0
return 0
sort the list boxes
sort the list boxes
dic := an empty map
dic := an empty map
for each start s and end e in boxes, dodic[e] := maximum of dic[e] and dic[s] + 1
for each start s and end e in boxes, do
dic[e] := maximum of dic[e] and dic[s] + 1
dic[e] := maximum of dic[e] and dic[s] + 1
return maximum of the list of all values of dic
return maximum of the list of all values of dic
Let us see the following implementation to get better understanding:
 Live Demo
import collections

class Solution:
   def solve(self, boxes):
      if not boxes:
         return 0
      boxes.sort()
      dic = collections.defaultdict(int)
      for s, e in boxes:
         dic[e] = max(dic[e], dic[s] + 1)
      return max(dic.values())

ob = Solution()
boxes = [
   [4, 5],
   [5, 6],
   [4, 8],
   [1, 2],
   [2, 4]
]
print(ob.solve(boxes))
[[4, 5],
[5, 6],
[4, 8],
[1, 2],
[2, 4] ]
4
How to load and show image in OpenCV using C++?

In this topic, we will determine how to load and show images using OpenCV in C++. There are the following functions required for loading and showing an image in OpenCV.
 Mat: Mat is not a function. It is a data structure, a type of variable. Like int, char, string variable types in C++, Mat is a variable of OpenCV, which creates a matrix data structure to load images inside it. In this program, we wrote 'Mat myImage;'. That means we are declaring a matrix variable named 'myImage'.
 namedWindow(): It allocates some memory and creates a window to show the image. It works like a photo frame. In OpenCV, we have to make the function as 'namedWindow("name of the window",flag)'.
3. imread(): This function reads an image from a defined location. This program reads the image from 'C:' drive. To use this function, you have to write it as 'imread("location of the image/name of the image with the extension", flag)'.
 imshow(): This function shows the image in the defined window. To use this function you have to write as 'imshow(name of the window", name of the matrix)'.
 waitKey(): This is a vital function of OpenCV. To process images and executes operations, we must allow the system some time. If we don't do it, we will not
This function waits for a certain period before closing the program. If you use waitKey(10000), it will close the program after 10 seconds. If you write waitKey(0), it will get the desired output. This function will enable us to give the system the required time to operate. wait for the keystroke from the user. When the user clicks any key from the keyboard, the program will stop. This function has to be written as 'waitKey(milliseconds)'.
 destroyWindows(): This function closes all windows. When we create windows, we allocate some memory. destroyWindow() function releases that memory to the system.
The following program shows how to load and show an image using OpenCV Libraries.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat myImage;//declaring a matrix named myImage//
   namedWindow("PhotoFrame");//declaring the window to show the image//
   myImage = imread("lakshmi.jpg");//loading the image named lakshme in the matrix//
   if (myImage.empty()) {//If the image is not loaded, show an error message//
      cout << "Couldn't load the image." << endl;
      system("pause");//pause the system and wait for users to press any key//
      return-1;
   }
   imshow("PhotoFrame", myImage);//display the image which is stored in the 'myImage' in the "myWindow" window//  
   destroyWindow("Photoframe");//close the window and release allocate memory//
   waitKey(0);//wait till user press any key
   return 0;
}
On executing the above program, we get the following output −
What are string and String data types in C#?

String stands for System.String whereas string is an alias in C# for System.String −
For example −
string str = "Welcome!";
It’s not essential, but generally String is used when you work with classes −
string str = String.Format("Welcome! {0}!", user);
Since string is an alias for System.String. The alias for other datatypes are −
object: System.Object
string: System.String
bool: System.Boolean
float: System.Single
double: System.Double
decimal: System.Decimal
byte: System.Byte
sbyte: System.SByte
short: System.Int16
ushort: System.UInt16
int: System.Int32
uint: System.UInt32
long: System.Int64
ulong: System.UInt64
char: System.Char
The String type in C# allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms − quoted and @quoted.
String str = "Okay!";
Perl symlink Function

This function creates a symbolic link between OLDFILE and NEWFILE. On systems that don't support symbolic links, causes a fatal error.
Following is the simple syntax for this function −
symlink ( OLDFILE, NEWFILE )

This function returns 0 on failure and 1 on success.
Following is the example code showing its basic usage, first create one file test.txt in /tmp directory and then try out following example it will create a symbolic link in the same directory::
#!/usr/bin/perl -w

symlink("/tmp/text.txt", "/tmp/symlink_to_text.txt");
When above code is executed, it produces the following result −
Symbolic link gets created


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page