code-rag-bench/online-tutorials huggingface dataset:
How to find a node in a JTree Component with Java?

To find a node in a JTree component, use the getNextMatch() method. Here, wer are trying to find a node that begins with character “A”. The search begins from the node set below with begnRow variable −
int begnRow = 0;
String prefix = "A"; TreePath treePath = tree.getNextMatch(prefix, begnRow, Position.Bias.Forward);
We have displayed the resultant node in the Console −
System.out.println("Node = "+treePath);
The following is an example to find a node in a JTree Component with Java −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp");
      node.add(node1);
      node.add(node2);
      node.add(node3);
      DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website");
      DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website");
      DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website");
      DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app");
      DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app");
      DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp");
      node1.add(one);
      node1.add(two);
      node1.add(three);
      node2.add(four);
      node2.add(five);
      node3.add(six);
      JTree tree = new JTree(node);
      int begnRow = 0;
      String prefix = "A"; TreePath treePath = tree.getNextMatch(prefix, begnRow, Position.Bias.Forward); System.out.println("Node = "+treePath);
      tree.setRowHeight(25);
      frame.add(tree);
      frame.setSize(550,400);
      frame.setVisible(true);
   }
}
The output is as follows. On running, the node which is to be found is visible −
bits.Reverse() Function in Golang with Examples - GeeksforGeeks

19 Apr, 2020
Go language provides inbuilt support for bits to implement bit counting and manipulation functions for the predeclared unsigned integer types with the help of bits package. This package provides Reverse() function which is used to find the reversed order of the value of a. To access Reverse() function you need to add a math/bits package in your program with the help of the import keyword.
Syntax:
func Reverse(a uint) uint
Parameters: This function takes one parameter of uint type, i.e., a.
Return Value: This function returns the value of a with its bits in reversed order.
Example 1:
// Golang program to illustrate bits.Reverse() Functionpackage main  import (    "fmt"    "math/bits")  // Main functionfunc main() {      // Using Reverse() function    a := bits.Reverse(5)    fmt.Printf("Reverse order of %d: %b", 5, a)  }
Output:
Reverse order of 5: 1010000000000000000000000000000000000000000000000000000000000000
Example 2:
// Golang program to illustrate bits.Reverse() Functionpackage main  import (    "fmt"    "math/bits")  // Main functionfunc main() {      // Using Reverse() function    a1 := bits.Reverse(23)    fmt.Printf("Reverse(%b) := %b\n", 23, a1)      a2 := bits.Reverse(13)    fmt.Printf("Reverse(%b) := %b\n", 13, a2)  }
Output:
Reverse(10111) := 1110100000000000000000000000000000000000000000000000000000000000Reverse(1101) := 1011000000000000000000000000000000000000000000000000000000000000
Golang-bits
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Time Formatting in Golang
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Slices in Golang
Golang Maps
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to draw an Image with drawImage() in HTML5?

The HTML5 drawImage() method is used to draw an image, canvas or video on the canvas. It also draws parts of an image. You can also use it to increase or decrease image size.
Here are the parameter values of the drawImage() method −
 
You can try to run the following code to learn how to draw an image using the drawImage() method −
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
   var pattern = new Image();
   function animate() {
      pattern.src = '/html5/images/pattern.jpg';
      setInterval(drawShape, 100);
   }
   function drawShape() {
      // get the canvas element using the DOM
      var canvas = document.getElementById('newCanvas');
      // Make sure we don't execute when canvas isn't supported
      if (canvas.getContext) {
         // use getContext to use the canvas for drawing
         var ctx = canvas.getContext('2d');
         ctx.fillStyle = 'rgba(0,0,0,0.4)';
         ctx.strokeStyle = 'rgba(0,153,255,0.4)';
         ctx.save();
         ctx.translate(150,150);
         var time = new Date();
         ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() );
         ctx.translate(0,28.5);
         ctx.drawImage(pattern,-3.5,-3.5);
         ctx.restore();
      }
      else {
         alert('You need Safari or Firefox 1.5+ to see this demo.');
      }
   }
</script>
</head>
<body onload = "animate();">
<canvas id = "newCanvas" width = "400" height = "400"></canvas>
</body>
</html>
ChronoLocalDate from() method in Java with Examples - GeeksforGeeks

