code-rag-bench/online-tutorials huggingface dataset:
How to order by timestamp (descending order) in MongoDB

To order by timestamp, use sort() in MongoDB. Let us create a collection with documents −
> db.demo737.insertOne({"timestamp" : new ISODate("2020-04-01" )});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead682157bb72a10bcf065c")
}
> db.demo737.insertOne({"timestamp" : new ISODate("2020-10-31" )});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead682757bb72a10bcf065d")
}
> db.demo737.insertOne({"timestamp" : new ISODate("2020-05-02" )});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead682a57bb72a10bcf065e")
}
Display all documents from a collection with the help of find() method −
> db.demo737.find();
This will produce the following output −
{ "_id" : ObjectId("5ead682157bb72a10bcf065c"), "timestamp" : ISODate("2020-04-01T00:00:00Z") }
{ "_id" : ObjectId("5ead682757bb72a10bcf065d"), "timestamp" : ISODate("2020-10-31T00:00:00Z") }
{ "_id" : ObjectId("5ead682a57bb72a10bcf065e"), "timestamp" : ISODate("2020-05-02T00:00:00Z") }
Following is the query to order by timestamp (descending order) −
> db.demo737.find().sort({"timestamp":-1});
This will produce the following output −
{ "_id" : ObjectId("5ead682757bb72a10bcf065d"), "timestamp" : ISODate("2020-10-31T00:00:00Z") }
{ "_id" : ObjectId("5ead682a57bb72a10bcf065e"), "timestamp" : ISODate("2020-05-02T00:00:00Z") }
{ "_id" : ObjectId("5ead682157bb72a10bcf065c"), "timestamp" : ISODate("2020-04-01T00:00:00Z") }
Explain malloc function in C programming

