code-rag-bench/online-tutorials huggingface dataset:
Python | Handling no element found in index() - GeeksforGeeks

27 Sep, 2019
Sometimes, while working with Python lists, we are confronted with a problem in which we need to check whether an element is present in a list and also where exactly, which index it occurs. The convenient solution of it is to use index(). But problem with this can come that sometimes, the desired element might not be present in the list. Let’s discuss a method in which this exception can be handled.
Method : Using ValueError + try + except
In this method, knowing that the value might not exists, we catch the error in try-except block. The ValueError is raised in the absence and can be used to catch this particular exception.
# Python3 code to demonstrate working of# Handling no element found in index()# Using try + except + ValueError  # initializing listtest_list = [6, 4, 8, 9, 10]  # printing listprint("The original list : " + str(test_list))  # Handling no element found in index()# Using try + except + ValueErrortry :    test_list.index(11)    res = "Element found"except ValueError :    res = "Element not in list !"  # Printing resultprint("The value after catching error : " + str(res))
 
The original list : [6, 4, 8, 9, 10]
The value after catching error : Element not in list!

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

In dynamic binding, the method call is bonded to the method body at runtime. This is also known as late binding. This is done using instance methods.
class Super {
   public void sample() {
      System.out.println("This is the method of super class");
   }
}

Public class extends Super {
   Public static void sample() {
      System.out.println("This is the method of sub class");
   }

   Public static void main(String args[]) {
      new Sub().sample()
   }
}
This is the method of sub class
GATE | GATE-CS-2003 | Question 86 - GeeksforGeeks

28 Jun, 2021
Consider the set of relations shown below and the SQL query that follows.
Students: (Roll_number, Name, Date_of_birth)
  Courses: (Course number, Course_name, Instructor)
  Grades: (Roll_number, Course_number, Grade)
 select distinct Name
         from Students, Courses, Grades
         where Students. Roll_number = Grades.Roll_number
              and Courses.Instructor = Korth
              and Courses.Course_number = Grades.Course_number
              and Grades.grade = A
Which of the following sets is computed by the above query?(A) Names of students who have got an A grade in all courses taught by Korth(B) Names of students who have got an A grade in all courses(C) Names of students who have got an A grade in at least one of the courses taught by Korth(D) None of the aboveAnswer: (C)Explanation: The query gives the name of all the students who have scored “A” grade in any of the courses that are taught by Korth.So, C is the correct choice. Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE-IT-2004 | Question 71
Where should I put <script> tags in HTML markup?

The JavaScript code should be inserted between <script> and </script> tags in HTML. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using. Typically, its value will be JavaScript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
 Let us take a simple example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document.
 This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
   <body>
      <script language="javascript" type="text/javascript">
         <!--
            document.write("Hello World!")
         //-->
      </script>
   </body>
</html>
Hello World!
How do you find the length of an array in C#?

To find the length of an array, use the Array.Length() method.
Let us see an example −
 Live Demo
using System;
class Program {
   static void Main(){
      int[] arr = new int[10];
      // finding length
      int arrLength = arr.Length;
      Console.WriteLine("Length of the array: "+arrLength);
   }
}
Length of the array: 10
Above, we have an array −
int[] arr = new int[10];
Now to find the length, we used the Length() method −
int arrLength = arr.Length;
Progress Bars in Python. When dealing with large data, even... | by Sam Wilkinson | Towards Data Science