29 Apr, 2019
The from() method of ChronoLocalDate interface in Java method obtains an instance of ChronoLocalDate from a temporal object.
Syntax:
public static ChronoLocalDate 
    from(TemporalAccessor temporal)

Parameter: This method accepts a parameter temporal which specifies the temporal object to convert and not null.
Return Value: It returns the ChronoLocalDate and not null.
Exceptions: The function throws only DateTimeException which occurs if it is unable to convert it to a ChronoLocalDate.
Below programs illustrate the from() method of ChronoLocalDate in Java:
Note: The output will change on every run.
// Program to illustrate the from() method  import java.util.*;import java.time.*;import java.time.chrono.*;  public class GfG {    public static void main(String[] args)    {          ChronoLocalDate dt            = LocalDate.from(ZonedDateTime.now());          System.out.println(dt);    }}
2019-04-28

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#from-java.time.temporal.TemporalAccessor-
Java-ChronoLocalDate
Java-Functions
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Set in Java
Overriding in Java
Queue poll() method example in Java

Fetch and remove the first element in Queue using the poll() method.
Create a queue −
Queue<String> q = new LinkedList<String>();
Add some elements −
q.add("abc");
q.add("def");
q.add("ghi");
q.add("jkl");
q.add("mno");
q.add("pqr");
q.add("stu");
q.add("vwx");
Now, remove the first element −
q.poll()
The following is an example to implement the poll() method −
 Live Demo
import java.util.LinkedList;
import java.util.Queue;
public class Demo {
   public static void main(String[] args) {
      Queue<String> q = new LinkedList<String>();
      q.add("abc");
      q.add("def");
      q.add("ghi");
      q.add("jkl");
      q.add("mno");
      q.add("pqr");
      q.add("stu");
      q.add("vwx");
      System.out.println("Queue head = " + q.element());
      System.out.println("Removing element from queue = " + q.poll());
      System.out.println("Queue head now = " + q.element());
      System.out.println("Removing element from queue = " + q.poll());
      System.out.println("Queue head now = " + q.element());
      System.out.println("\nRemaining Queue elements...");
      Object ob;
      while ((ob = q.poll()) != null) {
         System.out.println(ob);
      }
   }
}
Queue head = abc
Removing element from queue = abc
Queue head now = def
Removing element from queue = def
Queue head now = ghi
Remaining Queue elements...
ghi
jkl
mno
pqr
stu
vwx
How to change font size in HTML?

To change the font size in HTML, use the style attribute. The style attribute specifies an inline style for an element.  The attribute is used with the HTML <p> tag, with the CSS property font-size. HTML5 do not support the <font> tag, so the CSS style is used to add font size.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to change the font size in an HTML page,
Live Demo
<!DOCTYPE html>
   <html>    
      <head>      
         <title>HTMLFont size</title>    
      </head>    
      <body>      
         <h1 style="color:red;font-size:40px;">Heading</h1>      
         <p style="color:blue;font-size:18px;">This is demo text</p>    
      </body>
</html>
Node.js os.hostname() Method - GeeksforGeeks

13 Oct, 2021
The os.hostname() method is an inbuilt application programming interface of the os module which is used to get host name of the operating system.
Syntax:
os.hostname()
Parameters: This method does not accept any parameters.
Return Value: This method returns a string value that specifies the host name of the operating system.
Below examples illustrate the use of os.hostname() method in Node.js:
Example 1:
// Node.js program to demonstrate the    // os.hostname() method      // Allocating os moduleconst os = require('os');  // Printing os.hostname() valueconsole.log(os.hostname());
Output:
gekchos_lappy

Example 2:
// Node.js program to demonstrate the    // os.hostname() method      // Allocating os moduleconst os = require('os');  // Printing os.hostname() valueif(os.hostname()) {    var hostname = os.hostname();    console.log("Hostname for the operating"        + " system is " + String(hostname));}
Output:
Hostname for the operating system is gekchos_lappy
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_hostname
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
\ast - Tex Command

\ast - Used to draw asterisk symbol.
{ \ast }
\ast command is used to draw asterisk symbol.

