code-rag-bench/online-tutorials huggingface dataset:
Python Mongodb – Delete_one()

04 Jul, 2022
Mongodb is a very popular cross-platform document-oriented, NoSQL(stands for “not only SQL”) database program, written in C++. It stores data in JSON format(as key-value pairs), which makes it easy to use. MongoDB can run over multiple servers, balancing the load to keep the system up and run in case of hardware failure.
Step 1 – Establishing Connection: Port number Default: 27017  
conn = MongoClient(‘localhost’, port-number)
If using default port-number i.e. 27017. Alternate connection method: 
conn = MongoClient()
Step 2 – Create Database or Switch to Existing Database:  
db = conn.dabasename
Create a collection or Switch to an existing collection: 
collection = db.collection_name
In MongoDB, a single document can be deleted by the method delete_one(). The first parameter of the method would be a query object which defines the document to be deleted. If there are multiple documents matching the filter query, only the first appeared document would be deleted. 
Note: Deleting a document is the same as deleting a record in the case of SQL.
Consider the sample database: 
Examples:  
Python
# Python program to demonstrate# delete_one  import pymongo  # creating Mongoclient object to# create database with the specified# connection URLstudents = pymongo.MongoClient('localhost', 27017) # connecting to a database with# name GFGDb = students["GFG"] # connecting to a collection with# name Geekscoll = Db["Geeks"] # creating query objectmyQuery ={'Class':'2'}coll.delete_one(myQuery) # print collection after deletion:for x in coll.find():    print(x)
Output : 
'_id': 2.0, 'Name': 'Golu', 'Class': '3'}
{'_id': 3.0, 'Name': 'Raja', 'Class': '4'}
{'_id': 4.0, 'Name': 'Moni', 'Class': '5'}
MongoDB Shell: 
 
surinderdawra388
gabaa406
khushb99
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python script to shows Laptop Battery Percentage

29 Aug, 2020
psutil is a cross-platform library for retrieving information on running processes and system utilization(CPU, memory, disks, networks, sensors) in Python. The Python script below can be run in both Windows and Linux. Install psutil in windows by :
pip install psutil

Install psutil in Linux by:
sudo apt-get install gcc python3-dev
sudo pip3 install psutil

Code:
Python
# python script showing battery detailsimport psutil  # function returning time in hh:mm:ssdef convertTime(seconds):    minutes, seconds = divmod(seconds, 60)    hours, minutes = divmod(minutes, 60)    return "%d:%02d:%02d" % (hours, minutes, seconds)  # returns a tuplebattery = psutil.sensors_battery()  print("Battery percentage : ", battery.percent)print("Power plugged in : ", battery.power_plugged)  # converting seconds to hh:mm:ssprint("Battery left : ", convertTime(battery.secsleft))
Output:
Battery percentage :  57
Power plugged in :  False
Battery left :  1:58:32

Explanation:
psutil.sensors.battery() returns a named tuple consisting of following values. If no battery is installed or metrics can’t be determined None is returned.
percent: Power left in percentage.
secsleft: Approx seconds left before the power runs out. It is set to psutil.POWER_TIME_UNLIMITED if it is on charging. If this value can’t be determined it is set to psutil.POWER_TIME_UNKNOWN .
power_plugged: True if power is plugged in, False if it isn’t charging or None if it can’t be determined.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | replaceAll() with Examples

13 Feb, 2019
The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements.
Syntax:
$(content).replaceAll(selector)
Parameters: This method accepts two parameter as mentioned above and described below:
content: It is the required parameter which is used to specify the content to insert.
selector: It is required parameter which specify the elements to be replaced.
Return Value: This method return the selected elements with new content.
Below program illustrates the above function:
Program:
<!DOCTYPE html><html>    <head>        <title>The replaceAll Method</title>        <script src=        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">        </script>                  <!-- jQuery code to show the working of this method -->        <script>            $(document).ready(function() {                $("button").click(function() {                    $("<h1>GeeksforGeeks!</h1>").replaceAll("p");                    $("h1").css({"color":"green"});                });            });        </script>        <style>            div {                width: 60%;                height: 150px;                padding: 10px;                border: 2px solid green;                font-size: 20px;                text-align:center;            }            p {                font-size:25px;                font-weight:bold;            }        </style>    </head>    <body>        <div>            <p>Welcome to </p>                          <!-- click on this button and see the change -->            <button>Click Here!</button>            <br>        </div>    </body></html>
Output:
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
How to flip an image on hover using CSS ? - GeeksforGeeks