Just like a watched pot never boils, a watched for loop never ends. When dealing with large datasets, even the simplest operations can take hours. Progress bars can help make data processing jobs less of a headache because:
You get a reliable estimate of how long it will take.You can see immediately if it’s gotten stuck.
You get a reliable estimate of how long it will take.
You can see immediately if it’s gotten stuck.
The first of these is especially valuable in a business environment, where having a solid delivery estimate can make you look super professional. The best/only way I’ve found to add progress bars to Python code is with tqdm. While it is super easy to use, tqdm can be a bit finnicky to set up, especially if you use JupyterLab (which you totally should).
After trawling StackOverflow and some trial and error, I think I’ve found a surefire way to get tqdm up and running (even with JupyterLab)!
First, install tqdm with your package manager of choice (pip, pipenv, anaconda etc). Once it’s installed, you can activate the ipywidgets plugin for JupyterLab by running,
> pip install ipywidgets > jupyter nbextension enable --py widgetsnbextension> jupyter labextension install @jupyter-widgets/jupyterlab-manager
To activate tqdm in a notebook you just need to add a cell with,
%%capturefrom tqdm import tqdm_notebook as tqdmtqdm().pandas()
If you’re just going to be using tqdm in a script, you can skip both of these steps!
You can get a progress bar for any iterable by wrapping it with tqdm(). For example,
my_list = list(range(100))for x in tqdm(my_list):    pass
will give you a (very fast) progress bar. You also use tqdm more explicitly,
my_list = list(range(100))with tqdm(total=len(my_list)) as pbar:    for x in my_list:        pbar.update(1)
There’s also a pandas integration,
df.progress_apply(lambda x: pass)
For more on using tqdm, including things like nested progress bars, check out their documentation.
How can I save HTML locally with JavaScript?

To save HTML locally with JavaScript, create an HTML file and save the following code in it. The code is for cookies in JavaScript −
<!DOCTYPE html>
<html>
   <body>
      <p id="visits"></p>
      <script>
         var visits = parseInt(document.cookie.split("=")[1]);
         if (isNaN(visits)) visits = 0;
         visits++;
         document.cookie = "visits =" + visits;
         document.getElementById("visits").innerHTML = "The page ran " + timesVisited + " times.";
      </script>
   </body>
</html>
Just save the above file and open in a web browser.
Puppet - Agent Setup

Puppet agent is a software application, provided by Puppet labs, which runs on any node in Puppet cluster. If one wants to manage any server using the Puppet master, the Puppet agent software needs to be installed on that particular server. In general, the Puppet agent will be installed on all the machines excluding the Puppet master machine on any given infrastructure. Puppet agent software has the capability to run on most of the Linux, UNIX, and Windows machines. In the following examples, we are using CentOS machine installation Puppet agent software on it.
Step 1 − Enable the official Puppet labs collection repository with the following command.
$ sudo rpm -ivh https://yum.puppetlabs.com/puppetlabs-release-pc1-el7.noarch.rpm

Step 2 − Install the Puppet agent package.
$ sudo yum -y install puppet-agent

Step 3 − Once the Puppet agent is installed, enable it with the following command.
$ sudo /opt/puppetlabs/bin/puppet resource service puppet ensure=running enable = true

One key feature of the Puppet agent is, for the first time when the Puppet agent starts running, it generates a SSL certificate and sends it to the Puppet master which is going to manage it for signing and approval. Once the Puppet master approves the agent’s certificate signature request, it will be able to communicate and manage the agent node.
Note − One needs to repeat the above steps on all the nodes which needs to be configured and managed any a given Puppet master.
 Print
 Add Notes
 Bookmark this page
VBA - Sub Procedure

Sub Procedures are similar to functions, however there are a few differences.
Sub procedures DO NOT Return a value while functions may or may not return a value.
Sub procedures DO NOT Return a value while functions may or may not return a value.
Sub procedures CAN be called without a call keyword.
Sub procedures CAN be called without a call keyword.
Sub procedures are always enclosed within Sub and End Sub statements.
Sub procedures are always enclosed within Sub and End Sub statements.
Sub Area(x As Double, y As Double)
   MsgBox x * y
End Sub
To invoke a Procedure somewhere in the script, you can make a call from a function. We will not be able to use the same way as that of a function as sub procedure WILL NOT return a value.
Function findArea(Length As Double, Width As Variant)
   area Length, Width    ' To Calculate Area 'area' sub proc is called
End Function
Now you will be able to call the function only but not the sub procedure as shown in the following screenshot.
The area is calculated and shown only in the Message box.
The result cell displays ZERO as the area value is NOT returned from the function. In short, you cannot make a direct call to a sub procedure from the excel worksheet.

    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

19 Nov, 2018
Consider the following code sequence having five instructions I1 to I5. Each of these instructions has the following format.
    OP Ri, Rj, Rk 
