code-rag-bench/online-tutorials huggingface dataset:
Python | Find dictionary matching value in list - GeeksforGeeks

02 Aug, 2019
The problem of getting only the suitable dictionary that has a particular value of the corresponding key is quite common when one starts working with dictionary. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is the brute force method by which this task can be performed. For this, we just use naive check and compare and return the result once we find the suitable match and break for rest of dictionaries.
# Python3 code to demonstrate working of# Find dictionary matching value in list# Using loop  # Initialize listtest_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},              {'it' : 5, 'is' : 7, 'best' : 8},             {'CS' : 10}]  # Printing original listprint("The original list is : " + str(test_list))  # Using loop# Find dictionary matching value in listres = Nonefor sub in test_list:    if sub['is'] == 7:        res = sub        break  # printing result print("The filtered dictionary value is : " + str(res))
The original list is : [{'is': 4, 'gfg': 2, 'best': 6}, {'is': 7, 'best': 8, 'it': 5}, {'CS': 10}]
The filtered dictionary value is : {'is': 7, 'best': 8, 'it': 5}

 
Method #2 : Using next() + dictionary comprehensionThe combination of these methods can also be used to perform this task. This difference is that it’s a one liner and more efficient as next function uses iterator as internal implementation which are quicker than generic methods.
# Python3 code to demonstrate working of# Find dictionary matching value in list# Using next() + dictionary comprehension  # Initialize listtest_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},              {'it' : 5, 'is' : 7, 'best' : 8},             {'CS' : 10}]  # Printing original listprint("The original list is : " + str(test_list))  # Using next() + dictionary comprehension# Find dictionary matching value in listres = next((sub for sub in test_list if sub['is'] == 7), None)  # printing result print("The filtered dictionary value is : " + str(res))
The original list is : [{'is': 4, 'gfg': 2, 'best': 6}, {'is': 7, 'best': 8, 'it': 5}, {'CS': 10}]
The filtered dictionary value is : {'is': 7, 'best': 8, 'it': 5}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
K-th Symbol in Grammar in C++

Suppose on the first row, we have a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 by 01, and each occurrence of 1 by 10. Suppose we have N rows and index K, we have to find the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). So if N = 4 and K = 5, then the output will be 1. This is because −
Row 1: 0
Row 2: 01
Row 3: 0110
Row 4: 01101001
To solve this, we will follow these steps −
Suppose the name of the method is kthGrammar. This takes N and K.
if N is 1, then return 0
if k is even, return 1 when then kthGrammar(N – 1, K/2) is 0, otherwise 0
otherwise return kthGrammar(N – 1, (K + 1)/2)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int kthGrammar(int N, int K) {
      if(N == 1) return 0;
      if(K % 2 == 0){
      return kthGrammar(N - 1, K / 2) == 0 ? 1 : 0;
      }else{
         return kthGrammar(N - 1, (K + 1) / 2);
      }
   }
};
main(){
   Solution ob;
   cout << (ob.kthGrammar(4, 5));
}
4
5
1
How to solve an IllegalArgumentException in Java?