29 Jun, 2020
In this article, you will learn how to flip an image (add mirror effect), both horizontally and vertically when the mouse has hovered over it. This can be done by applying the transformation to the image as shown in the following example:
Example 1: This example represents how to flip image horizontally by transforming it along the X-axis using transform: scaleX(-1) property.
<!DOCTYPE html><html>  <head>    <style>        img:hover{            transform: scaleX(-1);        }    </style></head>  <body>    <h2>GeeksforGeeks</h2>    <img src="gfg.jpg" width="50%"></body>  </html>
Output:
Example 2: This example represents how to flip image vertically by transforming it along the Y-axis using transform: scaleY(-1) property.
<!DOCTYPE html><html>  <head>    <style>        img:hover{            transform: scaleY(-1);        }    </style></head>  <body>    <h2>GeeksforGeeks</h2>    <img src="gfg.jpg" width="50%"></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
How to see the extensions loaded by PHP ? - GeeksforGeeks

11 Oct, 2019
To see all the extensions loaded by PHP, firstly we must be sure that PHP is successfully installed in our system. After that, we can use any of the following approaches to see the loaded extension list.
Approach 1: In this approach, we will use command line to check all the loaded PHP extensions.Open Terminal or Command Line Interface and type the following command and hit enter.
php -m
It will display the list of all the loaded PHP extensions.
Approach 2: This approach uses get_loaded_extensions() function to display the list of all the loaded PHP extensions.
Example:
<?php print_r(get_loaded_extensions());?> 
Output:
Note: Please note that the list of the extension might vary from system to system.
Picked
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
How to create admin login page using PHP?
How to Install php-curl in Ubuntu ?
How to limit Decimal Places in Android EditText?

This example demonstrates about How to limit Decimal Places in Android EditText.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <EditText
      android:hint="Enter decimal numbers"
      android:id="@+id/etText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="16dp"
      android:inputType="numberDecimal" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      EditText etText = findViewById(R.id.etText);
      etText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(5, 2)});
   }
}
class DecimalDigitsInputFilter implements InputFilter {
   private Pattern mPattern;
   DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
      mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
   }
   @Override
   public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
      Matcher matcher = mPattern.matcher(dest);
      if (!matcher.matches())
      return "";
      return null;
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Python program to convert int to exponential - GeeksforGeeks

05 Jan, 2022
Given a number of int type, the task is to write a Python program to convert it to exponential.
Examples:
Input: 19
Output: 1.900000e+01

Input: 2002
Output: 2.002000e+03

Input: 110102
Output: 1.101020e+05
Approach:
We will first declare and initialise an integer number
Then we will use format method to convert the number from integer to exponential type.
Then we will print the converted value.
Syntax:
String {field_name:conversion} Example.format(value)
Errors and Exceptions:
ValueError: Error occurs during type conversion in this method.
More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.
Example:
Python3
# Python program to convert int to exponential # Declaring the integer numberint_number = 110102 # Converting the integer number to exponential numberexp_number = "{:e}".format(int_number) # Printing the converted numberprint("Integer Number:",int_number)print("Exponent Number:",exp_number)
  
Output:
 
Integer Number: 110102
Exponent Number: 1.101020e+05
 
clintra
Python-datatype
Technical Scripter 2020
Python
Python Programs
Technical Scripter
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
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?
Data Structures | Binary Search Trees | Question 12 - GeeksforGeeks

28 Jun, 2021
Consider the following code snippet in C. The function print() receives root of a Binary Search Tree (BST) and a positive integer k as arguments.
// A BST nodestruct node {    int data;    struct node *left, *right;};  int count = 0;  void print(struct node *root, int k){    if (root != NULL && count <= k)    {        print(root->right, k);        count++;        if (count == k)          printf("%d ", root->data);       print(root->left, k);    }}
What is the output of print(root, 3) where root represent root of the following BST.
                   15
                /     \
              10      20
             / \     /  \
            8  12   16  25   