where operation OP is performed on contents of registers Rj and Rk and the result is stored in register Ri.
   I1 : ADD R1, R2, R3
   I2 : MUL R7, R1, R3
   I3 : SUB R4, R1, R5
   I4 : ADD R3, R2, R4
   I5 : MUL R7, R8, R9 
Consider the following three statements:
S1: There is an anti-dependence between instructions I2 and I5.
S2: There is an anti-dependence between instructions I2 and I4.
S3: Within an instruction pipeline an anti-dependence always 
    creates one or more stalls. 
Which one of above statements is/are correct?
(A) Only S1 is true(B) Only S2 is true(C) Only S1 and S2 are true(D) Only S2 and S3 are trueAnswer: (B)Explanation: The given instructions can be written as below:
I1: R1 = R2 + R3
I2: R7 = R1 * R3
I3: R4 = R1 - R5 
I4: R3 = R2 + R4
I5: R7 = R8 * R9 
An anti-dependency, also known as write-after-read (WAR), occurs when an instruction requires a value that is later updated.
S1: There is an anti-dependence between instructions I2 and I5.
False, I2 and I5 don't form any write after read situation.  
They both write R7.

S2: There is an anti-dependence between instructions I2 and I4.
True, I2 reads R3 and I4 writes it.

S3: Within an instruction pipeline an anti-dependence always 
    creates one or more stalls. 
Anti-dependency can be removed by renaming variables. 
See following example.
1. B = 3
2. A = B + 1
3. B = 7
Renaming of variables could remove the dependency.
1. B = 3
N. B2 = B
2. A = B2 + 1
3. B = 7
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
String Concatenation in Java

You can concatenate two strings in Java either by using the concat() method or by using the ‘+’ , the “concatenation” operator.
The concat() method appends one String to the end of another. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.
public class ConncatSample {
   public static void main(String []args) {
      String s1 = "Hello";
      String s2 = "world";
      String res = s1.concat(s2);
      System.out.print("Concatenation result:: ");
      System.out.println(res);
   }
}
Concatenation result:: Helloworld
Just like the concat method the ‘+’ operator also performs the concatenation operation on the given operators.
public class ConncatSample {
   public static void main(String []args) {
      String s1 = "Hello";
      String s2 = "world";
      String res = s1+s2;
      System.out.print("Concatenation result:: ");
      System.out.println(res);
   }
}
Concatenation result:: Helloworld
How to locate the median in a (Seaborn) KDE plot?

To locate the median in a seaborn KDE plot, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Create random data using numpy.
Find the median of data (Step 2).
Use kdeplot() to plot the shaded region.
Use axvline() method to plot the vertical line.
To display the figure, use show() method.
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(30)
xmedian = np.median(data)
k = sns.kdeplot(x=data, shade=True)
plt.axvline(xmedian, c='red')

plt.show()
PHP if else elseif

Conditional execution of one or more statements is a most important feature of any programming language. PHP provides this ability with its if, else and elseif statements. Primary usage of if statement is as follows −
if (expression)
   statement;
The expression in front of if keyword is a logical expression, evaluated either to TRUE or FALSE. If its value is TRUE, statement in next line is executed, otherwise it is ignored. If there are more than one statements to be executed when the expression is TRUE, statements are grouped by using additional pair of curly brackets,
if (expression){
   statement1;
   statement2;
   ..
}
If another staement or a group of statements are required to be executed when expression is FALSE, else keyword is used and one or more statements (inside another pair of curly brackets) are written below it
if (expression){
   statement1;
   statement2;
   ..
} else {
   statement3;
   statement4;
   ..
}
Following example shows typical use of if and else keywords. It also uses readline() function to read keyboard input in command line execution of following code. It receive marks as input and displays result as pass or fail depending on marks>=50 or not.
 Live Demo