An IllegalArgumentException is thrown in order to indicate that a method has been passed an illegal argument. This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.
When Arguments out of range. For example, the percentage should lie between 1 to 100. If the user entered 101 then an IllegalArugmentExcpetion will be thrown.
When argument format is invalid. For example, if our method requires date format like YYYY/MM/DD but if the user is passing YYYY-MM-DD. Then our method can’t understand then IllegalArugmentExcpetion will be thrown.
When a method needs non-empty string as a parameter but the null string is passed.
public class Student {
   int m;
   public void setMarks(int marks) {
      if(marks < 0 || marks > 100)
         throw new IllegalArgumentException(Integer.toString(marks));
      else
         m = marks;
   }
   public static void main(String[] args) {
      Student s1 = new Student();
      s1.setMarks(45);
      System.out.println(s1.m);
      Student s2 = new Student();
      s2.setMarks(101);
      System.out.println(s2.m);
   }
}
45
Exception in thread "main" java.lang.IllegalArgumentException: 101
at Student.setMarks(Student.java:5)
at Student.main(Student.java:15)
When an IllegalArgumentException is thrown, we must check the call stack in Java’s stack trace and locate the method that produced the wrong argument.
The IllegalArgumentException is very useful and can be used to avoid situations where the application’s code would have to deal with unchecked input data.
The main use of this IllegalArgumentException is for validating the inputs coming from other users.
If we want to catch the IllegalArgumentException then we can use try-catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping.
import java.util.Scanner;
public class Student {
    public static void main(String[] args) {
        String cont = "y";
        run(cont);
    }
    static void run(String cont) {
        Scanner scan = new Scanner(System.in);
        while( cont.equalsIgnoreCase("y")) {
           try {
               System.out.println("Enter an integer: ");
               int marks = scan.nextInt();
               if (marks < 0 || marks > 100)
                  throw new IllegalArgumentException("value must be non-negative and below 100");
               System.out.println( marks);
            }
            catch(IllegalArgumentException i) {
               System.out.println("out of range encouneterd. Want to continue");
               cont = scan.next();  
               if(cont.equalsIgnoreCase("Y"))
                   run(cont);
               }
          }
     }
}
Enter an integer:
1
1
Enter an integer:
100
100
Enter an integer:
150
out of range encouneterd. Want to continue
y
Enter an integer:
JSF - f:attribute

The h:attribute tag provides option to pass a attribute value to a component, or a parameter to a component via action listener.
<h:commandButton id = "submit" 
   actionListener = "#{userData.attributeListener}" action = "result"> 
   <f:attribute name = "value" value = "Show Message" />				
   <f:attribute name = "username" value = "JSF 2.0 User" />
</h:commandButton>
name
The name of the attribute to set
value
The value of the attribute
Let us create a test JSF application to test the above tag.
package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;
   public String data = "1";

   public String getData() {
      return data;
   }

   public void setData(String data) {
      this.data = data;
   }

   public void attributeListener(ActionEvent event) {
      data = (String)event.getComponent().getAttributes().get("username");	
   }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns = "http://www.w3.org/1999/xhtml"> 
   <head> 
      <title>JSF Tutorial!</title> 
   </head> 
   
   <body> 
      <h2>f:attribute example</h2> 
      <hr /> 
      
      <h:form> 
         <h:commandButton id = "submit"  
            actionListener = "#{userData.attributeListener}" action = "result">  
            <f:attribute name = "value" value = "Show Message" /> 
            <f:attribute name = "username" value = "JSF 2.0 User" /> 
         </h:commandButton> 
      </h:form> 
   
   </body> 
</html> 
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:f = "http://java.sun.com/jsf/core"    
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:ui = "http://java.sun.com/jsf/facelets">
   
   <head>
      <title>JSF Tutorial!</title>
   </head>
   
   <h:body>
      <h2>Result</h2>
      <hr />
      #{userData.data}
   </h:body>
</html>  
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Press Show Message button and you'll see the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
Difference between pointer and array in C

The details about a pointer and array that showcase their difference are given as follows.
A pointer is a variable that stores the address of another variable. When memory is allocated to a variable, pointer points to the memory address of the variable. Unary operator ( * ) is used to declare a pointer variable.
The following is the syntax of pointer declaration.
datatype *variable_name;
Here, the datatype is the data type of the variable like int, char, float etc. and variable_name is the name of variable given by user.
A program that demonstrates pointers is given as follows.
 Live Demo
#include <stdio.h>
int main () {
   int a = 8;
   int *ptr;
   ptr = &a;
   printf("Value of variable a: %d\n", a);
   printf("Address of variable a: %d\n", ptr);
   return 0;
}
The output of the above program is as follows.
Value of variable a: 8
Address of variable a: -2018153420
An array is a collection of the same type of elements at contiguous memory locations. The lowest address in an array corresponds to the first element while highest address corresponds to the last element. Array index starts with zero(0) and ends with the size of array minus one(array size - 1).
The following is the syntax of array.
type array_name[array_size ];
Here, array_name is the name given to an array and array_size is the size of the array.
A program that demonstrates arrays is given as follows.
 Live Demo