Write a C program to display and add the elements using dynamic memory allocation functions.
In C, the library function malloc allocates a block of memory in bytes at runtime. It returns a void pointer, which points to the base address of allocated memory and it leaves the memory uninitialized.
void *malloc (size in bytes)
For example,
int *ptr;ptr = (int * ) malloc (1000);
int *ptr;
ptr = (int * ) malloc (1000);
int *ptr;ptr = (int * ) malloc (n * sizeof (int));
int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
Note − It returns NULL, if the memory is not free.
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Printing elements//
   printf("Enter the elements : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}
Enter the number of elements : 5
Enter the elements :
23
45
65
12
23

The sum of elements is 168
Displaying the cleared out memory location :
10753152
0
10748240
0
23
Python | Remove all occurrences in nested list

16 May, 2019
The task of removal of element generally doesn’t pose any challenge, but sometimes, we may have a more complex problem than just removing a single element or performing removal in just a normal list. Problem can be removing all occurrences of nested list. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension
The list comprehension can be used as a shorter method to the recommended longer method in normal way of loops to perform this task in which we just check for a match and reconstruct the list without the target list element.
# Python3 code to demonstrate# Remove all occurrences in nested list# using list comprehension  # initializing listtest_list = [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]  # initializing list to deletedel_list = [4, 5]  # printing original listprint("The original list : " + str(test_list))  # printing delete list print("The list to be deleted is : " + str(del_list))  # using list comprehension# Remove all occurrences in nested listres = [i for i in test_list if i != del_list]  # print resultprint("The list after removal of list element : " + str(res))
The original list : [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]
The list to be deleted is : [4, 5]
The list after removal of list element : [[1, 2, 3], [8, 9], [10, 11]]

 
Method #2 : Using filter() + partial() + operator.ne
The task can also be performed using the above functions. The filter function performs filtering, and returns the partial list by partial function and not equal condition is imposed using the operator.ne method.
# Python3 code to demonstrate# Remove all occurrences in nested list# using filter() + partial() + operator.nefrom functools import partialfrom operator import ne  # initializing listtest_list = [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]  # initializing list to deletedel_list = [4, 5]  # printing original listprint("The original list : " + str(test_list))  # printing delete list print("The list to be deleted is : " + str(del_list))  # using filter() + partial() + operator.ne# Remove all occurrences in nested listres = list(filter(partial(ne, del_list), test_list))  # print resultprint("The list after removal of list element : " + str(res))
The original list : [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]
The list to be deleted is : [4, 5]
The list after removal of list element : [[1, 2, 3], [8, 9], [10, 11]]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM onscroll Event

27 Jul, 2021
The HTML DOM onscroll event occurs when a scrollbar is used. CSS overflow is used to create a scrollbar.Supported tags
<address>
, <blockquote>
, <body>
, <caption>
, <center>
, <dd>
, <dir>
, <div>
, <dl>
, <dt>
, <fieldset>
, <form>
, <h1>to <h6>
, <html>
, <li>
, <menu>
, <object>
, <ol>
, <p>
, <pre>
, <select>
, <tbody>
, <textarea>
, <tfoot>
, <thead>
, <ul>
Syntax:  
In HTML:  
<element onscroll="myScript">
In JavaScript:  
object.onscroll = function(){myScript};
In JavaScript, using the addEventListener() method:  
object.addEventListener("scroll", myScript);
 
Example: Using the addEventListener() method  
html
<!DOCTYPE html><html> <head>    <title>        HTML DOM onscroll Event    </title></head> <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onscroll Event</h2>        <textarea style="width:100%" id="tID">            HTML stands for Hyper Text Markup Language.          It is used to design web pages using markup language.          HTML is the combination of Hypertext and Markup language.          Hypertext defines the link between the web pages.          Markup language is used to define the text document          within tag which defines the structure of web pages.          HTML is a markup language which is used by the browser          to manipulate text, images and other content to          display it in required format.        </textarea>         <p id="try"></p>     </center>    <script>        document.getElementById(          "tID").addEventListener("scroll", GFGfun);         function GFGfun() {            document.getElementById(              "try").innerHTML = "Textarea scrolled.";        }    </script> </body> </html>
Output:  
Supported Browsers: The browsers supported by HTML DOM onscroll Event are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
ManasChhabra2
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ?
View DICOM images using pydicom and matplotlib

24 Feb, 2021
Prerequisite : Matplotlib 
DICOM stands for Digital Imaging and Communications in Medicine. DICOM files were introduced to maintain uniformity among varied types of medical image modalities. It is a standard format to view, store, share and retrieve medical images.
Python offers a powerful module, pydicom to work with the DICOM files such as medical images, reports and radiotherapy objects. pydicom reads, modifies and write data in DICOM files. 
Run the following commands in the command prompt:
pip install dicom
pip install matplotlib
pydicom enables us to work with DICOM files, in this article we will discuss the mechanism of viewing the DICOM file using pydicom and matplotlib. For reading the DICOM files we use pydicom package and to view the result we use matplotlib.
The path where the dicom file is stored is passed as an argument to data_manager.get_files method.
Explanation:
Import module
Read DICOM file using pydicom.data.data_manager.get_files() method
Syntax : 
pydicom.data.data_manager.get_files(base,pass_dicom)[0]
Parameter:
Base : is base directory to recursively search as a string.
Pattern : By default it is “*”. It is a string pattern which is used to filter the files.
Provide 2 arguments: base and pattern
Displays the data as image i.e. on 2D regular raster.
Display image
Note : Enter the location of the dcm file excluding the file name in the variable names base and enter the file name in the pass_dicom variable. In this case the file is stored at a directory named dicom_image as shown:
Download the dcm file from here and rename it to: 1-12.dcm
Compare the path shown in the address bar with the values stored in the variable base and pass_dicom
Program:
Python3
import matplotlib.pyplot as pltimport pydicomimport pydicom.data  # Full path of the DICOM file is passed in basebase = r"C:\Users\Ajit Gupta\Documents\dicom image"pass_dicom = "1-12.dcm"  # file name is 1-12.dcm  # enter DICOM image name for pattern# result is a list of 1 elementfilename = pydicom.data.data_manager.get_files(base, pass_dicom)[0]  ds = pydicom.dcmread(filename)  plt.imshow(ds.pixel_array, cmap=plt.cm.bone)  # set the color map to boneplt.show()
Output:
Python-matplotlib
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
10 Best Web Development Projects For Your Resume
E-commerce Website using Django
Banking Transaction System using Java
Voting System Project Using Django Framework
Browser Automation Using Selenium
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python program to remove Duplicates elements from a List?

One list is given with duplicate element, our task is create another list which contains the element of without duplicates.
A::[2,3,4,3,4,6,78,90]
Output::[2,3,4,6,78,90]

Step 1: create a list.
Step 2: create a new list which is empty.
Step 3: traverse every element in list.
Step 4: if element is not present in the list return true.
Step 5: append in the new list.
Step 6: display new list.

#  To remove duplicate elements
defremoveduplicateele(A):
   newlist = []
   for n in A:
      if n not in newlist:
         newlist.append(n)
   returnnewlist
# Driver Code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
fori in range(int(n)):
   k=int(input(""))
   A.append(int(k))
print("THE NEW LIST IS ::>",removeduplicateele(A))
Enter the size of the List ::5
Enter the number ::
10
20
30
20
10
THE LIST IS ::> [10, 20, 30]
Convert String to Set in Python

20 Aug, 2020
We can convert a string to setin Python using the set() function.
Syntax : set(iterable)
Parameters : Any iterable sequence like list, tuple or dictionary.
Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.
Example 1 :
# create a string strstring = "geeks"print("Initially")print("The datatype of string : " + str(type(string)))print("Contents of string : " + string)  # convert String to Setstring = set(string)print("\nAfter the conversion")print("The datatype of string : " + str(type(string)))print("Contents of string : ", string)
Output :
Initially
The datatype of string : 
Contents of string : geeks

After the conversion
The datatype of string : 
Contents of string :  {'k', 's', 'g', 'e'}

Example 2 :
# create a string strstring = "Hello World!"print("Initially")print("The datatype of string : " + str(type(string)))print("Contents of string : " + string)  # convert String to Setstring = set(string)print("\nAfter the conversion")print("The datatype of string : " + str(type(string)))print("Contents of string : ", string)
Output :
Initially
The datatype of string : 
Contents of string : Hello World!

After the conversion
The datatype of string : 
Contents of string :  {'r', 'H', ' ', 'l', 'o', '!', 'd', 'W', 'e'}

python-set
python-string
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Two columns as primary key with auto-increment in MySQL?

Achieve this using MyISAM Engine. Here is an example of two columns as primary key with auto-increment.
Creating a table with two columns as primary key −
mysql> create table TwoPrimaryKeyTableDemo
   -> (
   -> Result ENUM('First','Second','Third','Fail') not null,
   -> StudentId int not null auto_increment,
   -> StudentName varchar(200) not null,
   -> Primary key(Result,StudentId)
   -> )
   -> ENGINE=MyISAM;
Query OK, 0 rows affected (0.20 sec)
Inserting records into table
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('John','Fail');
Query OK, 1 row affected (0.42 sec)
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result)values('Carol','First');
Query OK, 1 row affected (0.09 sec)
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Smith','Third');
Query OK, 1 row affected (0.05 sec)
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Johnson','Second');
Query OK, 1 row affected (0.03 sec)
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Johnson','Third');
Query OK, 1 row affected (0.06 sec)
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Carol','Second');
Query OK, 1 row affected (0.18 sec)
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Carol','Fail');
Query OK, 1 row affected (0.05 sec)
Now we can check the records with the help of select statement with order by clause. The query is as follows.
mysql> select *from TwoPrimaryKeyTableDemo order by StudentId,Result;
The following is the output −
+--------+-----------+-------------+
| Result | StudentId | StudentName |
+--------+-----------+-------------+
| First  | 1         | Carol       |
| Second | 1         | Johnson     |
| Third  | 1         | Smith       |
| Fail   | 1         | John        |
| Second | 2         | Carol       |
| Third  | 2         | Johnson     |
| Fail   | 2         | Carol       |
+--------+-----------+-------------+
7 rows in set (0.00 sec)
Histograms and Density Plots in R - GeeksforGeeks