<?php
$marks=(int)readline("enter marks: ");
if ($marks>=50){
   echo "The result is pass" . "\n";
   echo "congratulations" . "\n";
}
else{
   echo "The result is Fail". "\n";
   echo "Better luck next time" . "\n";
}
?>
This will produce following result −
The result is Fail
Better luck next time
Many a times, if a condition is false, you may require to check if another condition is fulfilled. In this case, another if statement has to be used in else clause of first if statement. There may be a series of cascaded if - else blocks which makes the program tedious. PHP provides elseif statement to address this problem.
As the keyword indicates, elseif is combination of if and else keywords. It works similar to else keyword, with a little difference. Conditional logic of the code has multiple if conditions. The program flow falls through cascade of elseif conditionals and first instance of elseif expression being true, its block is executed and the execution comes out. Last conditional block is a part of else clause, which will be executed only if all preceding if and elseif expressions are false
if (expression){
   statement;
}
elseif (expression){
   statement;
}
elseif (expression){
   statement;
}
.
.
else{
   statement;
}
}
In following example, elseif statement is used to calculate grade of student based on marks
 Live Demo
<?php
$marks=(int)readline("enter marks: ");
if ($marks<35)
   echo "fail";
elseif ($marks<50)
   echo "pass class";
elseif ($marks<60)
   echo "second class";
elseif ($marks<75)
   echo "first class";
else
   echo "distinction";
?>
This will produce following result −
fail
Python | sympy.Matrix().col_insert() - GeeksforGeeks

25 Jun, 2019
With the help of Matrix().col_insert() method, we can insert a column in a matrix having dimension nxm, where dimension of inserted column is nx1.
Syntax : Matrix().col_insert()Return : Return a new matrix.
Example #1 :In this example, we are able to insert a column in a matrix by using Matrix().col_insert() method.
# Import all the methods from sympyfrom sympy import *  # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]])  # use the col_insert() method for matrixnew_mat = gfg_mat.col_insert(1, Matrix([[3], [4]]))   print(new_mat)
Output :
Matrix([[1, 3, 2], [2, 4, 1]])
Example #2 :
# Import all the methods from sympyfrom sympy import *  # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]])  # use the col_insert() method for matrixnew_mat = gfg_mat.col_insert(2, Matrix([[13], [24]]))   print(new_mat)
Output :
Matrix([[1, 2, 13], [2, 1, 24]])
SymPy
Python
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()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
How to start the Azure VM using Azure CLI in PowerShell?

To start the stopped Azure VM using Az CLI, we can use the az vm start command. Before starting the azure VM, make sure that you are connected to the desired subscription and the Azure cloud account.
To start the specific VM, we will use the command below.
PS C:\> az vm start -n vmname -g RGname --verbose
Or you can use,
PS C:\> az vm start --name vmname --resource-group RGName --verbose
When you start the multiple VMs, you can specify the “--no-wait” parameter.
PS C:\> az vm start -n vmname -g RGname –no-wait
How can we retrieve a blob datatype from a table using the getBinaryStream() method in JDBC?

The ResultSet interface provides the method named getBlob() to retrieve blob datatype from a table in the database. In addition to this, it also provides a method named getBinaryStream()
Like getBlob() this method also accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column. The difference is unlike the getBlob() method (which returns a Blob object) this method returns an InputStream object which holds the contents of the blob datatype in the form of un-interpreted bytes.
Assume we have created a table named MyTable in the database with the following description.
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Name  | varchar(255) | YES  |     | NULL    |       |
| image | blob         | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
And, we have inserted an image in it with name sample_image. Following program retrieves the contents of the MyTable using the getString() and getBinaryStream() methods.
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingBlob_ByteStream {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");

      //Creating a Statement object
      Statement stmt = con.createStatement();
      //retrieving the data
      ResultSet rs = stmt.executeQuery("select * from MyTable");

      int i = 0;
      System.out.println("Contents of the table");
      while(rs.next()) {
         System.out.println(rs.getString("Name"));
         InputStream inputStream = rs.getBinaryStream("image");
         byte byteArray[] = new byte[inputStream.available()];
         inputStream.read(byteArray);
         FileOutputStream outPutStream = new
         FileOutputStream("E:\\images\\blob_output"+i+".jpg");
         outPutStream.write(byteArray);
         System.out.println("E:\\images\\blob_output"+i+".jpg");
      }
   }
}
Connection established......
Contents of the table
sample_image
E:\images\blob_output0.jpg
How to capture the text from Alert Message in Selenium Webdriver?