#include <stdio.h>
int main () {
   int a[5];
   int i,j;
   for (i = 0;i<5;i++) {
      a[i] = i+100;
   }
   for (j = 0;j<5;j++) {
      printf("Element[%d] = %d\n", j, a[j] );
   }
   return 0;
}
The output of the above program is as follows.
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
HTML | <iframe> src Attribute - GeeksforGeeks

16 Oct, 2019
The HTML <iframe> src attribute is used to specify the URL of the document that are embedded to the <iframe> element.
Syntax:
<iframe src="URL">
Attribute Values: It contains single value URL which specifies the URL of the document that is embedded to the iframe. There are two types of URL link which are listed below:
Absolute URL: It points to another webpage.
Relative URL: It points to other files of the same web page.
Below example illustrates the <iframe> src attribute in HTML:
Example:
<!DOCTYPE html> <html>   <head>    <title>        HTML iframe src Attribute    </title></head>  <body style="text-align:center;">           <h1>GeeksforGeeks</h1>          <h2>HTML iframe src Attribute</h2>          <iframe src="https://ide.geeksforgeeks.org/index.php"            height="200" width="400"></iframe> </body>   </html>                    
Output:
Supported Browsers: The browser supported by HTML <iframe> src attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubham_singh
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
Form validation using HTML and JavaScript
HTML Introduction
How to Upload Image into Database and Display it using PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
F# - if/elif/else statement

An if/then/elif/else construct has multiple else branches.
The syntax of an if/then/elif/else statement in F# programming language is −
if expr then
   expr
elif expr then
   expr
elif expr then
   expr
...
else
   expr

let a : int32 = 100

(* check the boolean condition using if statement *)

if (a = 10) then
   printfn "Value of a is 10\n"
elif (a = 20) then
   printfn " Value of a is 20\n"
elif (a = 30) then
   printfn " Value of a is 30\n"
else
   printfn " None of the values are matching\n"
   printfn "Value of a is: %d" a
When you compile and execute the program, it yields the following output −
None of the values are matching

Value of a is: 100

 Print
 Add Notes
 Bookmark this page
GATE | GATE CS 2020 | Question 31 - GeeksforGeeks

13 Aug, 2021
A direct mapped cache memory of 1 MB has a block size of 256 bytes. The cache has an access time of 3 ns and a hit rate of 94%. During a cache miss, it takes 20 ns to bring the first word of a block from the main memory, while each subsequent word takes 5 ns. The word size is 64 bits. The average memory access time in ns (round off to 1 decimal place) is ________ .
Note – This question was Numerical Type.(A) 13.5(B) 15.5(C) 23.5(D) 15.3Answer: (A)Explanation: Given,
Word size = 64 bit = 8 byte
And, 
Block size = 256 byte 
Therefore, Number of words per block will be,
= 256 / 8 = 32
According to question, first word takes 20ns and rest (31) each subsequent words take 5ns each to fetch a word from main-memory to cache.
Hence,
Tavg = (0.94 × 3) + (1 – 0.94) [3 + (20 + (31 × 5))]
= 13.5 (in ns) 
Option (A) is correct.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGate PYQs on Avg. Memory access time Part-2 with Ashish Verma | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:01 / 25:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=D94hqMo-FWs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
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 2019 | Question 27
GATE | GATE-CS-2016 (Set 2) | Question 48
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 2021 | Set 1 | Question 47
GATE | GATE-CS-2017 (Set 2) | Question 42
\textit - Tex Command

