code-rag-bench/online-tutorials huggingface dataset:
Python | sympy.solve() method

12 Jun, 2019
With the help of sympy.solve(expression) method, we can solve the mathematical equations easily and it will return the roots of the equation that is provided as parameter using sympy.solve() method.
Syntax : sympy.solve(expression)Return : Return the roots of the equation.
Example #1 :In this example we can see that by using sympy.solve() method, we can solve the mathematical expressions and this will return the roots of that equation.
# import sympyfrom sympy import *  x, y = symbols('x y')gfg_exp = x**2 - 4  print("Before Integration : {}".format(gfg_exp))  # Use sympy.integrate() methodintr = solve(gfg_exp, x)  print("After Integration : {}".format(intr))
Output :
Before Integration : x**2 – 4
After Integration : [-2, 2]
 
Example #2 :
# import sympyfrom sympy import *   x, y = symbols('x y')gfg_exp = x**2 + 36  print("Before Integration : {}".format(gfg_exp))  # Use sympy.integrate() methodintr = solve(gfg_exp, x)  print("After Integration : {}".format(intr))
Output :
Before Integration : x**2 + 36
After Integration : [-6*I, 6*I]
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Password encryption in Node.js using bcryptjs module

18 Oct, 2021
While submitting a form, there are some sensitive data (like passwords) that must not be visible to anyone, not even to the database admin. To avoid the sensitive data being visible from anyone, Node.js uses “bcryptjs”.
This module enables storing of passwords as hashed passwords instead of plaintext.
Installation of bcryptjs module:
You can visit the link to Install bcryptjs module. You can install this package by using this command.
npm install bcryptjs
After installing bcryptjs module you can check your request version in the command prompt using the command.
npm version bcryptjs
After that, you can 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
index.js
// Requiring moduleconst bcrypt = require('bcryptjs');  const password = 'pass123';var hashedPassword;  // Encryption of the string passwordbcrypt.genSalt(10, function (err, Salt) {      // The bcrypt is used for encrypting password.    bcrypt.hash(password, Salt, function (err, hash) {          if (err) {            return console.log('Cannot encrypt');        }          hashedPassword = hash;        console.log(hash);          bcrypt.compare(password, hashedPassword,             async function (err, isMatch) {              // Comparing the original password to            // encrypted password               if (isMatch) {                console.log('Encrypted password is: ', password);                console.log('Decrypted password is: ', hashedPassword);            }              if (!isMatch) {                              // If password doesn't match the following                // message will be sent                console.log(hashedPassword + ' is not encryption of '                 + password);            }        })    })})
Step to run the application: Run the application using the following command:
node index.js
Output: We will see the following output on the console screen.
$2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGmEncrypted password is: pass123Decrypted password is: $2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Wfuzz Download – Web Application Password Cracker in Kali Linux

14 Sep, 2021
Brute-Forcing is the technique to discover the hidden directories and files on the target server. We can even brute-force usernames and passwords. All this process is done through an automated tool. Quickly Request-Response methodology is executed on the domain. Wfuzz tool is an automated tool used to perform all types of brute-forcing on the target domain. Wfuzz tool is developed in the Python Language. Wfuzz tool is available on the GitHub platform, it’s free and open-source to use. We can specify our mode of request and change the User-Agent values to stay anonymous on the target domain.
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/xmendez/wfuzz.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 wfuzz
Step 3: You are in the directory of the Wfuzz. Now you have to install a dependency of the Wfuzz using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
wfuzz -h
Example 1: Simple Directory Scan on geeksforgeeks.org
wfuzz -c -z file,wordlist/general/big.txt –hc 404 http://geeksforgeeks.org/FUZZ
Example 2: Printing Wfuzz version details
wfuzz --version
Example 3:  Verbose Information/ More Detailed Output
 wfuzz -v -z file,wordlist/general/big.txt –hc 404,301 http://geeksforgeeks.org/FUZZ
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
Compiling with g++
'crontab' in Linux with Examples
UDP Server-Client implementation in C
touch command in Linux with Examples
nohup Command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
Conditional Statements | Shell Script
Python | Difference of two lists including duplicates