We can capture the text from the alert message in Selenium webdriverwith the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the webdriver focus from the main page to the alert.
This is done with the help of the switchTo().alert() method. Once the driver focus is shifted, we can obtain the text of the pop-up with the help of the method switchTo().alert().getText(). Finally we shall use the accept method to accept the alert and dismiss method to dismiss it.
Let us take an example of the below alert and obtain its message −
Alert a = driver.switchTo().alert();
String s= driver.switchTo().alert().getText();
a.accept();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class JsEnterText{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://the-internet.herokuapp.com/javascript_alerts");
      // identify element
      WebElement l = driver.
      findElement(By.xpath("//*[text()='Click for JS Alert']"));
      l.click();
      //switch focus to alert
      Alert a = driver.switchTo().alert();
      //get alert text
      String s= driver.switchTo().alert().getText();
      System.out.println("Alert text is: " + s);
      //accepting alert
      a.accept();
      driver.quit();
   }
}
What are the rules for naming classes in C#?

A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces.
The following is the syntax −
<access specifier> class class_name {
   // member variables
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list) {
      // method body
   }

   <access specifier> <return type> method2(parameter_list) {
   // method body
   }

   ...
   <access specifier> <return type> methodN(parameter_list) {
      // method body
   }
}
The following are the conventions for class names −
The coding conventions for a class name is the name of the class name, for example, it should being PascalCasing −
public class CalculateCost {

}
Above, the class name CalculateCost is in PascalCasing.
Prefer adding class names as noun or noun phrases −
public class Department {

}
How do you improve Matplotlib image quality?

To improve matplotlib image quality we can use greater dot per inch i.e dpi value (greater than 600) and pdf or .eps format can be recommended.
Set the figure size and adjust the padding between and around the subplots.
Make a 2D data raster using a np.array.
Display data as an image, i.e., on a 2D regular raster.
Save the current image using savefig() with dpi=1200 and .eps format,
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.array(
   [[0.1, 0.7, 0.6, 0.3],
   [0.2, 0.6, 0.5, 0.2],
   [0.8, 0.3, 0.80, 0.01],
   [0.3, 0.4, 0.2, 0.1]]
)
plt.imshow(data, interpolation="nearest", cmap="RdYlGn_r")
plt.savefig("myimage.eps", dpi=1200)
plt.show()
Python | Extract substrings between brackets

07 Feb, 2022
Sometimes, while working with Python strings, we can have a problem in which we need to extract the substrings between certain characters and can be brackets. This can have application in cases we have tuples embedded in string. Lets discuss certain ways in which this task can be performed.Method #1 : Using regex One way to solve this problem is by using regex. In this we employ suitable regex and perform the task of extraction of required elements.  
Python3
# Python3 code to demonstrate working of# Extract substrings between brackets# Using regeximport re # initializing stringtest_str = "geeks(for)geeks is (best)" # printing original stringprint("The original string is : " + test_str) # Extract substrings between brackets# Using regexres = re.findall(r'\(.*?\)', test_str) # printing resultprint("The element between brackets : " + str(res))
The original string is : geeks(for)geeks is (best)
The element between brackets : ['(for)', '(best)']
 
 Method #2 : Using list comprehension + isinstance() + eval() The combination of above methods can also be used to solve this problem. In this eval() assume the brackets to be tuples and helps the extraction of strings within them. 
Python3
# Python3 code to demonstrate working of# Extract substrings between brackets# Using list comprehension + eval() + isinstance() # initializing stringtest_str = "[(234, ), 4, (432, )]" # printing original stringprint("The original string is : " + test_str) # Extract substrings between brackets# Using list comprehension + eval() + isinstance()res = [str(idx) for idx in eval(test_str) if isinstance(idx, tuple)] # printing resultprint("The element between brackets : " + str(res))
The original string is : [(234, ), 4, (432, )]
The element between brackets : ['(234, )', '(432, )']
 
saurabh1990aror
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maryam – Perfect OSINT Framework