\ast 

∗



\ast 

∗


\ast 

    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
Python | Increase list size by padding each element by N - GeeksforGeeks

24 Jun, 2019
Given a list and an integer N, write a Python program to increase the size of the list by padding each element by N.
Examples:
Input : lst = [1, 2, 3]
        N = 3
Output : [1, 1, 1, 2, 2, 2, 3, 3, 3]

Input : lst = ['cats', 'dogs']
        N = 2
Output : ['cats', 'cats', 'dogs', 'dogs']

Approach #1 : List comprehension
# Python3 program to increase list size # by padding each element by N  def increaseSize(lst, N):          return [el for el in lst for _ in range(N)]          # Driver codelst = [1, 2, 3]N = 3print(increaseSize(lst, N))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

 Approach #2 : Using functools.reduce() method
The reduce function apply a particular function passed in its argument to all of the list elements. Therefore, in this approach we apply a function on each element where it’s occurrence gets multiplied by N.
# Python3 program to increase list size # by padding each element by Nfrom functools import reduce  def increaseSize(lst, N):          return reduce(lambda x, y: x + y, [[el]*N for el in lst])          # Driver codelst = [1, 2, 3]N = 3print(increaseSize(lst, N))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

 Approach #3 : Using itertools.chain()
# Python3 program to increase list size # by padding each element by Nfrom itertools import chain  def increaseSize(lst, N):          return list(chain(*([el]*N for el in lst)))          # Driver codelst = [1, 2, 3]N = 3print(increaseSize(lst, N))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

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

The jQuery.getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request.
Assuming we have the following JSON content in result.json file −
{
"name": "Amy",
"age" : "24",
"sex": "female"
}
The following is the code snippet showing the usage of this method −
   <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){
               $.getJSON('result.json', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.name + '</p>');
                  $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                  $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
               });
            });
               
         });
      </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>
GATE | Gate IT 2008 | Question 42 - GeeksforGeeks

22 Apr, 2020
When n = 22k for some k ≥ 0, the recurrence relation
T(n) = √(2) T(n/2) + √n, T(1) = 1
evaluates to :(A) √(n) (log n + 1)(B) √(n) (log n )(C) √(n) log √(n)(D) n log √(n)Answer: (A)Explanation: Please note that the question is asking about exact solution. Master theorem provides results in the form of asymptotic notations. So we can’t apply Master theorem here. We can solve this recurrence using simple expansion or recurrence tree method.
T(n) = √(2) T(n/2) + √n
     = √(2) [√(2) T(n/4) + √(n/2) ] + √n
     = 2 T(n/4) + √2 √(n/2) +√n
     = 2[ √2 T(n/8) + √(n/4) ]+√2 √(n/2)+√n
     = √(2^3) T(n/8)+ 2 √(n/4) + √2 √(n/2) +√n
     = √(2^3) T(n/8)+√n +√n +√n
     = √(2^3) T(n/(2^3))+3√n
     .............................................
     = √(2^k) T(n/(2^k))+k√n
     = √(2^logn) + logn √n
     = √n + logn √n
     = √n(logn +1)

Alternate Solution :This question can be easily done by substitution method look:T(1)= 1; GIVEN.Now use n=2 in the given recurrence relation which gives 2*(1.414) (since value of root over 2 is 1.414)now by looking at the options use n=2 which satisfies option A.
Quiz of this Question
praveenkarmakar8
Gate IT 2008
GATE-Gate IT 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 53
Replace() and Space() Function in MS Access - GeeksforGeeks

31 Aug, 2020
1. Replace() Function :In MS Access The Replace function will replace a substring by another substring with a specified number. In this function, the first parameter will be the string and the second parameter will be found (The substring to search for in string)  and the third parameter will be the replacement(The substring to replace find in the string) and fourth is optional is the starting point if not given then default it will be taken 1, fifth will be the count( number of replaces to perform), this will also optional.
Syntax :
Replace(string1, find, replacement, start, count) 
Example –
SELECT Replace("geeksforgeeks", "e", "i") AS ReplaceString;
Output –
Example –
SELECT Replace("geeksforgeeks", "g", "z", 4) AS ReplaceString;
Output –
2. Space() Function :In MS Access, The Space function returns a string of the given number of space characters. A number will be pass as a parameter and it will return a string of the length of the given number and all characters will be space.
Syntax :
Space(number) 
Example –
SELECT len(Space(15)) AS SpaceString;
Output –
Example –
SELECT len(Space(10)) AS SpaceString;
Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
How to Create a Table With Multiple Foreign Keys in SQL?
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
SQL - ORDER BY
What is Temporary Table in SQL?
How to fill the area under a step curve using pyplot? (Matplotlib)