13 May, 2019
The ways to find difference of two lists has been discussed earlier, but sometimes, we require to remove only the specific occurrences of the elements as much they occur in other list. Let’s discuss certain ways in which this can be performed.
Method #1 : Using collections.Counter()The Counter method can be used to get the exact occurrence of the elements in the list and hence can subtract selectively rather than using the set and ignoring the count of elements altogether. Then the subtraction can be performed to get the actual occurrence.
# Python3 code to demonstrate# Difference of list including duplicates# Using collections.Counter()from collections import Counter  # initializing liststest_list1 = [1, 3, 4, 5, 1, 3, 3]test_list2 = [1, 3, 5]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # Using collections.Counter()# Difference of list including duplicatesres = list((Counter(test_list1) - Counter(test_list2)).elements())  # print resultprint("The list after performing the subtraction : " + str(res))
The original list 1 : [1, 3, 4, 5, 1, 3, 3]
The original list 2 : [1, 3, 5]
The list after performing the subtraction : [1, 3, 3, 4]

 
Method #2 : Using map() + lambda + remove()The combination of above functions can be used to perform this particular task. The map function can be used to link the function to all elements and remove removes the first occurrence of it. Hence doesn’t remove repeatedly. Works with Python2 only.
# Python code to demonstrate# Difference of list including duplicates# Using map() + lambda + remove()  # initializing liststest_list1 = [1, 3, 4, 5, 1, 3, 3]test_list2 = [1, 3, 5]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # Using map() + lambda + remove()# Difference of list including duplicatesres = map(lambda x: test_list1.remove(x)           if x in test_list1 else None, test_list2)  # print resultprint("The list after performing the subtraction : " + str(test_list1))
The original list 1 : [1, 3, 4, 5, 1, 3, 3]
The original list 2 : [1, 3, 5]
The list after performing the subtraction : [1, 3, 3, 4]

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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python | Extract only characters from given string

03 Apr, 2019
Given a string, the task is to extract only alphabetical characters from a string. Given below are few methods to solve the given problem.
Method #1: Using re.split
# Python code to demonstrate# to get characters from stringimport re  # initialising stringini_string = "123()#$ABGFDabcjw"ini_string2 = "abceddfgh"  # printing stringsprint ("initial string : ", ini_string, ini_string2)  # code to find characters in stringres1 = " ".join(re.split("[^a-zA-Z]*", ini_string))res2 = " ".join(re.split("[^a-zA-Z]*", ini_string2))  # printing resultant stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2))
Output:
initial string :  123()#$ABGFDabcjw abceddfgh
first string result:   ABGFDabcjw
second string result:  abceddfgh
 Method #2: Using re.fidall
# Python code to demonstrate# to get characters in stringimport re  # initialising stringini_string = "123()#$ABGFDabcjw"ini_string2 = "abceddfgh"  # printing stringsprint ("initial string : \n", ini_string, "\n", ini_string2)  # code to find characters in stringres1 = " ".join(re.findall("[a-zA-Z]+", ini_string))res2 = " ".join(re.findall("[a-zA-Z]+", ini_string2))  # printing resultant stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2))
Output:
initial string : 
 123()#$ABGFDabcjw 
 abceddfgh

first string result:  ABGFDabcjw
second string result:  abceddfgh
 Method #3: Using isalpha()
# Python code to demonstrate# to get characters in a string# if present  # initialising stringini_string = "123()#$ABGFDabcjw"  # printing string and its lengthprint ("initial string : ", ini_string)  # code to find characters in stringres1 = ""for i in ini_string:    if i.isalpha():        res1 = "".join([res1, i])    # printing resultant stringprint ("first result: ", str(res1))
Output:
initial string :  123()#$ABGFDabcjw
first result:  ABGFDabcjw

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Split string into list of characters
jQuery - Interaction Drag-able

The Drag-able function can be used with interactions in JqueryUI.This function can enable drag-able functionality on any DOM element.We can drag the drag-able element by clicking on it with mouse.
Here is the simple syntax to use drag-able −
 $( "#draggable" ).draggable();