15 Dec, 2021
OSINT techniques are used to collect the data from publicly possible sources like Social Media Platforms etc. There are various ways to collect information. There are some automated tools that make the task easier. Maryam tool is one of the best tools which is been designed by the OWASP team and has the potential to collect information from open sources. This tool is developed in the Python language and it also comes as the package in the Python Pip. We can collect lots of information from Twitter, LinkedIn, and also from Google. This tool is also available on the GitHub platform. It’s free and open-source to use.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/saeeddhqan/Maryam.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd Maryam
Step 3: You are in the directory of the Maryam. Now you have to install a dependency of the Maryam using the following command.
sudo pip install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system.
./maryam
Example 1: Modules
show modules
In this example, we have displayed the list of available modules which the tool offers.
Example 2: Anonymous Email Grabbing – OSINT
email_search
In this example, we are using the Email Grabbing module.
email_search -q gmail.com -e bing,google,yahoo –output
We have got the email address for public sources.
Example 3: Social Nets – OSINT
social_nets
In this example, we are using the Social Nets module.
social_nets -q geeksforgeeks.org -e google,yahoo,bing
We have got the information about the geeksforgeeks username for public sources.
Example 4: Crawl Pages – Footprinting
crawl_pages
In this example, we are using the Crawl Pages module.
crawl_pages -d geeksforgeeks.org -r “https?://[A-z0-9./]+” –output
We have got the URLs that match the regex which is been provided in the query
Example 5: Getting Profiles From LinkedIn – Search
linkedin
In this example, we are using the LinkedIn module.
linkedin -q geeksforgeeks -e google,bing,yahoo
We have got the link of profiles on LinkedIn which are been associated with the geeksforgeeks organization.
Example 6: Getting Profiles From Twitter – Search
twitter
In this example, we are using the Twitter module.
twitter -q geeksforgeeks -e bing,google
We have got the link of profiles on Twitter which are been associated with the geeksforgeeks organization.
adnanirshad158
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.read() method

18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.read() method in Python is used to read at most n bytes from the file associated with the given file descriptor.
If the end of the file has been reached while reading bytes from the given file descriptor, os.read() method will return an empty bytes object for all bytes left to be read.
A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc.
Note: os.read() method is intended for low-level operation and should be applied to a file descriptor as returned by os.open() or os.pipe() method.
Syntax: os.read(fd, n)
Parameter:fd: A file descriptor representing the file to be read.n: An integer value denoting the number of bytes to be read from the file associated with the given file descriptor fd.
Return Type: This method returns a bytestring which represents the bytes read from the file associated with the file descriptor fd.
Consider the below text as the content of the file named Python_intro.txt.
Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.
# Python program to explain os.read() method     # importing os module import os  # File path path = "/home / ihritik / Documents / Python_intro.txt"    # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDONLY)    # Number of bytes to be readn = 50  # Read at most n bytes # from file descriptor fd# using os.read() methodreadBytes = os.read(fd, n)  # Print the bytes readprint(readBytes)  # close the file descriptoros.close(fd)
b'Python is a widely used general-purpose, high leve'

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Fuzzy Clustering

17 Sep, 2019
Prerequisite: Clustering in Machine Learning
What is clustering?Clustering is an unsupervised machine learning technique which divides the given data into different clusters based on their distances (similarity) from each other.
The unsupervised k-means clustering algorithm gives the values of any point lying in some particular cluster to be either as 0 or 1 i.e., either true or false. But the fuzzy logic gives the fuzzy values of any particular data point to be lying in either of the clusters. Here, in fuzzy c-means clustering, we find out the centroid of the data points and then calculate the distance of each data point from the given centroids until the clusters formed becomes constant.
Suppose the given data points are {(1, 3), (2, 5), (6, 8), (7, 9)} The steps to perform algorithm are:
Step 1: Initialize the data points into desired number of clusters randomly.Let’s assume there are 2 clusters in which the data is to be divided, initializing the data point randomly. Each data point lies in both the clusters with some membership value which can be assumed anything in the initial state.
The table below represents the values of the data points along with their membership (gamma) in each of the cluster.
Cluster    (1, 3)    (2, 5)    (4, 8)    (7, 9)
1)          0.8        0.7       0.2       0.1
2)          0.2        0.3       0.8       0.9