(A) 10(B) 16(C) 20(D) 20 10Answer: (B)Explanation: The code mainly finds out k’th largest element in BST, see K’th Largest Element in BST for details.Quiz of this Question
Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count number of times each Edge appears in all possible paths of a given Tree
Data Structures | Linked List | Question 5
Data Structures | Tree Traversals | Question 4
Data Structures | Linked List | Question 6
Advantages and Disadvantages of Linked List
FIFO vs LIFO approach in Programming
Data Structures | Graph | Question 9
Introduction to Data Structures
Data Structures | Stack | Question 1
Binary Search Tree | Set 3 (Iterative Delete)
RxJS - Transformation Operator mergeMap

In the case of mergeMap operator a project function is applied on each source value and the output of it is merged with the output Observable.
mergeMap(project_func: function): Observable

project_func − It takes in project_func as the argument which is applied to all the values of source observable.
It returns an Observable that has values based on the project_func applied on each value of source observable.
import { of} from 'rxjs';
import { mergeMap, map } from 'rxjs/operators';

let text = of('Welcome To');
let case1 = text.pipe(mergeMap((value) => of(value + ' Tutorialspoint!')));
case1.subscribe((value) => {console.log(value);});

    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
How to add items in a JComboBox on runtime in Java

The following is an example to add items on runtime on a JComboBox in Java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JComboBox<String> combo = new JComboBox<>(new String[] { "One","Two", "Three","Four","Five", "Six" });
      JButton add = new JButton("Add");
      add.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            combo.addItem("New");
         }
      });
      frame.add(combo);
      frame.add(add, BorderLayout.NORTH);
      frame.setSize(500, 100);
      frame.setVisible(true);
   }
}
Now, we have the following items:
Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:
How to move a Tkinter canvas with Mouse?

Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can move images in a particular direction on the Canvas widget using the move() method.
Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the object in the Canvas. We declare images globally in order to move or change the position.
We can follow these steps to allow our image to move within the canvas,
First, define the Canvas widget and add images to it.
First, define the Canvas widget and add images to it.
Define the move() function to allow the image to be dynamic within the Canvas.
Define the move() function to allow the image to be dynamic within the Canvas.
Bind the mouse buttons with the function that allows images to be moved within the Canvas.
Bind the mouse buttons with the function that allows images to be moved within the Canvas.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)

# Add Images to Canvas widget
image = ImageTk.PhotoImage(Image.open('logo.png'))
img = canvas.create_image(250, 120, anchor=NW, image=image)

def left(e):
   x = -20
   y = 0
   canvas.move(img, x, y)

def right(e):
   x = 20
   y = 0
   canvas.move(img, x, y)

def up(e):
   x = 0
   y = -20
   canvas.move(img, x, y)

def down(e):
   x = 0
   y = 20
   canvas.move(img, x, y)

# Define a function to allow the image to move within the canvas
def move(e):
   global image
   image = ImageTk.PhotoImage(Image.open('logo.png'))
   img = canvas.create_image(e.x, e.y, image=image)

# Bind the move function
canvas.bind("<B1-Motion>", move)

win.mainloop()
Running the above code will display a window that contains an image that can be moved across the window using the mouse buttons.
Now, click on the Canvas and drag the object around with your mouse.
How to get file character encoding in Node.js ? - GeeksforGeeks

13 Apr, 2021
Computer reads data in binary representation, that is why we need a way to convert text characters into binary data, this is done with the help of character encoding.
Most popular character encoding types are ASCII and Unicode. Unicode is defined as UTF-8, UTF-16, etc.
We can use a module called ‘detect-file-encoding-and-language‘ to get the character encoding of file in node.js
Syntax:
languageEncoding(pathToFile).then(
    fileInfo => // Do anything
);
Parameters:
pathToFile: (Relative or Absolute)Path of the actual file.
Return Value:
An Object having following values, { language: french, encoding: CP1252, confidence: 0.99 }
Setting up environment and Execution:
Step 1: Initialize node.js project
npm init
Step 2: Install required modules
npm install detect-file-encoding-and-language
Step 3: Create a text file
Filename- a.txt
Geeks for Geeks
Step 4: Code in index.js file
index.js
import languageEncoding from "detect-file-encoding-and-language"  const pathToFile = "./a.txt"  languageEncoding(pathToFile)    .then(fileInfo => console.log(fileInfo.encoding))    .catch(err => console.log(err));
Step 5: Run index.js File
node index.js
Output: See output in console
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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
Extract all integers from the given string in Java - GeeksforGeeks