To fill the area under step curve using pyplot, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Ceate random data points, x, y1 and y2, using numpy.
To fill the area under the curve, put x and y with ste="pre", using fill_between() method.
Plot (x, y1) and (x, y2) lines using plot() method with drawstyle="steps" method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x
plt.fill_between(x, y1, step="pre", alpha=0.4)
plt.fill_between(x, y2, step="pre", alpha=0.4)

plt.plot(x, y1, drawstyle="steps")
plt.plot(x, y2, drawstyle="steps")

plt.show()
SymPy - Plotting

SymPy uses Matplotlib library as a backend to render 2-D and 3-D plots of mathematical functions. Ensure that Matplotlib is available in current Python installation. If not, install the same using following command −
pip install matplotlib

Plotting support is defined in sympy.plotting module. Following functions are present in plotting module −
plot − 2D line plots
plot − 2D line plots
plot3d − 3D line plots
plot3d − 3D line plots
plot_parametric − 2D parametric plots
plot_parametric − 2D parametric plots
plot3d_parametric − 3D parametric plots
plot3d_parametric − 3D parametric plots
The plot() function returns an instance of Plot class. A plot figure may have one or more SymPy expressions. Although it is capable of using Matplotlib as backend, other backends such as texplot, pyglet or Google charts API may also be used.
plot(expr, range, kwargs)

where expr is any valid symPy expression. If not mentioned, range uses default as (-10, 10).
Following example plots values of x2 for each value in range(-10,10) −
>>> from sympy.plotting import plot 
>>> from sympy import * 
>>> x=Symbol('x') 
>>> plot(x**2, line_color='red')

To draw multiple plots for same range, give multiple expressions prior to the range tuple.
>>> plot( sin(x),cos(x), (x, -pi, pi))

You can also specify separate range for each expression.
plot((expr1, range1), (expr2, range2))

Following figure plots sin(x) and cos(x) over different ranges.
>>> plot( (sin(x),(x, -2*pi, 2*pi)),(cos(x), (x, -pi, pi)))

Following optional keyword arguments may be specified in plot() function.
line_color − specifies color of the plot line.
line_color − specifies color of the plot line.
title − a string to be displayed as title
title − a string to be displayed as title
xlabel − a string to be displayed as label for X axis
xlabel − a string to be displayed as label for X axis
ylabel − a string to be displayed as label for y axis
ylabel − a string to be displayed as label for y axis
>>> plot( (sin(x),(x, -2*pi, 2*pi)),(cos(x), (x, -pi, pi)), line_color='red', title='SymPy plot example')

The plot3d() function renders a three dimensional plot.
plot3d(expr, xrange, yrange, kwargs)

Following example draws a 3D surface plot −
>>> from sympy.plotting import plot3d 
>>> x,y=symbols('x y') 
>>> plot3d(x*y, (x, -10,10), (y, -10,10))

As in 2D plot, a three dimensional plot can also have multiple plots each with different range.
>>> plot3d(x*y, x/y, (x, -5, 5), (y, -5, 5))

The plot3d_parametric_line() function renders a 3 dimensional parametric line plot.
>>> from sympy.plotting import plot3d_parametric_line 
>>> plot3d_parametric_line(cos(x), sin(x), x, (x, -5, 5))

To draw a parametric surface plot, use plot3d_parametric_surface() function.
plot3d_parametric_surface(xexpr, yexpr, zexpr, rangex, rangey, kwargs)

>>> from sympy.plotting import plot3d_parametric_surface 
>>> plot3d_parametric_surface(cos(x+y), sin(x-y), x-y, (x, -5, 5), (y, -5, 5))

 Print
 Add Notes
 Bookmark this page