\textit - Used to produce text-mode material in italics within a mathematical expression.
{ \textit #1}
\textit command is used to produce text-mode material in italics within a mathematical expression.

\textit{\alpha in textit mode }\alpha

\alpha in textit mode α



\textit{\alpha in textit mode }\alpha

\alpha in textit mode α


\textit{\alpha in textit mode }\alpha

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to skip a particular test method from execution in Cucumber?

We can skip a particular test method from execution in Cucumber with
the help of tagging of scenarios in the feature file.
feature file.
@Regression
Feature: Invoice Testing
@Smoke
Scenario: Login Verification
Given User is in Home Page
@Payment
Scenario: Payment Testing
Given User is in Payment Page
Feature file with scenarios having tags Smoke and Payment.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.AbstractTestNGCucumberTests;
@RunWith(Cucumber.class)
@CucumberOptions(
   features = “src/test/java/features”,
   glue = “stepDefiniations”
   tags = { “~@Payment”}
)
To skip the scenarios with @Payment , ~ is placed before the @Payment tag in Test Runner file.
trunc() in Python

In this tutorial, we are going to learn about the math.trunc() method.
The method math.trunc() is used to truncate the float values. It will act as math.floor() method for positive values and math.ceil() method for negative values.
 Live Demo
# importing math module
import math
# floor value
print(math.floor(3.5))
# trunc for positive number
print(math.trunc(3.5))
If you run the above code, then you will get the similar result as follows.
3
3
 Live Demo
# importing math module
import math
# ceil value
print(math.ceil(-3.5))
# trunc for negative number
print(math.trunc(-3.5))
If you run the above code, then you will get the similar result as follows.
-3
-3
If you have any doubts in the tutorial, mention them in the comment section.
JavaScript Array forEach() Method

29 Oct, 2021
Below is the example of the Array forEach() method.
Example:<script>    // JavaScript to illustrate forEach() method    function func() {              // Original array        const items = [12, 24, 36];        const copy = [];          items.forEach(function (item) {            copy.push(item + item+2);        });          document.write(copy);    }    func();</script>                    
<script>    // JavaScript to illustrate forEach() method    function func() {              // Original array        const items = [12, 24, 36];        const copy = [];          items.forEach(function (item) {            copy.push(item + item+2);        });          document.write(copy);    }    func();</script>                    
Output:26,50,74
26,50,74
The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.
Syntax:
array.forEach(callback(element, index, arr), thisValue)
Parameters: This method accepts five parameters as mentioned above and described below:
callback: This parameter holds the function to be called for each element of the array.
element: The parameter holds the value of the elements being processed currently.
index: This parameter is optional, it holds the index of the current value element in the array starting from 0.
array: This parameter is optional, it holds the complete array on which Array.every is called.
thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Return value: The return value of this method is always undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function.
Below example illustrate the Array forEach() method in JavaScript:
Example: In this example the method forEach() calculates the square of every element of the array.const items = [1, 29, 47];
const copy = [];

items.forEach(function(item){
  copy.push(item*item);
});
print(copy);
Output:1,841,2209
const items = [1, 29, 47];
const copy = [];

items.forEach(function(item){
  copy.push(item*item);
});
print(copy);

Output:
1,841,2209
Code for the above method is provided below:
Program:
<script>    // JavaScript to illustrate forEach() method    function func() {                // Original array        const items = [1, 29, 47];        const copy = [];          items.forEach(function (item) {            copy.push(item * item);        });          document.write(copy);    }    func();</script>
Output:
1,841,2209
Supported Browsers: The browsers supported by JavaScript Array forEach() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1.5 and above
Internet Explorer 9 and above
Opera 9.5 and above
Safari 3 and above
ysachin2314
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
chroot command in Linux with examples

15 May, 2019
chroot command in Linux/Unix system is used to change the root directory. Every process/command in Linux/Unix like systems has a current working directory called root directory. It changes the root directory for currently running processes as well as its child processes.A process/command that runs in such a modified environment cannot access files outside the root directory. This modified environment is known as “chroot jail” or “jailed directory”. Some root user and privileged process are allowed to use chroot command.
“chroot” command can be very useful:
To create a test environment.
To recover the system or password.
To reinstall the bootloader.
Syntax:
chroot /path/to/new/root command
OR
chroot /path/to/new/root /path/to/server
OR
chroot [options] /path/to/new/root /path/to/server
Options:
–userspec=USER:GROUP : This option describe the user and group which is to be used. Either name or numeric ID can be used to specify the user and group.
–groups=G_LIST : It describe the supplementary groups as g1,g2,..,gN.
–help : Shows the help message, and exit.
–version : Gives version information, and exit.
Example:
Step 1: We will create a mini-jail with bash and basic commands only. Let’s create a “jail” directory inside the “home” directory, which will be our new root.$ mkdir $HOME/jail
$ mkdir $HOME/jail
Step 2: Create directories inside “$HOME/jail”:$ mkdir -p $HOME/jail/{bin, lib64}
$ cd $HOME/jail

$ mkdir -p $HOME/jail/{bin, lib64}
$ cd $HOME/jail

Step 3: Copy /bin/bash and /bin/ls into $HOME/jail/bin/ location using cp command:$ cp -v /bin/{bash, ls} $HOME/jail/bin
$ cp -v /bin/{bash, ls} $HOME/jail/bin
Step 4: Use ldd command to print shared libraries:$ ldd /bin/bash
$ ldd /bin/bash
Step 5: Copy required libraries into $HOME/jail/lib64/ location using cp command:cp -v libraries/displayed/by/above/command $HOME/jail/lib64Similarly, copy the libraries of ls command into $HOME/jail/lib64 location.
cp -v libraries/displayed/by/above/command $HOME/jail/lib64
Similarly, copy the libraries of ls command into $HOME/jail/lib64 location.
Step 6: Finally, chroot into your mini-jail:$ sudo chroot $HOME/jail /bin/bashNow user sees $HOME/jail directory as its root directory. This is a great boost in the security.
$ sudo chroot $HOME/jail /bin/bash
Now user sees $HOME/jail directory as its root directory. This is a great boost in the security.
linux-command
Linux-directory-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Weekday() and WeekdayName() Function in MS Access

23 Sep, 2020
1. Weekday() Function :In MS Access, The weekday() function returns the weekday number for a given date. In this function, a date will be passed as a parameter and it returns the weekday of that date. By default the 1 is denoted for Sunday and 7 for Saturday. The second parameter will be optional it will be the first day of the week.
Syntax :
Weekday(date, firstdayofweek)

Parameters Value :
Example-1 :
SELECT Weekday(#06/17/2020#);

Output :
4

Example-2 :
SELECT Weekday(Date());

Output :
5

2. WeekdayName() Function :In MS Access, the WeekdayName() function returns the weekday name. In this function, the first function will be the week number and the second parameter will be abbreviate.it is optional. If you want abbreviation then pass true otherwise pass false. and the third parameter will be the first day of the week. It is also optional.
Syntax :
WeekdayName(number, abbreviate, firstdayofweek)

Parameters :
Example-1 :
SELECT WeekdayName(1);

Output :
Sunday

Example-2 :
SELECT WeekdayName (3, TRUE, 2)

Output :
Wed

DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java String concat() Method

❮ String Methods

Concatenate two strings:
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));