14 Oct, 2019
Given a string str consisting of digits, alphabets and special characters. The task is to extract all the integers from the given string.
Examples:
Input: str = “geeksforgeeks A-118, Sector-136, Uttar Pradesh-201305”Output: 118 136 201305
Input: str = ” 1abc35de 99fgh, dd11′′Output: 1 35 99 11
Approach:
Replace all the non-digit characters with spaces (” “).
Now replace every consecutive group of spaces with a single space.
Eliminate the leading and the trailing spaces (if any) and the final string will only contain the required integers.
Below is the implementation of the above approach:
// Java implementation of the approachpublic class GFG {      // Function to return the modified string    static String extractInt(String str)    {        // Replacing every non-digit number        // with a space(" ")        str = str.replaceAll("[^\\d]", " ");          // Remove extra spaces from the beginning        // and the ending of the string        str = str.trim();          // Replace all the consecutive white        // spaces with a single space        str = str.replaceAll(" +", " ");          if (str.equals(""))            return "-1";          return str;    }      // Driver code    public static void main(String[] args)    {        String str = "avbkjd1122klj4 543 af";        System.out.print(extractInt(str));    }}
1122 4 543

Java
Java Programs
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How do I loop through a JSON file with multiple keys/sub-keys in Python?

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −
{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}
You can load it in your python program and loop over its keys in the following way −
import json
f = open('data.json')
data = json.load(f)
f.close()
# Now you can use data as a normal dict −
for (k, v) in data.items():
   print("Key: " + k)
   print("Value: " + str(v))
This will give the output −
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
If you want to iterate over sub values as well, you'd have to write a recursive function that can iterate over this tree-like dict.
C/C++ Program to Count set bits in an integer - GeeksforGeeks

02 Jan, 2019
Write an efficient program to count number of 1s in binary representation of an integer.
Examples :
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits

1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program.
C
#include <stdio.h>  /* Function to get no of set bits in binary   representation of positive integer n */unsigned int countSetBits(unsigned int n){    unsigned int count = 0;    while (n) {        count += n & 1;        n >>= 1;    }    return count;}  /* Program to test function countSetBits */int main(){    int i = 9;    printf("%d", countSetBits(i));    return 0;}
2

Recursive Approach :
C++
// Cpp implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n#include <bits/stdc++.h>using namespace std;  // recursive function to count set bitsint countSetBits(int n){    // base case    if (n == 0)        return 0;      else          // if last bit set add 1 else add 0        return (n & 1) + countSetBits(n >> 1);}  // driver codeint main(){    // get value from user    int n = 9;      // function calling    cout << countSetBits(n);      return 0;}  // This code is contributed by Raj.
2

Please refer complete article on Count set bits in an integer for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
time() function in C
Flex (Fast Lexical Analyzer Generator )
C Program to Swap two Numbers
java.util.regex.Pattern.matches() Method

The java.util.regex.Pattern.matches(String regex, CharSequence input) method compiles the given regular expression and attempts to match the given input against it.
Following is the declaration for java.util.regex.Pattern.matches(String regex, CharSequence input) method.
public static boolean matches(String regex, CharSequence input)

regex − The expression to be compiled.
regex − The expression to be compiled.
input − The character sequence to be matched.
input − The character sequence to be matched.
PatternSyntaxException − If the expression's syntax is invalid.
PatternSyntaxException − If the expression's syntax is invalid.
The following example shows the usage of java.util.regex.Pattern.matches(String regex, CharSequence input) method.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "foo*";
   private static final String INPUT = "fooooooooooooooooo";

   public static void main( String args[] ) {
      System.out.println("Current REGEX is: "+REGEX);
      System.out.println("Current INPUT is: "+INPUT);
      System.out.println("matches(): "+Pattern.matches(REGEX,INPUT));
   }
}
Let us compile and run the above program, this will produce the following result −
Current REGEX is: foo*
Current INPUT is: fooooooooooooooooo
matches(): true

 Print
 Add Notes
 Bookmark this page
HTML - <dt> Tag

The HTML <dt> tag is used to define the start of a term in a definition list.
A definition list is similar to other lists but in a definition list, each list item contains two entries; a term and a description.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML dt Tag</title>
   </head>

   <body>
      <dl>
         <dt>Definition List</dt>
         <dd>A list of terms and their definitions/descriptions.</dd>
         <dt>JAVA</dt>
         <dd>Tutorial on JAVA Programming Language.</dd>
         <dt>Android</dt>
         <dd>Tutorial on Android Operating System.</dd>
      </dl>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