jQuery Selectors

jQuery selectors are one of the most important parts of the jQuery library.
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their 
name, id, classes, types, attributes, values of attributes and much more.
It's based on the existing CSS Selectors, and in addition, it has 
some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:
Example
When a user clicks on a button, all <p> elements will be hidden:
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the 
HTML element:
Example
When a user clicks on a button, the element with id="test" will be hidden:
The jQuery .class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:
Example
When a user clicks on a button, the elements with class="test" will be hidden:
Use our jQuery Selector Tester to demonstrate the different selectors.
For a complete reference of all the jQuery selectors, please go to our jQuery Selectors Reference.
If your website contains a lot of pages, and you want your jQuery functions to be easy 
to maintain, you can put your jQuery functions in a separate .js file.
When we demonstrate jQuery in this tutorial, the functions are added directly into the <head> 
section. However, sometimes it is preferable to place them in a separate file, like this (use 
the src attribute to refer 
to the .js file): 
Use the correct selector to hide all <p> elements.
$("").hide();

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.
Partition List in C++

Suppose we have a linked list and a value x. We have to make partitions. The partition it such that all nodes less than x comes before the nodes that are greater than or equal to x. We should preserve the original relative order of the nodes in each of these two partitions. So if the list is like [1,4,3,2,5,2] and x = 3, then the output will be [1,2,2,4,3,5]
To solve this, we will follow these steps −
Make dummy nodes d1 and d2, and initialize them with -1, create two pointers dp1 and dp2, they are pointing d1 and d2 respectively.
while a is not nullif value of a < bnext of dp1 := a new node with value of adp1 := next pointer of dp1otherwisenext of dp2 := a new node with value of adp2 := next pointer of dp2a := next of a
if value of a < bnext of dp1 := a new node with value of adp1 := next pointer of dp1
next of dp1 := a new node with value of a
dp1 := next pointer of dp1
otherwisenext of dp2 := a new node with value of adp2 := next pointer of dp2
next of dp2 := a new node with value of a
dp2 := next pointer of dp2
a := next of a
next of dp1 := next of d2
return next of d1
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
void print_list(ListNode *head){
   ListNode *ptr = head;
   cout << "[";
   while(ptr->next){
      cout << ptr->val << ", ";
      ptr = ptr->next;
   }
   cout << "]" << endl;
}
class Solution {
public:
   ListNode* partition(ListNode* a, int b) {
      ListNode* dummy1 = new ListNode(-1);
      ListNode* dummy2 = new ListNode(-1);
      ListNode* dummyPtr1 = dummy1;
      ListNode* dummyPtr2 = dummy2;
      while(a){
         if(a->val < b){
            dummyPtr1->next = new ListNode(a->val);
            dummyPtr1 = dummyPtr1->next;
         }
         else{
            dummyPtr2->next = new ListNode(a->val);
            dummyPtr2 = dummyPtr2->next;
         }
         a = a->next;
      }
      dummyPtr1->next = dummy2->next;
      return dummy1->next;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,4,6,3,2,5,2,8};
   ListNode *head = make_list(v);
   print_list(ob.partition(head, 3));
}
[1,4,6,3,2,5,2,8]
3
[1, 2, 2, 4, 6, 3, 5, ]
C library macro - assert()

The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics in your C program.
Following is the declaration for assert() Macro.
void assert(int expression);
expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
This macro does not return any value.
The following example shows the usage of assert() macro −
#include <assert.h>
#include <stdio.h>
int main () {
   int a;
   char str[50];
	 
   printf("Enter an integer value: ");
   scanf("%d", &a);
   assert(a >= 10);
   printf("Integer entered is %d\n", a);
    
   printf("Enter string: ");
   scanf("%s", str);
   assert(str != NULL);
   printf("String entered is: %s\n", str);
	
   return(0);
}
Let us compile and run the above program in the interactive mode as shown below −
Enter an integer value: 11
Integer entered is 11
Enter string: tutorialspoint 
String entered is: tutorialspoint 


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Ext.js - Column Layout