25 Feb, 2021
A histogram is a graphical representation that organizes a group of data points into user-specified ranges and an approximate representation of the distribution of numerical data.
In R language the histogram is built with the use of hist() function.
Syntax: hist(v,main,xlab,xlim,ylim,breaks,col,border)
Parameters:
v:- It is a vector containing numeric values used in the histogram.
main:-It indicates the title of the chart.
col:- It is used to set the color of the bars.
border:-It is used to set the border color of each bar.
xlab:-It is used to give a description of the x-axis.
xlim:-It is used to specify the range of values on the x-axis.
ylim:-It is used to specify the range of values on the y-axis.
breaks:-It is used to mention the width of each bar.
Return: It will return the histogram.
Example:-
R
v <-  c(5,9,13,2,50,20,59,36,23,2,8,27,72,14)  hist(v,xlab = "Weight",col = "red",border = "black")
Output:
A density plot is a representation of the distribution of a numeric variable that uses a kernel density estimate to show the probability density function of the variable. In R Language we use the density() function which helps to compute kernel density estimates. And further with its return value, is used to build the final density plot.
Syntax: density(x)
Parameters:
x: the data from which the estimate is to be computed
Returns:
It will return the kernel density.
Example:
Used dataset link:-Link
R
library(readxl)library(ggplot2)  Salary_Data <- read_excel("Salary_Data.xls")  den <- density(Salary_Data$YearsExperience)  plot(den, frame = FALSE, col = "blue",main = "Density plot")
Output:
We can also create a histogram and a density plot in the same frame.
Example:
R
hist(beaver1$temp,      col="green",     border="black",     prob = TRUE,     xlab = "temp",     main = "GFG")  lines(density(beaver1$temp),      lwd = 2,      col = "chocolate3")
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
JavaScript - Convert an array to key value pair