This tag supports all the event attributes described in HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Perl unshift Function

This function places the elements from LIST, in order, at the beginning of ARRAY. This is opposite function to shift().
Following is the simple syntax for this function −
unshift ARRAY, LIST

This function returns the number of new elements in ARRAY.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

@array  = ( 1, 2, 3, 4);

print "Value of array is @array\n" ;

unshift( @array, 20, 30, 40 );

print "Now value of array is @array\n" ;
When above code is executed, it produces the following result −
Value of array is 1 2 3 4
Now value of array is 20 30 40 1 2 3 4


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Java Examples - Create a frame

How to display a message in a new frame?
Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this frame.
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setFont(new Font("Serif", Font.PLAIN, 48));
      paintHorizontallyCenteredText(g2, "Java Source", 200, 75);
      paintHorizontallyCenteredText(g2, "and", 200, 125);
      paintHorizontallyCenteredText(g2, "Support", 200, 175);
   }
   protected void paintHorizontallyCenteredText(
      Graphics2D g2, String s, float centerX, float baselineY) {
      
      FontRenderContext frc = g2.getFontRenderContext();
      Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
      float width = (float) bounds.getWidth();
      g2.drawString(s, centerX - width / 2, baselineY);
   }
   public static void main(String[] args) {
      JFrame f = new JFrame();
      f.getContentPane().add(new Main());
      f.setSize(450, 350);
      f.setVisible(true);
   }
}
The above code sample will produce the following result.
JAVA and J2EE displayed in a new Frame.

The following is an example to display a message in a new frame.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;

public class Main {
   public static void main(String[] args) {
      Frame f = new Frame("Tutorialspoint");
      Component text = new TextArea("Sairamkrishna Mamamahe");
      Component button = new Button("Button");
      f.add(text, BorderLayout.NORTH);
      f.add(button, BorderLayout.SOUTH);
      int width = 300;
      int height = 300;
      f.setSize(width, height);
      f.setVisible(true);
   } 
}
 Print
 Add Notes
 Bookmark this page
Currency Converter in Python - GeeksforGeeks

12 Dec, 2019
Python is a very versatile programming language. Python is being used in almost each mainstream technology and one can develop literally any application with it. Let’s see a Python program to convert the currency of one country to that of another country. To use this service, one must need the API key, which can be get form here.We will use fixer API to get the live conversion rates and convert the corresponding amount.
requests: This module does not built-in with python. To install it type the below command in the terminal or cmd.
pip install requests

Below is the implementation:
# Python program to convert the currency# of one country to that of another country   # Import the modules neededimport requests  class Currency_convertor:    # empty dict to store the conversion rates    rates = {}     def __init__(self, url):        data = requests.get(url).json()          # Extracting only the rates from the json data        self.rates = data["rates"]       # function to do a simple cross multiplication between     # the amount and the conversion rates    def convert(self, from_currency, to_currency, amount):        initial_amount = amount        if from_currency != 'EUR' :            amount = amount / self.rates[from_currency]          # limiting the precision to 2 decimal places        amount = round(amount * self.rates[to_currency], 2)        print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))  # Driver codeif __name__ == "__main__":      # YOUR_ACCESS_KEY = 'GET YOUR ACCESS KEY FROM fixer.io'    url = str.__add__('http://data.fixer.io/api/latest?access_key=', YOUR_ACCESS_KEY)      c = Currency_convertor(url)    from_country = input("From Country: ")    to_country = input("TO Country: ")    amount = int(input("Amount: "))      c.convert(from_country, to_country, amount)
Input :
From Country: USD 
TO Country: INR 
Amount: 1 

Output :
1 USD = 70.69 INR

python-utility
Python
Technical Scripter
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
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
Convert integer to string in Python
Stack in Python
How to Add Cookies in Postman?

We can add cookies in Postman. To add a cookie, the below steps need to be followed −
Step1 − Navigate to the Params tab below the address bar and then click on Cookies.
Step2 − The MANAGE COOKIES window shall open. It lists down all the current cookies. To add a cookie, click on the Add Cookie button. An edit box with pre-populated values of the cookie are displayed. We can update the value and Save it.
Step3 − Send the request to the server.
Step4 − After the request has been successfully completed, the Cookies tab in the Response will show the newly added cookie – Cookie_Postman.
We can also add a cookie programmatically and not from the GUI. For that, we have to first create a Cookie jar object with the help of the pm.cookies.jar method.
const cnt = pm.cookies.jar()
Then to create a cookie we have to use the function - .set. This function takes the URL, cookie name and value as parameters.
const cnt = pm.cookies.jar();
cnt.set(URL, cookie name, cookie value, callback(error, cookie))
Instruction type ANA R in 8085 Microprocessor