This layout is to show multiple columns in the container. We can define a fixed or percentage width to the columns. The percentage width will be calculated based on the full size of the container.
Following is a simple syntax to use the Column layout.
layout: 'column'

Following is a simple example showing the usage of Column layout.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      
      <script type = "text/javascript">
         Ext.onReady(function() {
            Ext.create('Ext.panel.Panel', {
               renderTo : Ext.getBody(),
               layout : 'column' ,
               xtype: 'layout-column',
               requires: ['Ext.layout.container.Column'],
               width : 600,
               
               items: [{
                  title : 'First Component width 30%',
                  html : 'This is First Component',
                  columnWidth : 0.30
               },{
                  title : 'Second Component width 40%',
                  html : '<p> This is Second Component </p> <p> Next line for second component </p>',
                  columnWidth : 0.40
               },{
                  title : 'Third Component width 30%',
                  html : 'This is Third Component' ,
                  columnWidth : 0.30
               }]
            });
         });
      </script>
   </head>
   
   <body>
   </body>
</html>
The above program will produce the following result −
This is Second Component
Next line for second component
 Print
 Add Notes
 Bookmark this page
Java Lambda Expressions

Lambda Expressions were added in Java 8.
A lambda expression is a short block of code which takes in parameters and returns a
value. Lambda expressions are similar to methods, but they do not need a name and they
can be implemented right in the body of a method.
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Expressions are limited. They have to immediately return a value, and they cannot contain
variables, assignments or statements such as if or for. In order to do more complex
operations, a code block can be used with curly braces. If the lambda expression needs to
return a value, then the code block should have a return statement.
(parameter1, parameter2) -> { code block }
Lambda expressions are usually passed as parameters to a function:
Use a lamba expression in the ArrayList's forEach() method to print
every item in the list:
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    numbers.forEach( (n) -> { System.out.println(n); } );
  }
}

Try it Yourself »

Lambda expressions can be stored in variables if the variable's type is an interface which
has only one method. The lambda expression should have the same number of
parameters and the same return type as that method. Java has many of these kinds of
interfaces built in, such as the Consumer interface (found in the java.util package) used by lists.
Use Java's Consumer interface to store a lambda expression in a variable:
import java.util.ArrayList;
import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    Consumer<Integer> method = (n) -> { System.out.println(n); };
    numbers.forEach( method );
  }
}

Try it Yourself »

To use a lambda expression in a method, the method should have a parameter with a
single-method interface as its type. Calling the interface's method will run the lambda
expression:
Create a method which takes a lambda expression as a parameter:
interface StringFunction {
  String run(String str);
}

public class Main {
  public static void main(String[] args) {
    StringFunction exclaim = (s) -> s + "!";
    StringFunction ask = (s) -> s + "?";
    printFormatted("Hello", exclaim);
    printFormatted("Hello", ask);
  }
  public static void printFormatted(String str, StringFunction format) {
    String result = format.run(str);
    System.out.println(result);
  }
}

Try it Yourself »

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.
Tkinter Programming in Python

Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the user.
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
This would create a following window −
C++ String Library - end

It returns an iterator pointing to the first character of the string.
Following is the declaration for std::string::end.
   iterator end();
const_iterator end() const;
   iterator end() noexcept;
const_iterator end() const noexcept;
none
It returns an iterator to the past-the-end of the string.
Never throw any exceptions.
In below example for std::string::end.
#include <iostream>
#include <string>

int main () {
   std::string str ("Tutorials Point");
   for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
      std::cout << *it;
   std::cout << '\n';

   return 0;
}
The sample output should be like this −
Tutorials point  

 Print
 Add Notes
 Bookmark this page
Palindrome Linked List in Python