Following is a simple example showing the usage of drag-able −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
   
         $(function() {
            $( "#draggable" ).draggable();
         });
		 
      </script>
		
      <style>
         #draggable { width: 150px; height: 150px; padding: 0.5em; }
         .back{
            background-color: lightgrey;
            width: 50px;
            padding: 25px;
            border: 25px solid navy;
            margin: 25px;
         }
      </style>
   </head>
	
   <body>
      <div id = "draggable" class = "ui-widget-content">
         <p class = "back">Drag</p>
      </div>
	 
   </body>
</html>
This will produce following result −
Drag

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
HBase - Listing Table

list is the command that is used to list all the tables in HBase. Given below is the syntax of the list command.
hbase(main):001:0 > list

When you type this command and execute in HBase prompt, it will display the list of all the tables in HBase as shown below.
hbase(main):001:0> list
TABLE
emp

Here you can observe a table named emp.
Follow the steps given below to get the list of tables from HBase using java API.
You have a method called listTables() in the class HBaseAdmin to get the list of all the tables in HBase. This method returns an array of HTableDescriptor objects.
//creating a configuration object
Configuration conf = HBaseConfiguration.create();

//Creating HBaseAdmin object
HBaseAdmin admin = new HBaseAdmin(conf);

//Getting all the list of tables using HBaseAdmin object
HTableDescriptor[] tableDescriptor = admin.listTables();

You can get the length of the HTableDescriptor[] array using the length variable of the HTableDescriptor class. Get the name of the tables from this object using getNameAsString() method. Run the ‘for’ loop using these and get the list of the tables in HBase.
Given below is the program to list all the tables in HBase using Java API.
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.client.HBaseAdmin;

public class ListTables {

   public static void main(String args[])throws MasterNotRunningException, IOException{

      // Instantiating a configuration class
      Configuration conf = HBaseConfiguration.create();

      // Instantiating HBaseAdmin class
      HBaseAdmin admin = new HBaseAdmin(conf);

      // Getting all the list of tables using HBaseAdmin object
      HTableDescriptor[] tableDescriptor = admin.listTables();

      // printing all the table names.
      for (int i=0; i<tableDescriptor.length;i++ ){
         System.out.println(tableDescriptor[i].getNameAsString());
      }
   
   }
}
Compile and execute the above program as shown below.
$javac ListTables.java
$java ListTables

The following should be the output:
User
emp

 Print
 Add Notes
 Bookmark this page
GATE | GATE CS 2018 | Question 9 - GeeksforGeeks

22 Feb, 2018
If pqr ≠ 0 and , what is the value of the product xyz ?
(A) -1(B) 1 / pqr(C) 1(D) pqrAnswer: (C)Explanation: Taking logs of given three values,we get
1/q = p-x -------(1)
1/r = q-y -------(2)
1/p = r-z -------(3)

1/q = p-x
    = r-xz [Putting value of p from (3)]
    = q-xyz  [Putting value of r from (2)]
    = 1 / qxyz

On comparing power of q both sides, we get xyz = 1
So, option (C) is correct.
Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
Python Creating Blockchain

A blockchain contains a list of blocks chained to each other. To store the entire list, we will create a list variable called TPCoins −
TPCoins = []

We will also write a utility method called dump_blockchain for dumping the contents of the entire blockchain. We first print the length of the blockchain so that we know how many blocks are currently present in the blockchain.
def dump_blockchain (self):
   print ("Number of blocks in the chain: " + str(len (self)))

Note that as the time passes, the number of blocks in the blockchain would be extraordinarily high for printing. Thus, when you print the contents of the blockchain you may have to decide on the range that you would like to examine. In the code below, we have printed the entire blockchain as we would not be adding too many blocks in the current demo.
To iterate through the chain, we set up a for loop as follows −
for x in range (len(TPCoins)):
   block_temp = TPCoins[x] 

Each referenced block is copied to a temporary variable called block_temp.
We print the block number as a heading for each block. Note that the numbers would start with zero, the first block is a genesis block that is numbered zero.
print ("block # " + str(x))