Try it Yourself »

The concat() method appends (concatenate) a 
string to the end of another string.
public String concat(String string2)

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.
How to use POST method to send data in jQuery Ajax?

The jQuery.post( url, [data], [callback], [type] ) method loads a page from the server using a POST HTTP request.
Here is the description of all the parameters used by this method −
url − A string containing the URL to which the request is sent
data − This optional parameter represents key/value pairs or the return value of the .serialize() function that will be sent to the server.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
type − This optional parameter represents a type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".
Let’s say we have the following PHP content in result.php file:
<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
}
?>
Here's the code snippet to implement how to use POST method to send data in jQuery Ajax:
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               
               $.post(
                  "result.php",
                  { name: "John" },
                  function(data) {
                     $('#stage').html(data);
                  }
               );            
            });
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file −</p>
       
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>
Python String startswith() Method

Python string  method startswith() checks whether string starts with str, optionally restricting the matching with the given indices start and end.
Following is the syntax for startswith() method −
str.startswith(str, beg=0,end=len(string));

str − This is the string to be checked.
str − This is the string to be checked.
beg − This is the optional parameter to set start index of the matching boundary.
beg − This is the optional parameter to set start index of the matching boundary.
end − This is the optional parameter to end start index of the matching boundary.
end − This is the optional parameter to end start index of the matching boundary.
This method returns true if found matching string otherwise false.
The following example shows the usage of startswith() method.
#!/usr/bin/python