Suppose we have an array like this −
const arr = [
{"name": "Rahul", "score": 89},
   {"name": "Vivek", "score": 88},
   {"name": "Rakesh", "score": 75},
   {"name": "Sourav", "score": 82},
   {"name": "Gautam", "score": 91},
   {"name": "Sunil", "score": 79},
];
We are required to write a JavaScript function that takes in one such array and constructs an object where name value is the key and the score value is their value.
Use the Array.prototype.reduce() method to construct an object from the array.
Following is the code −
const arr = [
   {"name": "Rahul", "score": 89},
   {"name": "Vivek", "score": 88},
   {"name": "Rakesh", "score": 75},
   {"name": "Sourav", "score": 82},
   {"name": "Gautam", "score": 91},
   {"name": "Sunil", "score": 79},
];
const buildObject = arr => {
   const obj = {};
   for(let i = 0; i < arr.length; i++){
      const { name, score } = arr[i];
      obj[name] = score;
   };
   return obj;
};
console.log(buildObject(arr));
This will produce the following output in console −
{ Rahul: 89, Vivek: 88, Rakesh: 75, Sourav: 82, Gautam: 91, Sunil: 79 }
Checking if a HashSet contains certain value in Java

Let’s say the following is our Integer array −
Integer arr[] = { 50, 100, 150, 200, 250, 300 };
Set the above integer array in HashSet −
Set<Integer>set = new HashSet<Integer>(Arrays.asList(arr));
Now, let us check whether the HashSet contains certain value or not −
set.contains(150)
TRUE is returned if the value is in the List, else FALSE is the return value.
 Live Demo
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      Integer arr[] = { 50, 100, 150, 200, 250, 300 };
      Set<Integer>set = new HashSet<Integer>(Arrays.asList(arr));
      System.out.println(set.contains(200));
      System.out.println(set.contains(150));
      System.out.println(set.contains(100));
      System.out.println(set.contains(10));
   }
}
true
true
true
false
Difference between BFS and DFS - GeeksforGeeks

11 Apr, 2022
Breadth First Search:BFS stands for Breadth First Search is a vertex-based technique for finding the shortest path in the graph. It uses a Queue data structure that follows first in first out. In BFS, one vertex is selected at a time when it is visited and marked then its adjacent are visited and stored in the queue. It is slower than DFS. Example:
 Input:
        A
       / \
      B   C
     /   / \
    D   E   F
Output: 
A, B, C, D, E, F
Depth First Search:DFS stands for Depth First Search is an edge-based technique. It uses the Stack data structure and performs two stages, first visited vertices are pushed into the stack, and second if there are no vertices then visited vertices are popped. Example: 
  Input:
        A
       / \
      B   C
     /   / \
    D   E   F
Output: 
A, B, D, C, E, F
BFS vs DFS
Please also see BFS vs DFS for Binary Tree for the differences for a Binary Tree Traversal. 
MahammadRafeeShaik
ashushrma378
tusharsingh2
adityarajeevis19
mihirvilankar64
itskawal2000
harendrakumar123
BFS
DFS
Algorithms
Difference Between
DFS
BFS
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Playfair Cipher with Examples
How to write a Pseudo Code?
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing
Stack vs Heap Memory Allocation
Difference between Turn Around Time (TAT) and Waiting Time (WT) in CPU Scheduling - GeeksforGeeks

28 Mar, 2020
In CPU Scheduling, we often need to find average Turnaround and Waiting Time with the help of Arrival, Burst and Completion Time. Let’s have a brief look of them:
Turnaround Time (TAT):
It is the time interval from the time of submission of a process to the time of the completion of the process.Difference b/w Completion Time and Arrival Time is called Turnaround Time.
It is the time interval from the time of submission of a process to the time of the completion of the process.
Difference b/w Completion Time and Arrival Time is called Turnaround Time.
Completion Time (CT): This is the time when the process completes it’s execution.Arrival Time (AT): This is the time when the process has arrived in the ready state.
TAT = CT - AT
Waiting Time (WT):
The time spent by a process waiting in the ready queue for getting the CPU.The time difference b/w Turnaround Time and Burst Time is called Waiting Time.
The time spent by a process waiting in the ready queue for getting the CPU.
The time difference b/w Turnaround Time and Burst Time is called Waiting Time.
Burst Time (BT): This is the time required by the process for it’s execution.
WT = TAT - BT
Now with Waiting Time and Burst Time we can also calculate Turn Around Time via:
TAT = BT + WT
Example:
Solution:
Avg. TAT = (24 + 27 + 31) / 3 = 27.33 sec
Avg. WT  = (0 + 24 + 27) / 3 = 17.0 sec 
Let’s see the difference between Turnaround Time and Waiting Time:
Picked
Difference Between
GATE CS
Operating Systems
Operating Systems
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
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
How can we implement a splash screen using JWindow in Java?