Within each block, we have stored a list of three transactions (except for the genesis block) in a variable called verified_transactions. We iterate this list in a for loop and for each retrieved item, we call display_transaction function to display the transaction details.
for transaction in block_temp.verified_transactions:
   display_transaction (transaction)

The entire function definition is shown below −
def dump_blockchain (self):
   print ("Number of blocks in the chain: " + str(len (self)))
   for x in range (len(TPCoins)):
      block_temp = TPCoins[x]
      print ("block # " + str(x))
      for transaction in block_temp.verified_transactions:
         display_transaction (transaction)
         print ('--------------')
      print ('=====================================')

Note that here we have inserted the separators at appropriate points in the code to demarcate the blocks and transactions within it.
As we have now created a blockchain for storing blocks, our next task is to create blocks and start adding it to the blockchain. For this purpose, we will add a genesis block that you have already created in the earlier step.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to implement Dependency Injection using Property in C#?

The process of injecting (converting) coupled (dependent) objects into decoupled (independent) objects is called Dependency Injection.
Types of Dependency Injection
There are four types of DI −
Constructor Injection
Constructor Injection
Setter Injection
Setter Injection
Interface-based injection
Interface-based injection
Service Locator Injection
Service Locator Injection
Getter and Setter Injection injects the dependency by using default public properties procedure such as Gettter(get(){}) and Setter(set(){}). 
public interface IService{
   string ServiceMethod();
}
public class ClaimService:IService{
   public string ServiceMethod(){
      return "ClaimService is running";
   }
}
public class AdjudicationService:IService{
   public string ServiceMethod(){
      return "AdjudicationService is running";
   }
}
public class BusinessLogicImplementation{
   private IService _client;
   public IService Client{
      get { return _client; }
      set { _client = value; }
   }
   public void SetterInj(){
      Console.WriteLine("Getter and Setter Injection ==>
      Current Service : {0}", Client.ServiceMethod());
   }
}
BusinessLogicImplementation ConInjBusinessLogic = new BusinessLogicImplementation();
ConInjBusinessLogic.Client = new ClaimService();
ConInjBusinessLogic.SetterInj();
Python | Pandas Series.loc - GeeksforGeeks

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.loc attribute is used to access a group of rows and columns by label(s) or a boolean array in the given Series object.
Syntax:Series.loc
Parameter : None
Returns : series
Example #1: Use Series.loc attribute to select some values from the given Series object based on the labels.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4']   # Print the seriesprint(sr)
Output :
Now we will use Series.loc attribute to return the values of the selected labels in the given Series object.
# return the selected values.sr.loc[['City 4', 'City 3', 'City 1']]
Output :
As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it. Example #2 : Use Series.loc attribute to select some values from the given Series object based on the labels.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.loc attribute to return the values of the selected labels in the given Series object.
# return the selected values.sr.loc[['Day 4', 'Day 3', 'Day 1']]
Output :As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it.
Python pandas-series
Python pandas-series-methods
Python-pandas
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
Java program to add two integers

The + operator in Java is used to multiply two numbers. Read required numbers from the user using Scanner class and add these two integers using the + operator.
import java.util.Scanner;
public class AddinTwoNumbers {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of the first number ::");
      int a = sc.nextInt();
      System.out.println("Enter the value of the first number ::");
      int b = sc.nextInt();
      int result = a+b;
      System.out.println("Sum of the given two numbers is ::"+result);
   }
}
Enter the value of the first number ::
5564
Enter the value of the first number ::
2234
Sum of the given two numbers is ::7798
How to write a conditional expression in lambda expression in Java?

The conditional operator is used to make conditional expressions in Java. It is also called a Ternary operator because it has three operands such as boolean condition, first expression, and second expression.
We can also write a conditional expression in lambda expression in the below program.
interface Algebra {
   int substraction(int a, int b);
}
public class ConditionalExpressionLambdaTest {
   public static void main(String args[]) {
      System.out.println("The value is: " + getAlgebra(false).substraction(20, 40));
      System.out.println("The value is: " + getAlgebra(true).substraction(40, 10));
   }
   static Algebra getAlgebra(boolean reverse) {
      Algebra alg = reverse ? (a, b) -> a - b : (a, b) -> b - a; // conditional expression 
      return alg;
   }
}
The value is: 20
The value is: 30
MongoDB query to remove subdocument from document?