In 8085 Instruction set, ANA is a mnemonic, which stands for “ANd Accumulator” and “R” stands for any one of the following registers, or memory location M pointed by HL pair.
R = A, B, C, D, E, H, L, or M

This instruction is used to AND contents of R with Accumulator’s content. The result thus produced for this AND operation will be stored back in to the Accumulator over writing its previous content. As R can have any of the eight values, there are eight opcodes for this type of instruction. It occupies only 1-Byte in memory.
Let us consider ANA E is an example instruction of this type. As it is a 1-Byte instruction so in memory only a single Byte will get allocated for it during execution. Let us consider the initial content of Accumulator is ABH and register E is CDH. So after The result of execution of this instruction has been depicted in the following tracing table −
(E)
(A)
(F)
The internal calculation will be done as shown below −
(A) ABH ---> 1010 1011
(d8) CDH ---> 1100 1101
              ---------
      ANA E ---> 1000 1001 (89H)

The timing diagram against this instruction ANA E execution is as follows −
Summary − So this instruction ANA E requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
How to modify a const variable in C? - GeeksforGeeks

05 Sep, 2018
Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: “assignment of read-only variable”.
In the below program, a read-only variable declared using the const qualifier is tried to modify:
#include<stdio.h>int main(){    const int var = 10;    var = 15;    printf("var = %d\n", var);    return 0;}
Output:
prog.c: In function 'main':
prog.c:5:9: error: assignment of read-only variable 'var'

Changing Value of a const variable through pointer
The variables declared using const keyword, get stored in .rodata segment, but we can still access the variable through the pointer and change the value of that variable. By assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier. Compiler optimization is different for variables and pointers. That is why we are able to change the value of a constant variable through a non-constant pointer.
Below program illustrates this:
//Write C code here#include<stdio.h>#include<stdlib.h>int main(){    const int var = 10;      int *ptr = &var;    *ptr = 12;      printf("var = %d\n", var);      return 0;}
Output:
prog.c: In function 'main':
prog.c:6:16: warning: initialization discards 'const' qualifier 
from pointer target type [-Wdiscarded-qualifiers]
     int *ptr = &var;
var = 12

Note: If we try to change the value through constant pointer then we will get an error because we are trying to change the read-only segment.
C++-const keyword
C-Pointers
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
UDP Server-Client implementation in C
Understanding "extern" keyword in C
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
How to split a string in C/C++, Python and Java?
How to fetch a property value dynamically in C#?

We can make use of Reflection to fetch a property value dynamically.
Reflection provides objects (of type Type) that describe assemblies, modules and types. We can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If we use attributes in our code, reflection enables us to access them.
The System.Reflection namespace and System.Type class play an important role in .NET Reflection. These two works together and allows us to reflect over many other aspects of a type.
 Live Demo
using System;
using System.Text;
   namespace DemoApplication {
      public class Program {
         static void Main(string[] args) {
            var employeeType = typeof(Employee);
            var employee = Activator.CreateInstance(employeeType);
            SetPropertyValue(employeeType, "EmployeeId", employee, 1);
            SetPropertyValue(employeeType, "EmployeeName", employee, "Mark");
            GetPropertyValue(employeeType, "EmployeeId", employee);
            GetPropertyValue(employeeType, "EmployeeName", employee);
            Console.ReadLine();
         }
         static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) {
            type.GetProperty(propertyName).SetValue(instanceObject, value);
         }
         static void GetPropertyValue(Type type, string propertyName, object instanceObject) {
            Console.WriteLine($"Value of Property {propertyName}:                   {type.GetProperty(propertyName).GetValue(instanceObject, null)}");
         }
      }
      public class Employee {
         public int EmployeeId { get; set; }
         public string EmployeeName { get; set; }
      }
   }
The output of the above code is
Value of Property EmployeeId: 1
Value of Property EmployeeName: Mark
In the above example we could see that the Employee properties values are set using Reflection by getting the type and property name. Similarly for fetching the property value we have used GetProperty() method of the Reflection class. By using this we can fetch the value of any property during the runtime.
JavaScript Number - toLocaleString()

