code-rag-bench/online-tutorials huggingface dataset:
How to find if element exists in document - MongoDB?

To find if element exists in a MongoDB document, use MongoDB $exists. Let us create a
collection with documents −
> db.demo497.insertOne({"details":[{"Name":"Chris"},{"Name":"Bob"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84b3cfb0f3fa88e22790d1")
}
> db.demo497.insertOne({"details":[{"Name":"Carol"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84b3d9b0f3fa88e22790d2")
}
> db.demo497.insertOne({"details":[{}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84b3e9b0f3fa88e22790d3")
}
Display all documents from a collection with the help of find() method −
> db.demo497.find();
This will produce the following output −
{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3d9b0f3fa88e22790d2"), "details" : [ { "Name" : "Carol" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }
Following is the query to find if element exists in a document −
> db.demo497.find({$or:[
...       {"details.Name" : {$ne : "Carol"}},
...       {details: {$exists: false}}
...    ]
... });
This will produce the following output −
{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }
Sublime Text - Command Palette

Command Palette includes a list of items or commands which are used frequently. The entries of commands are included in the .sublime-commands file.
To open a command palette in Sublime Text editor, you can use the shortcut key combination Ctrl+Shift+P on Windows and Cmd+Shift+P on OSX.
The commonly used commands from the palette are −
Build with Python
Install Packages
This will generate all the dependencies and build the specified code of a given Python file.
With this command, we get list of packages which can be installed which is not included earlier.
All the commands included in the command palette are stored in the Packages directory. The basic example of command declared inside the Default.sublime-commands file is shown in the code given below −
[
   { "caption": "Project: Save As", "command": "save_project_as" },
   
   { "caption": "Project: Close", "command": "close_project" },
   
   { "caption": "Project: Add Folder", "command": "prompt_add_folder" },
]
Note − The JSON file includes 3 main keys for every command −
Name/Caption
Location
Content
 Print
 Add Notes
 Bookmark this page
Impala - With Clause

In case a query is way too complex, we can define aliases to complex parts and include them in the query using the with clause of Impala.
Following is the syntax of the with clause in Impala.
with x as (select 1), y as (select 2) (select * from x union y);

Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 9  | robert   | 23  | banglore  | 28000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 7  | ram      | 25  | chennai   | 23000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
| 8  | ram      | 22  | vizag     | 31000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
+----+----------+-----+-----------+--------+ 
Fetched 9 row(s) in 0.59s

In the same way, suppose we have another table named employee and its contents are as follows −
[quickstart.cloudera:21000] > select * from employee; 
Query: select * from employee 
+----+---------+-----+---------+--------+ 
| id | name    | age | address | salary | 
+----+---------+-----+---------+--------+ 
| 3  | mahesh  | 54  | Chennai | 55000  | 
| 2  | ramesh  | 44  | Chennai | 50000  | 
| 4  | Rupesh  | 64  | Delhi   | 60000  | 
| 1  | subhash | 34  | Delhi   | 40000  | 
+----+---------+-----+---------+--------+ 
Fetched 4 row(s) in 0.59s

Following is an example of the with clause in Impala. In this example, we are displaying the records from both employee and customers whose age is greater than 25 using with clause.
[quickstart.cloudera:21000] > 
   with t1 as (select * from customers where age>25), 
   t2 as (select * from employee where age>25) 
   (select * from t1 union select * from t2);

On executing, the above query gives the following output.
Query: with t1 as (select * from customers where age>25), t2 as (select * from employee where age>25) 
   (select * from t1 union select * from t2)
+----+---------+-----+-----------+--------+ 
| id | name    | age | address   | salary | 
+----+---------+-----+-----------+--------+ 
| 3  | mahesh  | 54  | Chennai   | 55000  | 
| 1  | subhash | 34  | Delhi     | 40000  | 
| 2  | ramesh  | 44  | Chennai   | 50000  | 
| 5  | Hardik  | 27  | Bhopal    | 40000  | 
| 4  | Rupesh  | 64  | Delhi     | 60000  | 
| 1  | Ramesh  | 32  | Ahmedabad | 20000  | 
+----+---------+-----+-----------+--------+ 
Fetched 6 row(s) in 1.73s

 Print
 Add Notes
 Bookmark this page
Generate Random bytes in Java

In order to generate random bytes in Java, we use the nextBytes() method. The java.util.Random.nextBytes() method generates random bytes and provides it to the user defined byte array.
Declaration − The java.util.Random.nextBytes() method is declared as follows −
public void nextBytes(byte[] bytes)
where bytes is the byte array.
Let us see a program to generate random bytes in Java −
 Live Demo
import java.util.Random;
public class Example {
   public static void main(String[] args) {
      Random rd = new Random();
      byte[] arr = new byte[7];
      rd.nextBytes(arr);
      System.out.println(arr);
   }
}
[B@15db9742
Note − The output might vary on Online Compilers.
Ruby - String split() Method with Examples - GeeksforGeeks

03 Jul, 2020
split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified.
Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.
Syntax:
arr = str.split(pattern, limit) public
Parameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array.
Returns: Array of strings based on the parameters.
Example 1:
# Ruby program to demonstrate split method   # Split without parameters# Here the pattern is a # single whitespacemyArray = "Geeks For Geeks".splitputs myArray
Output:
Geeks
For
Geeks
Example 2:
# Ruby program to demonstrate split method  # Here pattern is a regular expression# limit value is 2# / / is one white spacemyArray = "Geeks For Geeks".split(/ /, 2)puts myArray
Output:
Geeks
For Geeks
Example 3:
# Ruby program to demonstrate split method  # Here the pattern is a regular expression# limit value is -1# if the limit is negative there is no # limit to the number of fields returned,# and trailing null fields are not # suppressed.myArray = "geeks geeks".split('s', -1)puts myArray
Output:
geek
 geek
Ruby-Methods
Ruby-String
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Ruby | Numeric round() function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Why do we use re.compile() method in Python regular expression?

re.compile(pattern, repl, string):
 We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.
import re
pattern=re.compile('TP')
result=pattern.findall('TP Tutorialspoint TP')
print result
result2=pattern.findall('TP is most popular tutorials site of India')
print result2
['TP', 'TP']
['TP']
Check if value is empty in JavaScript

Use the condition with “” and NULL to check if value is empty. Throw a message whenever ua ser does not fill the text box value.
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form name="register" onsubmit="return checkingUserName()">
USERNAME: <input type="text" name="username">
<input type="submit" value="Save">
</form>
<script>
   function checkingUserName() {
      var username = document.forms["register"]["username"].value;
      if (username == null || username == "") {
         alert("Please enter> the username. Can’t be blank or empty !!!");
         return false;
      }
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
On clicking the Save button, you will get the following alert along with a message −
How do I change the background of a Frame in Tkinter?

In order to change the background color and foreground color of a tkinter frame, we can assign different values to the bg and fg parameters in the Frame function.
In this example, we have created two frames with different background colors.
#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("650x250")

#Create an frame
frame1= Frame(win, bg= "red")
frame2= Frame(win, bg="black")

#Create an label inside the frame
Label(frame2, text= "Line:1", font=('Lucida font',20)).pack(pady=20)
Label(frame1, text= "Line:2", font=('Lucida font',20)).pack(pady=20)

frame1.pack()
frame2.pack()

win.mainloop()
Running the above code will display a window containing two frames with different background colors.
How to find the position of a data frame’s column value based on a column value of another data frame in R?

In data analysis, we encounter many problems with a lot of variations among them. One such problem is we have some information in a place that needs to be checked through a different place and these places can be data frames. Therefore, we need to find the position of a data frame’s column value based on a column value of another data frame. In R, we can easily do it with the help of which function.
 Live Demo
Consider the below data frame −
set.seed(12121)
x1<−sample(0:2,20,replace=TRUE)
y1<−sample(0:5,20,replace=TRUE)
df1<−data.frame(x1,y1)
df1
x1 y1
1 0 3
2 2 2
3 0 2
4 1 4
5 0 4
6 2 0
7 0 3
8 0 1
9 2 5
10 1 0
11 0 1
12 1 1
13 0 3
14 0 0
15 2 0
16 1 5
17 0 2
18 2 0
19 1 4
20 0 5
x2<−sample(1:2,20,replace=TRUE)
y2<−sample(1:5,20,replace=TRUE)
df2<−data.frame(x2,y2)
df2
x2 y2
1 1 2
2 1 2
3 1 2
4 2 4
5 2 3
6 1 4
7 2 1
8 2 3
9 1 2
10 1 5
11 1 2
12 2 2
13 2 1
14 2 5
15 1 2
16 1 3
17 2 2
18 2 1
19 1 1
20 1 3
Finding the position of x1 of df1 in x2 of df2 −
which(df1$x1 %in% df2$x2)
[1] 2 4 6 9 10 12 15 16 18 19
Finding the position of y1 of df1 in y2 of df2 −
which(df1$y1 %in% df2$y2)
[1] 1 2 3 4 5 7 8 9 11 12 13 16 17 19 20
Let’s have a look at another example −
x3<−sample(21:25,20,replace=TRUE)
y3<−sample(26:50,20)
df3<−data.frame(x3,y3)
df3
   x3 y3
1 21 39
2 24 36
3 24 31
4 22 46
5 25 27
6 24 29
7 24 30
8 23 26
9 24 45
10 22 37
11 23 35
12 23 43
13 22 38
14 22 32
15 25 49
16 23 44
17 24 34
18 21 40
19 21 47
20 25 42
 Live Demo
x4<−sample(24:25,20,replace=TRUE)
y4<−sample(41:50,20,replace=TRUE)
df4<−data.frame(x4,y4)
df4
   x4 y4
1 25 50
2 24 44
3 24 45
4 25 49
5 24 42
6 25 48
7 25 43
8 25 47
9 24 50
10 25 41
11 25 47
12 25 50
13 24 46
14 25 50
15 24 42
16 24 42
17 24 50
18 25 47
19 25 42
20 25 41
which(df3$x3 %in% df4$x4)
[1] 2 3 5 6 7 9 15 17 20
which(df3$y3 %in% df4$y4)
[1] 4 9 12 15 16 19 20
java.time.LocalDateTime.minusHours() Method Example

The java.time.LocalDateTime.minusHours(long hoursToSubtract) method returns a copy of this LocalDateTime with the specified hours subtracted.
Following is the declaration for java.time.LocalDateTime.minusHours(long hoursToSubtract) method.
public LocalDateTime minusHours(long hoursToSubtract)

hoursToSubtract − the hours to subtract, may be negative.
a LocalDateTime based on this date-time with the hours subtracted, not null.
DateTimeException − if the result exceeds the supported date range.
The following example shows the usage of java.time.LocalDateTime.minusHours(long hoursToSubtract) method.
package com.tutorialspoint;

import java.time.LocalDateTime;

public class LocalDateTimeDemo {
   public static void main(String[] args) {
 
      LocalDateTime date = LocalDateTime.parse("2017-02-03T12:30:30");
      System.out.println(date.minusHours(2));  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T10:30:30

 Print
 Add Notes
 Bookmark this page
Material Icons

Google  provides a set of 750 icons designed under "material design guidelines" and these are known as Material Design icons. These icons are simple and they support all modern web browsers. Since these icons are vector based, they are scalable as well. To use these icons, we have to load the font (library) material-icons.
To load the material-icons library, copy and paste the following line in the <head> section of a webpage.
<head>
   <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
</head>
Google's Material Icons provides a long list of icons. Choose any one of them and add the name of the icon class to any HTML element within the < body > tag. In the following example, we have used the icon named accessibility that belongs to the action category.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
   </head>
	
   <body>
      <i class = "material-icons">accessibility</i>
   </body>
	
</html>
It will produce the following output −
You can increase or decrease the size of an icon by defining its size in the CSS and using it along with the class name as shown below. In the following example, we have declared the size as 6 em.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
		
      <style>
         i.mysize {font-size: 6em;}
      </style>
		
   </head>
	
   <body>
      <i class = "material-icons mysize">accessibility</i>
   </body>
	
</html>
It will produce the following output −
You can use the CSS to define the color of an icon. The following example shows how you can change the color of an icon called accessibility.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
		
      <style>
         i.custom {font-size: 6em; color: green;}
      </style>
		
   </head>
	
   <body>
      <i class = "material-icons custom">accessibility</i>
   </body>
	
</html>
It will produce the following output −
Google's Material Icons font provides 519 icons in the following categories −
Action Icons
Alert Icons
AV Icons
Communication Icons
Content Icons
Device Icons
Editor Icons
File Icons
Hardware Icons
Image Icons
Maps Icons
Navigation Icons
Notification Icons
Social Icons
Toggle Icons
To use any of these icons, you have to replace the class name in the programs given in this chapter with the class name of the desired icon. In the coming chapters of this Unit (Material Icons), we have explained category-wise the usage and the respective outputs of various Material Icons.

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Arithmetic operations using OpenCV in Python

In this tutorial, we are going to perform arithmetic operations on images using OpenCV in Python. We need to install the OpenCV module.
Run the following command to install the OpenCV module.
pip install opencv-python==4.1.1.26
If you run the above command, you will get the following successful message.
Collecting opencv-python==4.1.1.26
Downloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e0
6221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.w
hl (39.0MB)
Requirement already satisfied: numpy>=1.14.5 in c:\users\hafeezulkareem\anaconda3\l
ib\site-packages (from opencv-python==4.1.1.26) (1.16.2)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.1.1.26
We need two images for the addition. We have a method called cv2.add(image_one,
image_two) to perform addition. It's very hand method. The sizes of the two images must be the same. Let's see the images.
Image One
Image two
Let's see the code.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_one.jpg')
image_two = cv2.imread('_two.jpg')
# adding two images
result_image = cv2.add(image_one, image_two)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
   cv2.destroyAllWindows()
Result Image
We have a method called cv2.substract(image_one, image_two) to perform subtraction on two images. We are going to use the same images as an addition. Let's see the code.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_one.jpg')
image_two = cv2.imread('_two.jpg')
# substracting two images
result_image = cv2.subtract(image_one, image_two)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
   cv2.destroyAllWindows()
Result Image
If you have any doubts regarding the tutorial, mention them in the comment section.
Count numbers from range whose prime factors are only 2 and 3 in C++

We are provided two numbers START and END to define a range of numbers. The goal is to find the numbers that have only 2 and 3 as their prime factors and are in the range [START,END].
We will do this by traversing numbers from START to END and for each number we will check if the number is divisible by 2 and 3 only. If divisible, divide it and reduce it. If not, break the loop. In the end if the number is reduced to 1 then it has only 2 and 3 as its factors.
Let’s understand with examples.
Input 
START=20 END=25
Output 
Numbers with only 2 and 3 as prime factors: 1
Explanation 
Prime factors of each number:
20 = 2*2*5
21 = 3*7
22 = 2*11
23 = 1*23
24 = 2*2*2*3
25 = 5*5
Only 24 has 2 and 3 as prime factors.
Input 
START=1000 END=1500
Output 
Numbers with only 2 and 3 as prime factors: 4
Explanation 
1024 1152 1296 1458 are the numbers with only 2 and 3 as prime factors
We take an integers START and END as range variables.
We take an integers START and END as range variables.
Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors.
Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors.
Take the initial variable count as 0 for such numbers.
Take the initial variable count as 0 for such numbers.
Traverse range of numbers using for loop. i=start to i=end
Traverse range of numbers using for loop. i=start to i=end
Now for each number num=i, using while loop check if num%2==0, divide it.
Now for each number num=i, using while loop check if num%2==0, divide it.
if num%3==0, divide it. If not by both break the while loop
if num%3==0, divide it. If not by both break the while loop
If after the while loop num is 1 then increase count.
If after the while loop num is 1 then increase count.
At the end of all loops count will have a total number which has only 2 and 4 as prime factors.
At the end of all loops count will have a total number which has only 2 and 4 as prime factors.
Return the count as result.
Return the count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int twothreeFactors(int start, int end){
   // Start with 2 so that 1 doesn't get counted
   if (start == 1)
      { start++; }
   int count = 0;
   for (int i = start; i <= end; i++) {
      int num = i;
      while(num>1){
         // if divisible by 2, divide it by 2
         if(num % 2 == 0)
            { num /= 2; }
         // if divisible by 3, divide it by 3
         else if (num % 3 == 0)
            { num /= 3; }
         else //if divisible by neither 2 nor 3 break
            { break; }
      }
      // means only 2 and 3 are factors of num
      if (num == 1)
         { count++; }
   }
   return count;
}
int main(){
   int START = 10, END = 20;
   cout <<"Numbers with only 2 and 3 as prime factors:"<< twothreeFactors(START,END);
   return 0;
}
If we run the above code it will generate the following output −
Numbers with only 2 and 3 as prime factors:3
How do I subtract minutes from a date in JavaScript?

To subtract minutes to a JavaScript Date object, use the setMinutes() method. JavaScript date setMinutes() method sets the minutes for a specified date according to local time.
You can try to run the following code to subtract 20 minutes.
<html>
   <head>
      <title>JavaScript setMinutes Method</title>
   </head>
   <body>
      <script>
         var dt = new Date("December 31, 2017 11:30:25");
         dt.setMinutes( dt.getMinutes() - 20 );
         document.write( dt );
      </script>
   </body>
</html>
How to get local date in android using local date API class?

This example demonstrate about How to get local date in android using local date API class.
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"?>
<android.support.constraint.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/date"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Local Date"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show date.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.icu.util.LocaleData;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.awt.font.TextAttribute;
import java.time.LocalDate;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView=findViewById(R.id.date);
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
         LocalDate date=LocalDate.now();
         LocalDate yesterday=date.minusDays(1);
         LocalDate tomorrow=date.plusDays(1);
         textView.setText(String.valueOf("Today "+date+" Yesterday "+yesterday+" tomorrow "+tomorrow));
      }
   }
}
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 −
In the above result, it is showing today date, yesterday and tomorrow date. To verify the date check system date as shown below −
Click here to download the project code
GATE | GATE CS 2018 | Question 7 - GeeksforGeeks

22 Feb, 2018
In a party, 60% of the invited guests are male and 40% are female. If 80% of the invited guests attended the party and if all the invited female guests attended, what would be the ratio of males to females among the attendees in the party?
(A) 2:3(B) 1:1(C) 3:2(D) 2:1Answer: (B)Explanation:
Let total males and females be 60x and
40x respectively.

Total number of people = (60x + 40x)
Total number of people who attended : 
                 0.8(60x + 40x) = 80x

Let y males attended. It is given all 
1females attended 

40x + y = 80x
y = 40x which is same as females.

Alternative Approach –Lets total number of people = 100.Therefore, 60 are male and and 40 are female.
But total 80 guests are attended and all 40 female attended the party.So, there remaining (80 – 40 = 40) attendees should be male.
Then the ration of male to female among attendees is 40 : 40 = 1 : 1Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Setting decimal precision in C - GeeksforGeeks

02 Jun, 2017
How to print floating point numbers with a specified precision? Rounding is not required. For example, 5.48958123 should be printed as 5.4895 if given precision is 4.
For example, below program sets the precision for 4 digits after the decimal point:
// C program to set precision in floating point numbers#include<stdio.h>#include<math.h>int main(){   float num = 5.48958123;     // 4 digits after the decimal point   num = floor(10000*num)/10000;     printf("%f", num);   return 0;}
Output:
5.489500
We can generalize above method using pow()
float newPrecision(float n, float i){    return floor(pow(10,i)*n)/pow(10,i);}
In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same.
// C program to set precision in floating point numbers// using format specifier#include<stdio.h>  int main() {    float num = 5.48958123;      // 4 digits after the decimal point      printf("%0.4f", num);     return 0;}
Output:
5.4896
This article is contributed by Niharika Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Converting Strings to Numbers in C/C++
Enumeration (or enum) in C
wxPython - Change Font of StaticText - GeeksforGeeks

18 Jun, 2020
In this article we are going to learn how can we change the font of static text present on the window. To do this first of all, we wil create a wx.Font class of wxPython. After this we will use SetFont() function of wx.StaticText class.SetFont() function takes a sing wx.Font type parameter.
Syntax: wx.StaticText.SetFont(self, font)
Parameters:
Code Example:
import wx    class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)        self.InitUI()      def InitUI(self):        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)        self.pnl = wx.Panel(self)          # create wx.Font object        font = wx.Font(20, family = wx.FONTFAMILY_MODERN, style = 0, weight = 90,                       underline = False, faceName ="", encoding = wx.FONTENCODING_DEFAULT)          self.st = wx.StaticText(self.pnl, id = 1, label ="This is the Label.", pos =(20, 20),                                size = wx.DefaultSize, style = wx.ST_ELLIPSIZE_MIDDLE, name ="statictext")          # set font for the statictext        self.st.SetFont(font)          self.SetSize((350, 250))        self.SetTitle('wx.Button')        self.Centre()  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output Window:
Python wxPython-StaticText
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
TimeUnit toMillis() method in Java with Examples

30 Oct, 2018
The toMillis() method of TimeUnit Class is used to get the time represented by the TimeUnit object, as the number of Seconds, since midnight UTC on the 1st January 1970.
Syntax:
public long toMillis(long duration)
Parameters: This method accepts a mandatory parameter duration which is the duration in milliSeconds.
Return Value: This method returns the converted duration as Seconds.
Below programt illustrate the implementation of TimeUnit toMillis() method:
Program 1:
// Java program to demonstrate// toMillis() method of TimeUnit Class  import java.util.concurrent.*;import java.util.Date;  class GFG {    public static void main(String args[])    {        // Get current time in seconds        long timeInSec = (new Date().getTime()) / 1000;          // Create a TimeUnit object        TimeUnit time = TimeUnit.SECONDS;          // Convert seconds to milliSeconds        // using toMillis() method        System.out.println("Time " + timeInSec                           + " Seconds in MilliSeconds = "                           + time.toMillis(timeInSec));    }}
Time 1539585757 Seconds in MilliSeconds = 1539585757000

Program 2:
// Java program to demonstrate// toMillis() method of TimeUnit Class  import java.util.concurrent.*;import java.util.Calendar;  class GFG {    public static void main(String args[])    {        // Get current time in milliseconds        long timeInSec = (Calendar                              .getInstance()                              .getTimeInMillis())                         / 1000;          // Create a TimeUnit object        TimeUnit time = TimeUnit.SECONDS;          // Convert seconds to milliSeconds        // using toMillis() method        System.out.println("Time " + timeInSec                           + " Seconds in MilliSeconds = "                           + time.toMillis(timeInSec));    }}
Time 1539585759 Seconds in MilliSeconds = 1539585759000

Java - util package
Java-Date-Time
Java-Functions
Java-TimeUnit
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap get() Method in Java

11 May, 2022
The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Syntax:
Hash_Map.get(Object key_element)
Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched.
Return Value: The method returns the value associated with the key_element in the parameter.
Below programs illustrates the working of java.util.HashMap.get() method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the get() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();          // Mapping string values to int keys        hash_map.put(10, "Geeks");        hash_map.put(15, "4");        hash_map.put(20, "Geeks");        hash_map.put(25, "Welcomes");        hash_map.put(30, "You");          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Getting the value of 25        System.out.println("The Value is: " + hash_map.get(25));          // Getting the value of 10        System.out.println("The Value is: " + hash_map.get(10));    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The Value is: Welcomes
The Value is: Geeks

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the get() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Getting the value of "Geeks"        System.out.println("The Value is: " + hash_map.get("Geeks"));          // Getting the value of "You"        System.out.println("The Value is: " + hash_map.get("You"));    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The Value is: 20
The Value is: 30

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Multidimensional Arrays in Java
Collections in Java
ArrayList in Java
Multithreading in Java
Stream In Java
Introduction to Java
Constructors in Java
Initializing a List in Java
Initialize an ArrayList in Java
Wand rectangle() function in Python - GeeksforGeeks

10 May, 2020
rectangle() function, as the name describes this function is used to draw a circle using wand.drawing object in Python. rectangle takes many arguments like left, top, right, bottom, width, height etc.
Syntax : wand.drawing.rectangle(left, top, right, bottom, width, height, radius, xradius, yradius)
Parameters :
Example #1:
# Import different modules of wandfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Colorimport math   with Drawing() as draw:    draw.fill_color = Color('GREEN')    draw.rectangle(left = 25, top = 50,                    right = 175, bottom = 150)      with Image(width = 200, height = 200, background = Color('lightgreen')) as image:        draw(image)        image.save(filename = "rectangle.png")
Output:
Example #2:setting corner-radius for the rectangle.
# Import different modules of wandfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Colorimport math   with Drawing() as draw:    draw.fill_color = Color('GREEN')    draw.rectangle(left = 25, top = 50, right = 175,                          bottom = 150, radius = 25)      with Image(width = 200, height = 200, background = Color('lightgreen')) as image:        draw(image)        image.save(filename = "rectangle.png")
Output:
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
NumPy Sorting Arrays

Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(), 
that will sort a specified array.
Sort the array:
Note: This method returns a copy of the array, leaving the 
  original array unchanged.
You can also sort arrays of strings, or any other data type:
Sort the array alphabetically:
Sort a boolean array:
If you use the sort() method on a 2-D array, both arrays will be sorted:
Sort a 2-D array:
Use the correct NumPy method to return a sorted array.
arr = np.array([3, 2, 0, 1])

x = np.(arr)

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.
Difference between the largest and the smallest primes in an array in Java

With a given array of integers where all elements are less than 1000000. Find the difference between the largest and the smallest primes in an array.
Array: [ 1, 2, 3, 4, 5 ]

Largest Prime Number = 5
Smallest Prime Number = 2

Difference = 5 - 3 = 2.
Use Sieve of Eratosthenes approach, which is an efficient way to find out all prime numbers smaller than a given number. Then we will figure out the largest and smallest prime number to get the required difference.
 Live Demo
Following is the program in Java to find the required output.
public class JavaTester {

   static int MAX = 1000000;
   static boolean prime[] = new boolean[MAX + 1];

   public static void runSieveOfEratosthenes(){
      //reset prime flags to be true
      for(int i=0; i< MAX+1; i++) prime[i] = true;
      //set 1 as non-prime
      prime[1] = false;

      for (int p = 2; p * p <= MAX; p++) {
         // If prime[p] is not modified, then it is a prime
         if (prime[p]) {
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p) prime[i] = false;
         }
      }
   }

   public static int difference(int arr[]){
      int min = MAX + 2;
      int max = -1;
      for (int i = 0; i < arr.length; i++) {
         // check if the number is prime or not
         if (prime[arr[i]] == true) {
            // set the max and min values
            if (arr[i] > max) max = arr[i];
            if (arr[i] < min) min = arr[i];
         }
      }
      return max - min;
   }

   public static void main(String args[]){
      // run the sieve
      runSieveOfEratosthenes();
      int arr[] = { 1, 2, 3, 4, 5 };
      System.out.println(difference(arr));
   }
}
3
CSS - background-image

background-image defines a pointer to an image resource which is to be placed in the background of an element.
uri − URL of the image.
uri − URL of the image.
none − Setting background-image to none means that no background image should be used for matching elements.
none − Setting background-image to none means that no background image should be used for matching elements.
transparent
transparent
All the HTML elements.
object.style.backgroundImage = "Any value as defined above";

Following is the example which demonstrates how to set the background image for an element.
<html>
   <head>
      <style>
         body {
            background-image: url("/css/images/css.jpg");
            background-color: #cccccc;
         }
      </style>
   </head>
   
   <body>
      <h1>Hello World!</h1>
   </body>
<html>
It will produce the following result −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Java Program to display a prime number less than the given number

Let’s say the value you have set is 20 and you have to display a prime number less than this value i.e. 19 in this case.
The following is an example that displays a prime number less than the given number −
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val = 20;
      boolean[] isprime = new boolean[val + 1];
      for (int i = 0; i<= val; i++)
         isprime[i] = true;
         // 0 and 1 is not prime
         isprime[0] = false;
         isprime[1] = false;
         int n = (int) Math.ceil(Math.sqrt(val));
      for (int i = 0; i<= n; i++) {
         if (isprime[i])
            for (int j = 2 * i; j<= val; j = j + i)
               // not prime
               isprime[j] = false;
      }
      int myPrime;
      for (myPrime = val; !isprime[myPrime]; myPrime--); // empty loop body
         System.out.println("Largest prime less than or equal to " + val + " = " + myPrime);
   }
}
Largest prime less than or equal to 20 = 19
Above, we have set the following as non-prime since both 0 and 1 are non-prime −
isprime[0] = false;
isprime[1] = false;
DAX Text - VALUE function

Converts a text string that represents a number to a number in numeric data type.
VALUE (<text>) 

text
The text to be converted.
A number.
The text parameter for the DAX VALUE function can be a constant, a number, a date, or a time in DAX data types.
If the text is not in one of these following formats, DAX VALUE function returns an error.
If the text represents an integer, the integer is returned.
If the text represents an integer, the integer is returned.
If the text represents a decimal number with only zero values to the right of the decimal point, then the integer part only is returned.
If the text represents a decimal number with only zero values to the right of the decimal point, then the integer part only is returned.
If the text represents a decimal number, then the decimal number is returned.
If the text represents a decimal number, then the decimal number is returned.
= VALUE ("5") returns 5. 
= VALUE ("5.0") returns 5. 
= VALUE ("5.1") returns 5.1. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
C# | Get the number of elements in the SortedSet - GeeksforGeeks

01 Feb, 2019
SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Count Property is used to get the number of elements in the SortedSet.
Properties:
In C#, SortedSet class can be used to store, remove or view elements.
It maintains ascending order and does not store duplicate elements.
It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order.
Syntax:
mySortedSet.Count

Here, mySortedSet is a SortedSet.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to get the number of// elements in the SortedSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a SortedSet of integers        SortedSet<int> mySortedSet = new SortedSet<int>();          // adding elements in mySortedSet        mySortedSet.Add(1);        mySortedSet.Add(2);        mySortedSet.Add(3);        mySortedSet.Add(4);        mySortedSet.Add(5);          // Displaying the number of elements in        // the SortedSet using "Count" function        Console.WriteLine("The number of elements in mySortedSet are: "                                                   + mySortedSet.Count);    }}
The number of elements in mySortedSet are: 5

Example 2:
// C# code to get the number of// elements in the SortedSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a SortedSet of strings        SortedSet<string> mySortedSet = new SortedSet<string>();          // adding elements in mySortedSet        mySortedSet.Add("Hey");        mySortedSet.Add("GeeksforGeeks");        mySortedSet.Add("and");        mySortedSet.Add("Geeks Classes");          // Displaying the number of elements in        // the SortedSet using "Count" function        Console.WriteLine("The number of elements in mySortedSet are: "                                                    + mySortedSet.Count);    }}
The number of elements in mySortedSet are: 4

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1.count?view=netcore-2.1
CSharp-Generic-Namespace
CSharp-Generic-SortedSet
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
Python math library | exp() method - GeeksforGeeks

06 Jan, 2019
Python has math library and has many functions regarding it. One such function is exp(). This method is used to calculate the power of e i.e. e^y or we can say exponential of y. The value of e is approximately equal to 2.71828.....
Syntax : math.exp(y)
Parameters :y [Required] – It is any valid python number either positive or negative.Note that if y has value other than number then its return error.
Returns: Returns floating point number by calculating e^y.
Code # 1:
# Python3 code to demonstrate # the working of exp() import math   # initializing the value test_int = 4test_neg_int = -3test_float = 0.00  # checking exp() values # with different numbersprint (math.exp(test_int))print (math.exp(test_neg_int))print (math.exp(test_float))
54.598150033144236
0.049787068367863944
1.0

 
Code #2:
# Python3 code to demonstrate # the working of exp() import math   # checking exp() values # with inbuilt numbersprint (math.exp(math.pi))print (math.exp(math.e))
23.140692632779267
15.154262241479262

 Code #3: TypeError
# Python3 code to demonstrate # the working of exp() import math   # checking for stringprint (math.exp("25"))
Output:
Traceback (most recent call last):
  File "/home/c7ae4f1bef0ed8c7756b3f55e7d2ce81.py", line 6, in 
    print (math.exp("25"))
TypeError: a float is required

Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python