Suppose we have a linked list. We have to check whether the list elements are forming a
palindrome or not. So if the list element is like [1,2,3,2,1], then this is a palindrome.
To solve this, we will follow these steps −
fast := head, slow := head, rev := None and flag := 1
fast := head, slow := head, rev := None and flag := 1
if the head is empty, then return true
if the head is empty, then return true
while fast and next of fast is availableif next of the next of fast is available, then set flag := 0 and break the loopfast := next of the next of fasttemp := slow, slow := next of slownext of temp := rev, and rev := temp
while fast and next of fast is available
if next of the next of fast is available, then set flag := 0 and break the loop
if next of the next of fast is available, then set flag := 0 and break the loop
fast := next of the next of fast
fast := next of the next of fast
temp := slow, slow := next of slow
temp := slow, slow := next of slow
next of temp := rev, and rev := temp
next of temp := rev, and rev := temp
fast := next of slow, and next of slow := rev
fast := next of slow, and next of slow := rev
if flag is set, then slow := next of slow
if flag is set, then slow := next of slow
while fast and slow are not None,if the value of fast is not the same as the value of slow, then return falsefast := next of fast, and slow := next of slow
while fast and slow are not None,
if the value of fast is not the same as the value of slow, then return false
if the value of fast is not the same as the value of slow, then return false
fast := next of fast, and slow := next of slow
fast := next of fast, and slow := next of slow
return true
return true
Let us see the following implementation to get a better understanding −
 Live Demo
class ListNode:
   def __init__(self, data, next = None):
      self.data = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
class Solution(object):
   def isPalindrome(self, head):
      fast,slow = head,head
      rev = None
      flag = 1
      if not head:
         return True
      while fast and fast.next:
         if not fast.next.next:
            flag = 0
            break
         fast = fast.next.next
         temp = slow
         slow = slow.next
         temp.next = rev
         rev = temp
      #print(fast.val)
      fast = slow.next
      slow.next = rev
      if flag:
         slow = slow.next
      while fast and slow:
         if fast.data != slow.data:
            return False
         fast = fast.next
         slow = slow.next
      return True
head = make_list([1,2,3,2,1])
ob1 = Solution()
print(ob1.isPalindrome(head))
[1,2,3,2,1]
True
How to check if any of the strings in a column contains a specific string in MySQL?

For this, use CONCAT() along with LIKE operator. Let us first create a table −
mysql> create table DemoTable
(
   Name varchar(40)
);
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Johnson');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+
| Name    |
+---------+
| John    |
| Adam    |
| Bob     |
| Johnson |
| David   |
+---------+
5 rows in set (0.00 sec)
Following is the query to check if any of the strings in a column contains a specific string −
mysql> select *from DemoTable where Name like "%Joh%" OR "Joh" LIKE CONCAT("%", Name, "%");
This will produce the following output −
+---------+
| Name    |
+---------+
| John    |
| Johnson |
+---------+
2 rows in set (0.00 sec)
C++ Program to Find ASCII Value of a Character

There are 128 characters in the ASCII (American Standard Code for Information Interchange) table with values ranging from 0 to 127.
Some of the ASCII values of different characters are as follows −
A program that finds the ASCII value of a character is given as follows −
 Live Demo
#include <iostream>
using namespace std;
void printASCII(char c) {
   int i = c;
   cout<<"The ASCII value of "<<c<<" is "<<i<<endl;
}
int main() {
   printASCII('A');
   printASCII('a');
   printASCII('Z');
   printASCII('z');
   printASCII('$');
   printASCII('&');
   printASCII('?');
   return 0;
}
The ASCII value of A is 65
The ASCII value of a is 97
The ASCII value of Z is 90
The ASCII value of z is 122
The ASCII value of $ is 36
The ASCII value of & is 38
The ASCII value of ? is 63
In the above program, the function printASCII() prints the ASCII values of characters. This function defines an int variable i and the value of the character c is stored into this variable. Since i is integer type, the corresponding ASCII code of the character is stored into i. Then the values of c and i are displayed.
This is demonstrated by the following code snippet.
void printASCII(char c) {
   int i = c;
   cout<<"The ASCII value of "<<c<<" is "<<i<<endl;
}
MongoDB – dropIndex() Method