This method converts a number object into a human readable string representing the number using the locale of the environment.
Its syntax is as follows −
number.toLocaleString()

Returns a human readable string representing the number using the locale of the environment.
Try the following example.
<html>
   <head>
      <title>JavaScript toLocaleString() Method </title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var num = new Number(177.1234);
         document.write( num.toLocaleString()); 
      </script>   
   </body>
</html>
177.1234


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: width and height attributes
Python | Character Encoding - GeeksforGeeks

29 May, 2021
Finding the text which is having nonstandard character encoding is a very common step to perform in text processing. All the text would have been from utf-8 or ASCII encoding ideally but this might not be the case always. So, in such cases when the encoding is not known, such non-encoded text has to be detected and the be converted to a standard encoding. So, this step is important before processing the text further. Charade Installation : For performing the detection and conversion of encoding, charade – a Python library is required. This module can be simply installed using sudo easy_install charade or pip install charade. Let’s see the wrapper function around the charade module. Code : encoding.detect(string), to detect the encoding  
Python3
# -*- coding: utf-8 -*- import charadedef detect(s):         try:        # check it in the charade list        if isinstance(s, str):            return charade.detect(s.encode())        # detecting the string          else:            return charade.detect(s)         # in case of error    # encode with 'utf -8' encoding    except UnicodeDecodeError:        return charade.detect(s.encode('utf-8'))
The detect functions will return 2 attributes :  
Confidence : the probability of charade being correct.
Encoding   : which encoding it is. 
Code : encoding.convert(string) to convert the encoding. 
Python3
# -*- coding: utf-8 -*-import charade def convert(s):         # if in the charade instance    if isinstance(s, str):        s = s.encode()         # retrieving the encoding information    # from the detect() output    encode = detect(s)['encoding']         if encode == 'utf-8':        return s.decode()    else:        return s.decode(encoding)
Code : Example  
Python3
# importing libraryimport encoding d1  = encoding.detect('geek')print ("d1 is encoded as  : ", d1) d2  = encoding.detect('ascii')print ("d2 is encoded as  : ", d2)
Output :  
d1 is encoded as : (confidence': 0.505, 'encoding': 'utf-8')
d2 is encoded as : ('confidence': 1.0, 'encoding': 'ascii')
detect() : It is a charade.detect() wrapper. It encodes the strings and handles the UnicodeDecodeError exceptions. It expects a bytes object so therefore the string is encoded before trying to detect the encoding.convert() : It is a charade.convert() wrapper. It calls detect() first to get the encoding. Then, it returns a decoded string. 
nidhi_biet
sumitgumber28
Natural-language-processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to sort an ArrayList in Descending Order in Java - GeeksforGeeks

11 Dec, 2018
Given an unsorted ArrayList, the task is to sort this ArrayList in descending order in Java.
Examples:
Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]Output: Sorted ArrayList: [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal]
Input: Unsorted ArrayList: [Geeks, For, ForGeeks]Output: Sorted ArrayList: [Geeks, ForGeeks, For]
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted and Collections.reverseOrder() as the parameter and returns a Collection sorted in the Descending Order. Collections.reverseOrder() acts as the comparator in this method.
Syntax:
Collections.sort(ArrayList, Collections.reverseOrder());
Below is the implementation of the above approach:
// Java program to demonstrate// How to sort ArrayList in descending order  import java.util.*;  public class GFG {    public static void main(String args[])    {          // Get the ArrayList        ArrayList<String>            list = new ArrayList<String>();          // Populate the ArrayList        list.add("Geeks");        list.add("For");        list.add("ForGeeks");        list.add("GeeksForGeeks");        list.add("A computer portal");          // Print the unsorted ArrayList        System.out.println("Unsorted ArrayList: "                           + list);          // Sorting ArrayList in descending Order        // using Collection.sort() method        // by passing Collections.reverseOrder() as comparator        Collections.sort(list, Collections.reverseOrder());          // Print the sorted ArrayList        System.out.println("Sorted ArrayList "                           + "in Descending order : "                           + list);    }}
Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Sorted ArrayList in Descending order : [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal]

Java - util package
Java-ArrayList
Java-Collections
Java-List-Programs
Sorting Quiz
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java