A JWindow is a container that can be displayed anywhere on the user desktop. It does not have the title bar, window management buttons, etc like a JFrame.
The JWindow contains a JRootPane as its only child class. The contentPane can be the parent of any children of the JWindow. Like a JFrame, a JWindow is another top-level container and it is as an undecorated JFrame. It does not have features like a title bar, windows menu, etc. A JWindow can be used as a splash screen window that displays once when the application is launched and then automatically disappears after a few seconds.
import javax.swing.*;
import java.awt.*;
public class CreateSplashScreen extends JWindow {
   Image splashScreen;
   ImageIcon imageIcon;
   public CreateSplashScreen() {
      splashScreen = Toolkit.getDefaultToolkit().getImage("C:/Users/User/Desktop/Java                Answers/logo.jpg");
      // Create ImageIcon from Image
      imageIcon = new ImageIcon(splashScreen);
      // Set JWindow size from image size
      setSize(imageIcon.getIconWidth(),imageIcon.getIconHeight());
      // Get current screen size
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      // Get x coordinate on screen for make JWindow locate at center
      int x = (screenSize.width-getSize().width)/2;
      // Get y coordinate on screen for make JWindow locate at center
      int y = (screenSize.height-getSize().height)/2;
      // Set new location for JWindow
      setLocation(x,y);
      // Make JWindow visible
      setVisible(true);
   }
   // Paint image onto JWindow
   public void paint(Graphics g) {
      super.paint(g);
      g.drawImage(splashScreen, 0, 0, this);
   }
   public static void main(String[]args) {
      CreateSplashScreen splash = new CreateSplashScreen();
      try {
         // Make JWindow appear for 10 seconds before disappear
         Thread.sleep(10000);
         splash.dispose();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
How to round array elements to the given number of decimals using NumPy?

05 Sep, 2020
In NumPy, we can round array elements to the given number of decimals with the help of round(). 
Syntax:
np.round(a, decimals=0, out=None)
The first parameter will be an array and the second parameter will be the number of decimals for which needed rounded. If no parameter will be pass as the second parameter then by default it takes 0. It will return round array elements to the given number of decimals.
Example 1:
Python3
import numpy as np    # perform the numpy.roundrounded_array = np.round([1.5, 1.53, 1.23, 3.89])  # print the rounded_arrayprint(rounded_array)
Output
[2. 2. 1. 4.]

Example 2:
Python3
import numpy as np    # perform the numpy.roundrounded_array = np.round([1.5, 1.53, 1.23, 3.89],                          decimals=1)  # print the rounded_arrayprint(rounded_array)
Output:
[1.5 1.5 1.2 3.9]

Example
Python3
import numpy as np    # perform the numpy.roundrounded_array = np.round(    [1.534, 1.5389, 1.2301, 3.89903, 6.987, 4.09], decimals=2)  # print the rounded_arrayprint(rounded_array)
Output:
[1.53 1.54 1.23 3.9  6.99 4.09]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Convert JSON to CSV in Python

29 May, 2021
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python. 
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. 
Refer to the below articles to understand the basics of JSON and CSV.  
Working With JSON Data in Python 
Working with CSV file in Python. 
 
For simple JSON data consisting of key and value pairs, keys will be headers for the CSV file and values the descriptive data. 
Example: Suppose the JSON file looks like this: 
We want to convert the above JSON to CSV file with key as headers. 
Python3
# Python program to convert# JSON file to CSV  import jsonimport csv  # Opening JSON file and loading the data# into the variable datawith open('data.json') as json_file:    data = json.load(json_file) employee_data = data['emp_details'] # now we will open a file for writingdata_file = open('data_file.csv', 'w') # create the csv writer objectcsv_writer = csv.writer(data_file) # Counter variable used for writing# headers to the CSV filecount = 0 for emp in employee_data:    if count == 0:         # Writing headers of CSV file        header = emp.keys()        csv_writer.writerow(header)        count += 1     # Writing data of CSV file    csv_writer.writerow(emp.values()) data_file.close()
Output: 
And, if you are working on JSON data like the following:
[
    {‘Age’: 18.0, ‘Salary’: 20000.0, ‘Gender’: ‘Male’, ‘Country’: ‘Germany’, ‘Purchased’: ‘N’}
    {‘Age’: 19.0, ‘Salary’: 22000.0, ‘Gender’: ‘Female’, ‘Country’: ‘France’, ‘Purchased’: ‘N’}
    {‘Age’: 20.0, ‘Salary’: 24000.0, ‘Gender’: ‘Female’, ‘Country’: ‘England’, ‘Purchased’: ‘N’}
]
The below code will work perfectly for you (please format the code before running)
Python3
import jsonimport csv with open('G:\Akhil\jsonoutput.json') as json_file:    jsondata = json.load(json_file) data_file = open('G:\Akhil\jsonoutput.csv', 'w', newline='')csv_writer = csv.writer(data_file) count = 0for data in jsondata:    if count == 0:        header = data.keys()        csv_writer.writerow(header)        count += 1    csv_writer.writerow(data.values()) data_file.close()
 
Akhi1
Python json-programs
python-csv
Python-json
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kotlin do-while loop

20 May, 2019
Like Java, do-while loop is a control flow statement which executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, it totally depends upon a Boolean condition at the end of do-while block. It contrast with the while loop because while loop executes the block only when condition becomes true but do-while loop executes the code first and then the expression or test condition is evaluated.
do-while loop working –First of the all the statements within the block is executed, and then the condition is evaluated. If the condition is true the block of code is executed again. The process of execution of code block repeated as long as the expression evaluates to true. If the expression becomes false, the loop terminates and transfers control to the statement next to do-while loop.
It is also known as post-test loop because it checks the condition after the block is executed.
Syntax of the do-while loop-
do {
      // code to run
{
while(condition)

Flowchart:
Kotlin program to find the factorial of a number using do-while loop –
fun main(args: Array<String>) {    var number = 6    var factorial = 1      do {        factorial *= number        number--    }while(number > 0)    println("Factorial of 6 is $factorial")}
Output:
Factorial of 6 is 720
 Kotlin program to print table of 2 using do-while loop –
fun main(args: Array<String>) {    var num = 2    var i = 1      do {        println("2 * $i = "+ num * i)        i++    }while(i < 11)}
Output:
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Kotlin Control-flow
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set a countdown timer in javascript?

You can create a countdown timer in Javascript using the setInterval
method. The setInterval() method, repeatedly calls a function or executes
a code snippet, with a fixed time delay between each call.
To create a countdown, we need to check the difference between current
time and final time and keep updating the countdown. For example,
let countDownDate = new Date("Jul 21, 2020 00:00:00").getTime();
let x = setInterval(() => {
   let now = new Date().getTime();
   let distance = countDownDate - now;
   // Time calculations for days, hours, minutes and seconds
   let days = Math.floor(distance / (1000 * 60 * 60 * 24));
   let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
   let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
   let seconds = Math.floor((distance % (1000 * 60)) / 1000);
   console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
   // If the count down is finished, write some text
   if (distance < 0) {
      clearInterval(x);
      console.log("completed")
   }
}, 1000);
This will give the output −
310d 0h 6m 46s
310d 0h 6m 45s
310d 0h 6m 44s
310d 0h 6m 43s
310d 0h 6m 42s
310d 0h 6m 41s
310d 0h 6m 40s
310d 0h 6m 39s
310d 0h 6m 38s
310d 0h 6m 37s
310d 0h 6m 36s
310d 0h 6m 35s
310d 0h 6m 34s
310d 0h 6m 33s
Usage of -moz-opacity property with CSS

The -moz-opacity property of an image is used to set the opacity of an image. This property is used to create a transparent image in Mozilla. IE uses filter:alpha(opacity=x) to create transparent images.
You can try to run the following code to style an image and set opacity with CSS
<html>
   <head>
   </head>
   <body>
      <img style = "border:1px solid red;-moz-opacity:0.2;filter:alpha(opacity=50);" src="https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg" />
   </body>
</html>
java.time.LocalTime.compareTo() Method Example

The java.time.LocalTime.compareTo(LocalTime other) method compares this time to another time.
Following is the declaration for java.time.LocalTime.compareTo(LocalTime other) method.
public int compareTo(LocalTime other)

other − the other time to compare to, not null.
the comparator value, negative if less, positive if greater.
NullPointerException − the other is null.
The following example shows the usage of java.time.LocalTime.compareTo(LocalTime other) method.
package com.tutorialspoint;

import java.time.LocalTime;

public class LocalTimeDemo {
   public static void main(String[] args) {

      LocalTime time = LocalTime.parse("12:30:30");
      System.out.println(time);  
      LocalTime time1 = LocalTime.parse("12:35:30");
      System.out.println(time1);  
      System.out.println(time1.compareTo(time));  
   }
}
Let us compile and run the above program, this will produce the following result −
12:30:30
12:35:30
1

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: The object element
Right align a Bootstrap dropdown menu

Use the .dropdown-menu-right class in Bootstrap to right align a dropdown menu −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Mobile Phones</h2>
         <p>The following are the mobile phone brands available in India:</p>
         <div class = "dropdown">
            <button class = "btn btn-primary dropdown-toggle" type = "button" data-toggle="dropdown">Companies
            <span class = "caret"></span></button>
            <ul class = "dropdown-menu dropdown-menu-right">
               <li><a href = "#">Apple</a></li>
               <li><a href = "#">Samsung</a></li>
               <li><a href = "#">Oppo</a></li>
            </ul>
         </div>
      </div>
   </body>
</html>
Take Matrix input from user in Python

In this tutorial, we are going to learn how to take matric input in Python from the user.
We can take input from the user in two different ways. Let's see two of them.
Taking all numbers of the matric one by one from the user. See the code below.
# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
   # empty row
   row = []
   for j in range(2):
      # asking the user to input the number
      # converts the input to int as the default one is string
      element = int(input())
      # appending the element to the 'row'
      row.append(element)
   # appending the 'row' to the 'matrix'
   matrix.append(row)
# printing the matrix
print(matrix)
If you run the above code, then you will get the following result.
1
2
3
4
[[1, 2], [3, 4]]
Taking one row at a time with space-separated values. And converting each of them to using map and int function. See the code.
# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
   # taking row input from the user
   row = list(map(int, input().split()))
   # appending the 'row' to the 'matrix'
   matrix.append(row)
# printing the matrix
print(matrix)
If you run the above code, then you will get the following result.
1 2
3 4
[[1, 2], [3, 4]]
If you have queries in the tutorial, mention them in the comment section.
How to build Plotly Choropleth Map with COVID data using Pandas in Google Colab | by Siddhartha Banerjee, PhD | Towards Data Science

Install packages and toolsImport the dataAnalyze the dataGraphically present the data in US choropleth map
Install packages and tools
Import the data
Analyze the data
Graphically present the data in US choropleth map
In Google Colab environment you can pip install packages required for your code. You need plotly-geo , geopands , pyshp and shapely for this project.
!pip install plotly-geo!pip install geopandas!pip install pyshp!pip install shapely
After installing these packages, git clone data repository to import COVID data. I have build a data repository with submodule that takes the latest data from John Hopkins University’s COVID database and import necessary packages.
# Clone repository!git clone https://github.com/sidbannet/US-political-analysis.git%cd ./US-political-analysis!git submodule init!git submodule update --remote
In this step, we are going to import the following US COVID data from John Hopkins University data repository.
In this project, I choose to filter data from geographical regions where both voting records and COVID data are available. Here is how you can filter out COVID data where voting data is also available.
First step of analyzing the COVID data is to put them into pandas data frame as time series of COVID data based on US counties. In this specific example we are using num_days (14 in this example) number of days to analyze COVID time series data. Then calculate three important statistics of all of US counties in pandas dataframe. These are:
Confirmed COVID infection in last 14 days per 100k people in countyGrowth in confirmed COVID cases in last 14 days per 100k people in county.Total number of COVID deaths per million people in county.
Confirmed COVID infection in last 14 days per 100k people in county
Growth in confirmed COVID cases in last 14 days per 100k people in county.
Total number of COVID deaths per million people in county.
These COVID statistics are now available in df_presentation for plotly choropleth maps.
Three choropleth maps are presented here based on
Nominal confirmed COVID cases in last 14 daysNominal growth in COVID infection in last 14 daysNominal total COVID deaths
Nominal confirmed COVID cases in last 14 days
Nominal growth in COVID infection in last 14 days
Nominal total COVID deaths
medium.com
Some rights reserved
MySQL: update field with Group By?

To update field with GROUP BY, use ORDER BY LIMIT with UPDATE command −
mysql> create table DemoTable2018
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20),
   -> EmployeeSalary int
   -> );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2018(EmployeeName,EmployeeSalary) values('Chris',10000);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable2018(EmployeeName,EmployeeSalary) values('David',12560);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable2018(EmployeeName,EmployeeSalary) values('Chris',25400);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2018;
This will produce the following output −
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1          | Chris       | 10000           |
| 2          | David       | 12560           |
| 3          | Chris       | 25400           |
+------------+--------------+----------------+
3 rows in set (0.00 sec)
Here is the query to MySQL update field −
mysql> update DemoTable2018
   -> set EmployeeSalary=EmployeeSalary+2500 where EmployeeName='Chris'
   -> order by EmployeeId limit 1;
Query OK, 1 row affected (0.13 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable2018;
This will produce the following output −
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1          | Chris        | 12500          |
| 2          | David        | 12560          |
| 3          | Mike         | 25400          |
+------------+--------------+----------------+
3 rows in set (0.00 sec)
PyGTK - Scrollbar Class

This class is an abstract base class for gtk.Hscrollbar and gtk.Vscrollbar widgets. Both are associated with an Adjustment object. The position of the thumb of the scrollbar is controlled by scroll adjustments. The attributes of adjustment object are used as follows −
The following program shows an HScale and an HScrollbar widget placed in a VBox added to the toplevel window. Each of them is associated with an adjustment object.
adj1 = gtk.Adjustment(0, 0, 101, 0.1, 1, 1)
self.adj2 = gtk.Adjustment(10,0,101,5,1,1)

An gtk.HScale widget is a slider control attached with adj1. Its update policy, number and position of drawing value are set up as follows −
scale1 = gtk.HScale(adj1)
scale1.set_update_policy(gtk.UPDATE_CONTINUOUS)
scale1.set_digits(1)
scale1.set_value_pos(gtk.POS_TOP)
scale1.set_draw_value(True)

gtk.HScrollbar provides a horizontal scrollbar. It is associated with adj2 object. Its update policy too is set to CONTINUOUS.
self.bar1 = gtk.HScrollbar(self.adj2)
self.bar1.set_update_policy(gtk.UPDATE_CONTINUOUS)

In order to display instantaneous value of the scrollbar, 'value-changed' signal of the adjustment object — adj2 is connected to callback function on_scrolled(). The function retrieves the value property of adjustment object and displays it on a label below the scrollbar.
self.adj2.connect("value_changed", self.on_scrolled)
   def on_scrolled(self, widget, data = None):
   self.lbl2.set_text("HScrollbar value: "+str(int(self.adj2.value)))

Observe the following code −
import gtk

class PyApp(gtk.Window):
   
   def __init__(self):
      super(PyApp, self).__init__()
      self.set_title("Range widgets Demo")
      self.set_default_size(250, 200)
      self.set_position(gtk.WIN_POS_CENTER)
      
      adj1 = gtk.Adjustment(0.0, 0.0, 101.0, 0.1, 1.0, 1.0)
      self.adj2 = gtk.Adjustment(10,0,101,5,1,1)
      
      scale1 = gtk.HScale(adj1)
      scale1.set_update_policy(gtk.UPDATE_CONTINUOUS)
      scale1.set_digits(1)
      scale1.set_value_pos(gtk.POS_TOP)
      scale1.set_draw_value(True)
      
      vb = gtk.VBox()
      vb.add(scale1)
      lbl1 = gtk.Label("HScale")
      
      vb.add(lbl1)
      self.bar1 = gtk.HScrollbar(self.adj2)
      self.bar1.set_update_policy(gtk.UPDATE_CONTINUOUS)
      vb.add(self.bar1)
      self.lbl2 = gtk.Label("HScrollbar value: ")
      
      vb.add(self.lbl2)
      self.adj2.connect("value_changed", self.on_scrolled)
      self.add(vb)
      self.connect("destroy", gtk.main_quit)
      self.show_all()
   
   def on_scrolled(self, widget, data=None):
      self.lbl2.set_text("HScrollbar value: "+str(int(self.adj2.value)))
if __name__ == '__main__':
   PyApp()
   gtk.main()
The above code will generate the following output −
 Print
 Add Notes
 Bookmark this page
How can I make a scatter plot colored by density in Matplotlib?

We can create a dict for color and a value. If the same value comes up, we can use a scatter method and if the closer values have the same set of colors, that could make the plot color denser.
Create a new figure, or activate an existing figure.
Create a new figure, or activate an existing figure.
Add an ~.axes.Axes to the figure as part of a subplot arrangement.
Add an ~.axes.Axes to the figure as part of a subplot arrangement.
Get the x and y values using np.random.normal() method. Draw random samples from a normal (Gaussian) distribution.
Get the x and y values using np.random.normal() method. Draw random samples from a normal (Gaussian) distribution.
Make a color list with red and blue colors.
Make a color list with red and blue colors.
To make it denser, we can store the same color with the same value.
To make it denser, we can store the same color with the same value.
Plot scatter point, a scatter plot of *y* vs. *x* with varying marker size and/or color.
Plot scatter point, a scatter plot of *y* vs. *x* with varying marker size and/or color.
Set the x-view limit.
Set the x-view limit.
Set the y-view limit.
Set the y-view limit.
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import random
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

x = np.random.normal(0.5, 0.3, 10000)
y = np.random.normal(0.5, 0.3, 10000)

colors = ['red', 'blue']

color = dict()
for i in x:
   if i not in color:
      color[i] = colors[random.randint(1, 10) % len(colors)]

ax.scatter(x, y, c=[color.get(i) for i in x])

ax.set_xlim(-0.5, 1.5)
ax.set_ylim(-0.5, 1.5)

plt.show()