08 Feb, 2021
The dropIndex() method drops or delete the specified index from the given collection. It takes only one parameter which is the index, that we want to drop and it is optional. To find the index name or the index specification document for the dropIndex() method, use getIndexes() method. 
Using this method you are not allowed to remove the default index of the _id field.
You can also drop the hidden indexes. 
Starting from MongoDB 4.4, in this method, if the specified index is still being built, then this method will abort the building process of the specified index.
Note: Starting from MongoDB 4.2, you are not allowed to remove all the non- _id indexes using db.Collection_Name.dropIndex(“*”). If you want to do that then use db.Collection_Name.dropIndexes() method.
Syntax:
db.Collection_Name.dropIndex(index : <document/string>)
Optional Parameters:
index: The type of this parameter is string or document. It specifies the index that we want to drop. We can specify the index either by the index name or by the index specification document. 
Return:
This method returns a document that contains nIndexesWas and Ok fields with their values.
Example: 
In the following examples, we are working with:
Database: gfg
Collection: student
Document: Three documents contains name and language that students use in coding
First of all we created an index on the name field using createIndex() method:
db.student.createIndex({name:2})
Now we want to see the index name, using getIndex() so we can drop that index:
db.student.getIndexes()
Drop the index with the name: name_1: 
db.student.dropIndex("name_1")
Here, we are going to drop the name: name_1 index using dropIndex() method. In this method, we are using the parameter as a string:
Drop the index with the name: 2:
db.student.dropIndex({name:2})
Here, we are going to drop the name: 2 index using dropIndex() method. In this method, we are using the parameter as a document:
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB - Compound Indexes
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Spring Boot - CRUD Operations using MongoDB
Python | Pandas Series.dt.strftime

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.strftime() function is used to convert to Index using specified date_format. The function return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library.
Syntax: Series.dt.strftime(*args, **kwargs)
Parameter :date_format : Date format string (e.g. “%Y-%m-%d”)
Returns : Index of formatted strings
Example #1: Use Series.dt.strftime() function to convert the dates in the given series object to the specified date format.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30',               '2010-1-1 09:25', '2019-12-31 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.strftime() function to convert the dates in the given series object to the specified format.
# convert to the given date formatresult = sr.dt.strftime('% B % d, % Y, % r')  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.strftime() function has successfully converted the dates in the given series object to the specified format.
Example #2 : Use Series.dt.strftime() function to convert the dates in the given series object to the specified date format.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'M',                            tz = 'Asia / Calcutta'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.strftime() function to convert the dates in the given series object to the specified format.
# convert to the given date formatresult = sr.dt.strftime('% d % m % Y, % r')  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.strftime() function has successfully converted the dates in the given series object to the specified format.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Image Scraping with Python

08 Sep, 2021
Scraping Is a very essential skill for everyone to get data from any website. In this article, we are going to see how to scrape images from websites using python. For scraping images, we will try different approaches.
Method 1: Using BeautifulSoup and Requests
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4

requests:  Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
pip install requests

Approach:
Import module
Make requests instance and pass into URL
Pass the requests into a Beautifulsoup() function
Use ‘img’ tag to find them all tag (‘src ‘)
Implementation:
Python3
import requests from bs4 import BeautifulSoup     def getdata(url):     r = requests.get(url)     return r.text     htmldata = getdata("https://www.geeksforgeeks.org/") soup = BeautifulSoup(htmldata, 'html.parser') for item in soup.find_all('img'):    print(item['src'])
Output:
https://media.geeksforgeeks.org/wp-content/cdn-uploads/20201018234700/GFG-RT-DSA-Creative.pnghttps://media.geeksforgeeks.org/wp-content/cdn-uploads/logo-new-2.svg
Method 2: Using urllib and BeautifulSoup
urllib : It is a Python module that allows you to access, and interact with, websites with their URL. To install this type the below command in the terminal.
pip install urllib

Approach:
Import module
Read URL with urlopen()
Pass the requests into a Beautifulsoup() function
Use ‘img’ tag to find them all tag (‘src ‘)
Implementation:
Python3
from urllib.request import urlopenfrom bs4 import BeautifulSoup  htmldata = urlopen('https://www.geeksforgeeks.org/')soup = BeautifulSoup(htmldata, 'html.parser')images = soup.find_all('img')  for item in images:    print(item['src'])
Output:
https://media.geeksforgeeks.org/wp-content/cdn-uploads/20201018234700/GFG-RT-DSA-Creative.pnghttps://media.geeksforgeeks.org/wp-content/cdn-uploads/logo-new-2.svg
abhishek0719kadiyan
Python web-scraping-exercises
python-utility
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python