Step 2: Find out the centroid.The formula for finding out the centroid (V) is:
Where, μ is fuzzy membership value of the data point, m is the fuzziness parameter (generally taken as 2), and xk is the data point.Here,
V11  = (0.82 *1 + 0.72 * 2 + 0.22 * 4 + 0.12 * 7) / ( (0.82 + 0.72  + 0.22  + 0.12 ) = 1.568
V12  = (0.82 *3 + 0.72 * 5 + 0.22 * 8 + 0.12 * 9) / ( (0.82 + 0.72  + 0.22  + 0.12 ) = 4.051
V11  = (0.22 *1 + 0.32 * 2 + 0.82 * 4 + 0.92 * 7) / ( (0.22 + 0.32  + 0.82  + 0.92 ) = 5.35
V11  = (0.22 *3 + 0.32 * 5 + 0.82 * 8 + 0.92 * 9) / ( (0.22 + 0.32  + 0.82  + 0.92 ) = 8.215

Centroids are: (1.568, 4.051) and (5.35, 8.215)

Step 3: Find out the distance of each point from centroid.
D11 = ((1 - 1.568)2 + (3 - 4.051)2)0.5 = 1.2
D12 = ((1 - 5.35)2 + (3 - 8.215)2)0.5 = 6.79

Similarly, the distance of all other points is computed from both the centroids.
Step 4: Updating membership values.
For point 1 new membership values are:
Similarly, compute all other membership values, and update the matrix.
Step 5: Repeat the steps(2-4) until the constant values are obtained for the membership values or the difference is less than the tolerance value (a small value up to which the difference in values of two consequent updations is accepted).
Step 6: Defuzzify the obtained membership values. Implementation: The fuzzy scikit learn library has a pre-defined function for fuzzy c-means which can be used in Python. For using fuzzy c-means you need to install the skfuzzy library.
pip install sklearn
pip install skfuzzy
fuzzy-logic
Articles
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
lseek() in C/C++ to read the alternate nth byte and write it in another file

07 Feb, 2018
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”.lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.Function Definition
off_t lseek(int fildes, off_t offset, int whence);
Field Descriptionint fildes : The file descriptor of the pointer that is going to be movedoff_t offset : The offset of the pointer (measured in bytes).int whence : The method in which the offset is to be interpreted(rela, absolute, etc.). Legal value r this variable are provided at the end.return value : Returns the offset of the pointer (in bytes) from thebeginning of the file. If the return value is -1,then there was an error moving the pointer.
For example, say our Input file is as follows:
// C program to read nth byte of a file and// copy it to another file using lseek#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <fcntl.h>  void func(char arr[], int n){    // Open the file for READ only.    int f_write = open("start.txt", O_RDONLY);      // Open the file for WRITE and READ only.    int f_read = open("end.txt", O_WRONLY);      int count = 0;    while (read(f_write, arr, 1))    {        // to write the 1st byte of the input file in        // the output file        if (count < n)        {            // SEEK_CUR specifies that            // the offset provided is relative to the            // current file position            lseek (f_write, n, SEEK_CUR);            write (f_read, arr, 1);            count = n;        }          // After the nth byte (now taking the alternate        // nth byte)        else        {            count = (2*n);            lseek(f_write, count, SEEK_CUR);            write(f_read, arr, 1);        }    }    close(f_write);    close(f_read);}  // Driver codeint main(){    char arr[100];    int n;    n = 5;      // Calling for the function    func(arr, n);    return 0;}
Output file (end.txt)
This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-file-handling
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Nested Structure in Golang

13 Aug, 2019
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure. A structure which is the field of another structure is known as Nested Structure. Or in other words, a structure within another structure is known as a Nested Structure.
Syntax:
type struct_name_1 struct{
  // Fields
} 
type struct_name_2 struct{
  variable_name  struct_name_1

}

Let us discuss this concept with the help of the examples:
Example 1:
// Golang program to illustrate// the nested structurepackage main  import "fmt"  // Creating structuretype Author struct {    name   string    branch string    year   int}  // Creating nested structuretype HR struct {      // structure as a field    details Author}  func main() {      // Initializing the fields    // of the structure    result := HR{              details: Author{"Sona", "ECE", 2013},    }      // Display the values    fmt.Println("\nDetails of Author")    fmt.Println(result)}
Output:
Details of Author
{{Sona ECE 2013}}

Example 2:
// Golang program to illustrate// the nested structurepackage main  import "fmt"  // Creating structuretype Student struct {    name   string    branch string    year   int}  // Creating nested structuretype Teacher struct {    name    string    subject string    exp     int    details Student}  func main() {      // Initializing the fields    // of the structure    result := Teacher{        name:    "Suman",        subject: "Java",        exp:     5,        details: Student{"Bongo", "CSE", 2},    }      // Display the values    fmt.Println("Details of the Teacher")    fmt.Println("Teacher's name: ", result.name)    fmt.Println("Subject: ", result.subject)    fmt.Println("Experience: ", result.exp)      fmt.Println("\nDetails of Student")    fmt.Println("Student's name: ", result.details.name)    fmt.Println("Student's branch name: ", result.details.branch)    fmt.Println("Year: ", result.details.year)}
Output:
Details of the Teacher
Teacher's name:  Suman
Subject:  Java
Experience:  5

Details of Student
Student's name:  Bongo
Student's branch name:  CSE
Year:  2

Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
HTML5 | MathML <math> tag

19 Aug, 2021
The MathML <math> tag in HTML5 is the most prioritize element. Whatever MathML element you want to use they should wrapped inside of the <math> tag.Syntax:  
<math> child elements </math>
Attributes: The tag accepts some attributes which are listed below:  
class|id|style: This attribute is used to hold the styles of the child elements.
dir: This attributes holds the direction value. It holds two types of direction values ltr for left to right and rtl for right to left.
href: This attribute is used to hold any hyperlink to a specified URL.
mathbackground: This attribute holds the value of the math expressions background color.
mathcolor: This attribute holds the color of the math expressions.
display: This attribute holds the value of rendering of HTML element. There can be two value block which means that this element will be displayed outside the current span of text, inline which means that this element will be displayed inside the current span of text.
mode: Express the display attribute, possible values are display and inline.
overflow: It holds the value how the expression will behave. The default value is the linebreak and other possible values are scroll, elide, truncate, and scale.
Below example illustrates the MathML <math> tag in HTML5:Example:  
html
<!DOCTYPE html><html>  <head>    <title>HTML5 MathML math tag</title></head>  <body>    <center>        <h1 style="color:green">            GeeksforGeeks        </h1>                 <h3>HTML5 MathML <math> tag</h3>                 <math>            <mrow>                <mrow>                    <msup>                        <mi>x</mi>                        <mn>2</mn>                    </msup>                    <mo>+</mo>                    <msup>                        <mi>y</mi>                        <mn>2</mn>                    </msup>                </mrow>                <mo>=</mo>                <msup>                    <mi>z</mi>                    <mn>2</mn>                </msup>            </mrow>        </math>    </center></body>  </html>
Output:  
Supported Browsers: The browsers supported by HTML5 MathML <math> tag are listed below:  
Firefox
Safari
 
ysachin2314
HTML-MathML
HTML-Tags
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS checked Attribute

25 May, 2021
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component.
In this article, we will know how to use checked or defaultChecked attribute in checkbox input in React.js.
The checked attribute can be used with a checkbox or RadioButton element. 
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example 1: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';  // Defining our App Componentconst App = () => {    // Returning our JSX code  return <>    <div>      <h1>GeeksforGeeks</h1>        Input: <input type='checkbox' checked={true} />    </div>  </>;}  // Exporting your Default App Componentexport default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: 
Example 2: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';  // Defining our App Componentconst App = () => {    // Returning our JSX code  return <>    <div>      <h1>GeeksforGeeks</h1>        Input: <input type='radio' checked={true} />    </div>  </>;}  // Exporting your Default App Componentexport default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference:https://reactjs.org/docs/dom-elements.html#checked
ReactJS Attributes
ReactJS DOM Elements
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React