To remove subdocument from a document, use $pull along with update(). Let us first create a collection with documents −
> db.demo538.insertOne(
... {
...    id:101,
...    "details":
...    {
...       anotherDetails:
...       [
...          {
...             "Name":"Chris",
...             Age:21
...          },
...          {
...             "Name":"David",
...             Age:23
...          },
...          {
...             "Name":"Bob",
...             Age:20
...          }
...       ]
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c8f0aef4dcbee04fbbc08")
}
Display all documents from a collection with the help of find() method −
> db.demo538.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [
   { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ]
} }
Following is the query to remove subdocument from a document −
> db.demo538.update({ id:101},
... {$pull : { "details.anotherDetails" : {"Age":23} } } )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo538.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ {
"Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 } ] } }
Binary Search a String in C++

In Binary search a string, we are given a sorted array of strings and we have to search for a string in the array of strings using binary search algorithm.
Input : stringArray = {“I”, “Love”, “Programming”, “tutorials”, “point”}.
Element = “programming”
Output : string found at index 3
Explanation : The index of string is 3.
Input : stringArray = {“I”, “Love”, “Programming”, “tutorials”, “point”}.
Element = “coding”
Output : -1 ‘string not found’
Binary search is searching technique that works by finding the middle of the array for finding the element.
For array of strings also the binary search algorithm will remain the same. But the comparisons that are made will be based on string comparison. String comparison check for the first character of the strings and compare it. characters are same then it goes to the next and so on.
arrString : array of sorted strings
Lower = 0 ; upper = n (length of array)
Element = string that is to be found
Step 1 : while element is not found. Do :
Step 2 : mid = lower + (upper - lower) / 2 ;
Step 3 : if arrString[mid] = element , return mid and exit
Step 4 : if arrString[mid] < element, lower = mid+1
Step 5 : if arrString[mid] > element, upper = mid-1
Step 6 : upper < lower , return -1, exit.
#include<bits/stdc++.h>
using namespace std;
int binarySearchString(string arr[], string x, int n) {
   int lower = 0;
   int upper = n - 1;
   while (lower <= upper) {
      int mid = lower + (upper - lower) / 2;
      int res;
      if (x == (arr[mid]))
         res = 0;
      if (res == 0)
         return mid;
      if (x > (arr[mid]))
         lower = mid + 1;
      else
         upper = mid - 1;
   }
   return -1;
}
int main () {
   string arr[] = {"I", "Love", "Programming" , "tutorials" , "point"};
   string x = "Programming";
   int n = 4;
   int result = binarySearchString(arr, x, n);
   if(result == -1)
      cout<<("Element not present");
   else
      cout<<("Element found at index ")<<result;
}
Element found at index 2
Program to implement the fractional knapsack problem in Python

Suppose we have two lists, weights and values of same length and another value capacity. The weights[i] and values[i] represent the weight and value of ith element. So if we can take at most capacity weights, and that we can take a fraction of an item's weight with proportionate value, we have to find the maximum amount of value we can get (rounded down to the nearest integer)
So, if the input is like weights = [6, 7, 3] values = [110, 120, 2] capacity = 10, then the output will be 178.
To solve this, we will follow these steps −
res := 0make a list of pairs P with weights and values, and sort them based on values per weightfor each pair in P, docif capacity is 0, thencome out from the loopif pair[0] > capacity, thenres := res + quotient of (pair[1] /(pair[0] / capacity)capacity := 0otherwise when pair[0] <= capacity, thenres := res + pair[1]capacity := capacity - pair[0]return floor value of res
res := 0
make a list of pairs P with weights and values, and sort them based on values per weight
make a list of pairs P with weights and values, and sort them based on values per weight
for each pair in P, docif capacity is 0, thencome out from the loopif pair[0] > capacity, thenres := res + quotient of (pair[1] /(pair[0] / capacity)capacity := 0otherwise when pair[0] <= capacity, thenres := res + pair[1]capacity := capacity - pair[0]
for each pair in P, do
cif capacity is 0, thencome out from the loop
come out from the loop
come out from the loop
if pair[0] > capacity, thenres := res + quotient of (pair[1] /(pair[0] / capacity)capacity := 0
if pair[0] > capacity, then
res := res + quotient of (pair[1] /(pair[0] / capacity)
res := res + quotient of (pair[1] /(pair[0] / capacity)
capacity := 0
capacity := 0
otherwise when pair[0] <= capacity, thenres := res + pair[1]capacity := capacity - pair[0]
otherwise when pair[0] <= capacity, then
res := res + pair[1]
res := res + pair[1]
capacity := capacity - pair[0]
capacity := capacity - pair[0]
return floor value of res
return floor value of res
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, weights, values, capacity):
      res = 0
      for pair in sorted(zip(weights, values), key=lambda x: - x[1]/x[0]):
         if not bool(capacity):
            break
         if pair[0] > capacity:
            res += int(pair[1] / (pair[0] / capacity))
            capacity = 0
         elif pair[0] <= capacity:
            res += pair[1]
            capacity -= pair[0]
      return int(res)

ob = Solution()
weights = [6, 7, 3]
values = [110, 120, 2]
capacity = 10
print(ob.solve(weights, values, capacity))
[6, 7, 3],[110, 120, 2],10
230
Multithreading in C++

Multithreading is a specialized form of multitasking and a multitasking is the feature
that allows your computer to run two or more programs concurrently. In general,
there are two types of multitasking: process-based and thread-based.
Process-based multitasking handles the concurrent execution of programs. Threadbased
multitasking deals with the concurrent execution of pieces of the same
program.
A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread, and each thread defines a separate
path of execution.
C++ does not contain any built-in support for multithreaded applications. Instead, it
relies entirely upon the operating system to provide this feature.
This tutorial assumes that you are working on Linux OS and we are going to write
multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API
which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD,
GNU/Linux, Mac OS X and Solaris.
The following routine is used to create a POSIX thread −
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
Here, pthread_create creates a new thread and makes it executable. This routine
can be called any number of times from anywhere within your code. Here is the
description of the parameters.
The maximum number of threads that may be created by a process is
implementation dependent. Once created, threads are peers, and may create other
threads. There is no implied hierarchy or dependency between threads.
There is following routine which we use to terminate a POSIX thread –
#include <pthread.h>
pthread_exit (status)
Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit()
routine is called after a thread has completed its work and is no longer required to
exist.
If main() finishes before the threads it has created, and exits with pthread_exit(), the
other threads will continue to execute. Otherwise, they will be automatically
terminated when main() finishes.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}
int main () {
   pthread_t threads[NUM_THREADS];
   int rc;
   int i;
   for( i = 0; i < NUM_THREADS; i++ ) {
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}
$gcc test.cpp -lpthread
$./a.out
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4
Go - The goto Statement

A goto statement in Go programming language provides an unconditional jump from the goto to a labeled statement in the same function.
Note − Use of goto statement is highly discouraged in any programming language because it becomes difficult to trace the control flow of a program, making the program difficult to understand and hard to modify. Any program that uses a goto can be rewritten using some other construct.
The syntax for a goto statement in Go is as follows −
goto label;
..
.
label: statement;

Here, label can be any plain text except Go keyword and it can be set anywhere in the Go program above or below to goto statement.
package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 10

   /* do loop execution */
   LOOP: for a < 20 {
      if a == 15 {
         /* skip the iteration */
         a = a + 1
         goto LOOP
      }
      fmt.Printf("value of a: %d\n", a)
      a++     
   }  
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
JavaScript DOM Elements

This page teaches you how to find and access HTML elements in 
an HTML page.
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are several ways to do this:
Finding HTML elements by id
Finding HTML elements by tag name 
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Finding HTML elements by HTML object collections
The easiest way to find an HTML element in the DOM, is by using the element id.
This example finds the element with id="intro":
If the element is found, the method will return the element as an object (in element).
If the element is not found, element will contain null.
This example finds all <p> elements:
This example finds the element with id="main", and then finds all <p> elements 
inside "main":
If you want to find all HTML elements with the same class name, use 
getElementsByClassName().

This example returns a list of all elements with class="intro".
If you want to find all HTML elements that match a specified CSS selector 
(id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".
This example finds the form element with id="frm1", in the forms 
collection, and displays all element 
values:
The following HTML objects (and object collections) are also accessible:
document.anchors
document.body
document.documentElement
document.embeds
document.forms
document.head
document.images
document.links
document.scripts
document.title
Use the getElementById method to find the 
<p> element, and change its text to "Hello".
<p id="demo"></p>

<script>
 = "Hello";
</script>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Python | Pandas Series.sort_index() - GeeksforGeeks

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.sort_index() function is used to sort the index labels of the given series object.
Syntax: Series.sort_index(axis=0, level=None, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, sort_remaining=True)
Parameter :axis : Axis to direct sorting. This can only be 0 for Series.level : If not None, sort on values in specified index level(s).ascending : Sort ascending vs. descending.inplace : If True, perform operation in-place.kind : Choice of sorting algorithm.na_position : Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.sort_remaining : If true and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified level.
Returns : Series
Example #1: Use Series.sort_index() function to sort the index labels of the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Indexindex_ = ['City 5', 'City 6', 'City 4', 'City 2', 'City 3', 'City 1']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.sort_index() function to sort the index labels of the given series object.
# sort the index labelssr.sort_index()
Output :
As we can see in the output, the Series.sort_index() function has successfully sorted the index labels of the given series object. Example #2: Use Series.sort_index() function to sort the index labels of the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])  # Create the Indexindex_ = [5, 3, 2, 1, 4]  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.sort_index() function to sort the index labels of the given series object.
# sort the index labelssr.sort_index()
Output :
As we can see in the output, the Series.sort_index() function has successfully sorted the index labels of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
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()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to join points on a scatterplot with smooth lines in R using plot function?

It is very difficult to join points on a scatterplot with smooth lines if the scatteredness is high but we might want to look at the smoothness that cannot be understood by just looking at the points. It is also helpful to understand whether the model is linear or not. We can do this by plotting the model with loess using plot function.
Consider the below data −
> set.seed(3)
> x<-sample(1:100,10,replace=TRUE)
> y<-rpois(10,100)
Using loess to create the smooth lines −
> Model <- loess(y~x)
> summary(Model)
Call:
loess(formula = y ~ x)
Number of Observations: 10
Equivalent Number of Parameters: 4.77
Residual Standard Error: 8.608
Trace of smoother matrix: 5.27 (exact)
Control settings:
span       : 0.75
degree     : 2
family     : gaussian
surface    : interpolate cell = 0.2
normalize  : TRUE
parametric : FALSE
drop.square: FALSE
> plot(x,y)
> lines(Model, col='red', lwd=2)
Python Pandas - Return numpy array of python datetime.time objects

To return numpy array of python datetime.time objects, use the datetimeindex.time property in Pandas.
At first, import the required libraries −
import pandas as pd
Create a DatetimeIndex with period 3 and frequency as us i.e. nanoseconds. The timezone is Australia/Sydney −
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')

Display DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
Returns only the time part of Timestamps without timezone information −
print("\nThe numpy array (time part)..\n",datetimeindex.time)

Following is the code −
import pandas as pd

# DatetimeIndex with period 3 and frequency as us i.e. nanoseconds
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# Returns only the date part of Timestamps without timezone information
print("\nThe numpy array (date part)..\n",datetimeindex.date)

# Returns only the time part of Timestamps without timezone information
print("\nThe numpy array (time part)..\n",datetimeindex.time)
This will produce the following code −
DateTimeIndex...
DatetimeIndex([ '2021-10-20 02:30:50+11:00',
'2021-10-20 02:30:50.000000001+11:00',
'2021-10-20 02:30:50.000000002+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='N')

The numpy array (date part)..
[datetime.date(2021, 10, 20) datetime.date(2021, 10, 20)
datetime.date(2021, 10, 20)]

The numpy array (time part)..
[datetime.time(2, 30, 50) datetime.time(2, 30, 50)
datetime.time(2, 30, 50)]
How and where does String literals in Java stored in the memory?

Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.
You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).
public class StringDemo {
   public static void main(String args[]) {
      String stringObject = new String("Hello how are you");
      System.out.println(stringObject);
      String stringLiteral = "Welcome to Tutorialspoint";
      System.out.println(stringLiteral);
   }
}
Hello how are you
Welcome to Tutorialspoint
Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held.
When you store a String as
String str1 = "Hello";
directly, then JVM creates a String object with the given value in a String constant pool.
And whenever we try to create another String as
String str2 = "Hello";
JVM verifies weather any String object with the same value exists in the String constant pool, if so, instead of creating a new object JVM assigns the reference of existing object to the new variable.
And when we store String as
String str = new String("Hello");
using the new keyword, a new object with the given value is created irrespective of the contents of the String constant pool.
F# - Program Structure

F# is a Functional Programming language.
In F#, functions work like data types. You can declare and use a function in the same way like any other variable.
In general, an F# application does not have any specific entry point. The compiler executes all top-level statements in the file from top to bottom.
However, to follow procedural programming style, many applications keep a single top level statement that calls the main loop.
The following code shows a simple F# program −
open System
(* This is a multi-line comment *)
// This is a single-line comment

let sign num =
   if num > 0 then "positive"
   elif num < 0 then "negative"
   else "zero"

let main() =
   Console.WriteLine("sign 5: {0}", (sign 5))

main()
When you compile and execute the program, it yields the following output −
sign 5: positive

Please note that −
An F# code file might begin with a number of open statements that is used to import namespaces.
An F# code file might begin with a number of open statements that is used to import namespaces.
The body of the files includes other functions that implement the business logic of the application.
The body of the files includes other functions that implement the business logic of the application.
The main loop contains the top executable statements.
The main loop contains the top executable statements.
 Print
 Add Notes
 Bookmark this page
Math.Ceiling() Method in C#

The Math.Ceiling() method in C# is used to return the smallest integral value greater than or equal to the specified number.
Following is the syntax −
public static decimal Ceiling (decimal val);
public static double Ceiling(double val)
For the first syntax above, the value Val is the decimal number, whereas Val in the second syntax is the double number.
Let us now see an example to implement Math.Ceiling() method −
using System;
public class Demo {
   public static void Main(){
      decimal val1 = 9.99M;
      decimal val2 = -5.10M;
      Console.WriteLine("Result = " + Math.Ceiling(val1));
      Console.WriteLine("Result = " + Math.Ceiling(val2));
   }
}
This will produce the following output −
Result = 10
Result = -5
Let us see another example to implement Math.Ceiling() method −
using System;
public class Demo {
   public static void Main(){
      double val1 = 3.1;
      double val2 = 55.99;
      double val3 = -55.99;
      Console.WriteLine("Result = " + Math.Ceiling(val1));
      Console.WriteLine("Result = " + Math.Ceiling(val2));
      Console.WriteLine("Result = " + Math.Ceiling(val3));
   }
}
This will produce the following output −
Result = 4
Result = 56
Result = -55
How to insert a row into a table that has only a single autoincrement column?

You can easily insert a row into a table that has only a single auto increment column. The syntax is as follows −
insert into yourTableName set yourColumnName =NULL;
You can use the below syntax −
insert into yourTableName values(NULL);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table singleAutoIncrementColumnDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into singleAutoIncrementColumnDemo set UserId =NULL;
Query OK, 1 row affected (0.18 sec)
mysql> insert into singleAutoIncrementColumnDemo values(NULL);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from singleAutoIncrementColumnDemo;
Here is the output −
+--------+
| UserId |
+--------+
| 1      |
| 2      |
+--------+
2 rows in set (0.00 sec)