str = "this is string example....wow!!!";
print str.startswith( 'this' )
print str.startswith( 'is', 2, 4 )
print str.startswith( 'this', 2, 4 )
When we run above program, it produces following result −
True
True
False


    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
Operation Counts Method in Algorithm

There are different methods to estimate the cost of some algorithm. One of them by using the operation count. We can estimate the time complexity of an algorithm by choosing one of different operations. These are like add, subtract etc. We have to check how many of these operations are done. The success of this method depends on our ability to identify the operations that contribute most of the time complexity.
Suppose we have an array, of size n [0 to n - 1]. Our algorithm will find the index of largest element. We can estimate the cost by counting number of comparison operation is performed between each pair of elements of the array. We have to remember that, we will choose only one operation. In this algorithm there are few more operations like increment of iteration variable i, or assign values for index etc. But they are not considered in this case.
getMax(arr, n):
   index := 0
   max := arr[0]
   for i in range 1 to n - 1, do
      if arr[i] > max, then
         max := arr[i]
         index := i
      end if
   done
   return index
We have to choose those operations that are performed maximum amount of time to estimate the cost. Suppose we have one bubble sort algorithm, and we count the swap operation. Then we have to keep in mind that when it will be maximum. That will give us maximum result during analysis.
VBScript InStrRev Function

The InStrRev Function returns the first occurrence of one string within another string. The Search happens from right to Left.
InStrRev(string1,string2[,start,[compare]])

String1, a Required Parameter. String to be searched.
String1, a Required Parameter. String to be searched.
String2, a Required Parameter. String against which String1 is searched.
String2, a Required Parameter. String against which String1 is searched.
Start, an Optional Parameter. Specifies the Starting position for the search. The Search begins at the first position from right to left.
Start, an Optional Parameter. Specifies the Starting position for the search. The Search begins at the first position from right to left.
Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below mentioned values −

0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison


Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below mentioned values −
0 = vbBinaryCompare - Performs Binary Comparison(Default)
0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison
1 = vbTextCompare - Performs Text Comparison
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "Microsoft VBScript"
         document.write("Line 1 : " & InStrRev(var,"s",10) & "<br />")
         document.write("Line 2 : " & InStrRev(var,"s",7) & "<br />")
         document.write("Line 3 : " & InStrRev(var,"f",-1,1) & "<br />")
         document.write("Line 4 : " & InStrRev(var,"t",5) & "<br />")
         document.write("Line 5 : " & InStrRev(var,"i",7) & "<br />")
         document.write("Line 6 : " & InStrRev(var,"i",7) & "<br />")
         document.write("Line 7 : " & InStrRev(var,"VB",1))
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : 6
Line 2 : 6
Line 3 : 8
Line 4 : 0
Line 5 : 2
Line 6 : 2
Line 7 : 0 


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Java Program to Add Two Binary Strings - GeeksforGeeks

28 Mar, 2021
When two binary strings are added, then the sum returned is also a binary string.
Example:
Input :  x = "10", y = "01"
Output: "11"

Input :  x = "110", y = "011"
Output: "1001"
Explanation:
  110 
+ 011
=1001
Here, we need to start adding from the right side and when the sum returned is more than one then store the carry for the next digits.
Let’s see a program in order to get the clear concept of above topic.
Example:
Java
// java program to add two binary strings  public class gfg {      // Function to add two binary strings    static String add_Binary(String x, String y)    {          // Initializing result        String res = "";          // Initializing digit sum        int d = 0;          // Traversing both the strings starting        // from the last characters        int k = x.length() - 1, l = y.length() - 1;        while (k >= 0 || l >= 0 || d == 1) {              // Computing the sum of last            // digits and the carry            d += ((k >= 0) ? x.charAt(k) - '0' : 0);            d += ((l >= 0) ? y.charAt(l) - '0' : 0);              // When the current digit's sum is either            // 1 or 3 then add 1 to the result            res = (char)(d % 2 + '0') + res;              // Computing carry            d /= 2;              // Moving to the next digits            k--;            l--;        }          return res;    }      // The Driver code    public static void main(String args[])    {        String x = "011011", y = "1010111";          System.out.print(add_Binary(x, y));    }}
1110010
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Python Program to Accept Three Digits and Print all Possible Combinations from the Digits

When it is required to print all possible combination of digits when the input is taken from the user, nested loop is used.
Below is a demonstration of the same −
 Live Demo
first_num = int(input("Enter the first number..."))
second_num = int(input("Enter the second number..."))
third_num = int(input("Enter the third number..."))
my_list = []
print("The first number is ")
print(first_num)
print("The second number is ")
print(second_num)
print("The third number is ")
print(third_num)

my_list.append(first_num)
my_list.append(second_num)
my_list.append(third_num)

for i in range(0,3):
   for j in range(0,3):
      for k in range(0,3):
         if(i!=j&j!=k&k!=i):
            print(my_list[i],my_list[j],my_list[k])
Enter the first number...3
Enter the second number...5
Enter the third number...8
The first number is
3
The second number is
5
The third number is
8
3 5 8
3 8 5
5 3 8
5 8 3
8 3 5
8 5 3
The three numbers re taken as input from the user.
The three numbers re taken as input from the user.
An empty list is created.
An empty list is created.
The three numbers are displayed on the console.
The three numbers are displayed on the console.
These numbers are appended to the empty list.
These numbers are appended to the empty list.
Three nested loops are used, and the numbers are iterated over.
Three nested loops are used, and the numbers are iterated over.
When they are not equal, their combinations are displayed as output on the console.
When they are not equal, their combinations are displayed as output on the console.
How can I get the current week using Python?

YOu can use the isocalender function from the datetime module to get the current week. Create the object of the date first, then call isocalender() on this object. This returns a 3-tuple of Year, Week number and Day of Week. 
import datetime
my_date = datetime.date.today() # if date is 01/01/2018
year, week_num, day_of_week = my_date.isocalendar()
print("Week #" + str(week_num) + " of year " + str(year))
This will give the output −
Week #1 of year 2018
Encode and decode MIME quoted-printable data using Python

Many times we need to deal with data which not always has the regular ASCII characters. For example, an email in a different language other than English. Python has mechanism to deal with such characters by using MIME (Multipurpose Internet Mail Extensions) based module. In this article we will see how we can decode such characters in an email or otherwise in some straight inputs.
The email package has modules namely mime and charset which can carry out the encoding and decoding work as shown in the below example. We have taken an email message containing Unicode characters and then encoded it to utf-8.
import email.mime, email.mime.nonmultipart, email.charset
msg=email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8')

#Construct a new charset
cs=email.charset.Charset('utf-8')
cs.body_encoding = email.charset.QP

# Set the content using the new charset
msg.set_payload(u'This is the text containing ünicöde', charset=cs)
print(msg)

Running the above code gives us the following result −
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable

This is the text containing =C3=BCnic=C3=B6de
This python module performs quoted-printable transport encoding and decoding. The quoted-printable encoding is designed for data where there are relatively few nonprintable characters. In the below example we see how we can encode and decode string with non regular ASCII characters.
import quopri
str1 = 'äé'
#encoded = quopri.encodestring('äé'.encode('utf-8'))
encoded = quopri.encodestring(str1.encode('utf-8'))
print(encoded)

str2 = '=C3=A4=C3=A9'
decoded_string = quopri.decodestring(str2)
print(decoded_string.decode('utf-8'))
Running the above code gives us the following result −
b'=C3=A4=C3=A9'
äé
The easiest way to concatenate two arrays in PHP?

Simply use, array_merge() to concatenate two arrays in PHP. Let’s say the following are out arrays −
$nameArray1 = array('John','David');
$nameArray2 = array('Mike','Sam');
Now, set both the above arrays in array_merge() to concatenate them.
The syntax is as follows −
array_merge($yourFirstArrayName, $yourSecondArrayName);
The PHP code is as follows 
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$nameArray1 = array('John','David');
$nameArray2 = array('Mike','Sam');
$result = array_merge($nameArray1, $nameArray2);
print_r($result);
?>
</body>
</html>
This will produce the following output
Array ( [0] => John [1] => David [2] => Mike [3] => Sam )
What is the usage of an abort event in JavaScript?

Use the on abort event to abort the loading of an image. You can try to run the following code to learn how to implement an abort event in JavaScript.
<!DOCTYPE html>
<html>
   <body>
      <script>
         function abortFunc() {
            alert('Error- Loading of the image aborted');
         }
      </script>
      <img src="/videotutorials/images/tutor_connect_home.jpg" onabort = "abortFunc()">
   </body>
</html>
Difference between two selects in MySQL?

You can use subqueries for difference between two selects in MySQL. The syntax is as follows:
SELECT *FROM yourTableName where yourColumnName NOT IN(SELECT yourColumnName FROM youTableName WHERE yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table DifferenceSelectDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserId int,
   -> UserValue int,
  -> PRIMARY KEY(Id)
   ->  );
Query OK, 0 rows affected (0.87 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(10,10);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(10,20);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(20,30);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(20,20);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(30,40);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(30,20);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from DifferenceSelectDemo;
The following is the output:
+----+--------+-----------+
| Id | UserId | UserValue |
+----+--------+-----------+
|  1 |     10 |        10 |
|  2 |     10 |        20 |
|  3 |     20 |        30 |
|  4 |     20 |        20 |
|  5 |     30 |        40 |
|  6 |     30 |        20 |
+----+--------+-----------+
6 rows in set (0.02 sec)
Here is the query to get the difference between two selects:
mysql> select *from DifferenceSelectDemo
   -> WHERE UserValue NOT IN (select UserValue from DifferenceSelectDemo where Id=1);
The following is the output:
+----+--------+-----------+
| Id | UserId | UserValue |
+----+--------+-----------+
|  2 |     10 |        20 |
|  3 |     20 |        30 |
|  4 |     20 |        20 |
|  5 |     30 |        40 |
|  6 |     30 |        20 |
+----+--------+-----------+
5 rows in set (0.09 sec)
Python3 Program to Move all zeroes to end of array - GeeksforGeeks

23 Dec, 2021
Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).Example:  
Input :  arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0};

Input : arr[]  = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
 
There can be many ways to solve this problem. Following is a simple and interesting way to solve this problem. Traverse the given array ‘arr’ from left to right. While traversing, maintain count of non-zero elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]’ and increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and ‘count’ is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from ‘count’ till end of the array.Below is the implementation of the above approach.  
Python3
# Python3 code to move all zeroes# at the end of array  # Function which pushes all# zeros to end of an array.def pushZerosToEnd(arr, n):    count = 0 # Count of non-zero elements          # Traverse the array. If element     # encountered is non-zero, then    # replace the element at index    # 'count' with this element    for i in range(n):        if arr[i] != 0:                          # here count is incremented            arr[count] = arr[i]            count+=1          # Now all non-zero elements have been    # shifted to front and 'count' is set    # as index of first 0. Make all     # elements 0 from count to end.    while count < n:        arr[count] = 0        count += 1          # Driver codearr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]n = len(arr)pushZerosToEnd(arr, n)print("Array after pushing all zeros to end of array:")print(arr)  # This code is contributed by "Abhishek Sharma 44"
Output:  
Array after pushing all zeros to end of array :
1 9 8 4 2 7 6 9 0 0 0 0
Time Complexity: O(n) where n is number of elements in input array.Auxiliary Space: O(1) 
Please refer complete article on Move all zeroes to end of array for more details!
Amazon
Bloomberg
Linkedin
Paytm
Samsung
SAP Labs
Arrays
Python
Paytm
Amazon
Samsung
SAP Labs
Linkedin
Bloomberg
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
current_url driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around current_url driver method in Selenium. current_url method gets current URL of the current page.
Syntax –
driver.current_url
Example –Now one can use current_url method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.current_url

To demonstrate, current_url method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get current_url,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get current urlprint(driver.current_url)
Output –Screenshot added –
Terminal output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.