code-rag-bench/online-tutorials huggingface dataset:
How can I get the current time and date in Kotlin?

This example demonstrates how to get the current time and date in an Android app Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns: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/dateAndTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="36dp"
      android:textAlignment="center"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      val textView: TextView = findViewById(R.id.dateAndTime)
      val simpleDateFormat = SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z")
      val currentDateAndTime: String = simpleDateFormat.format(Date())
      textView.text = currentDateAndTime
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Program for Fibonacci numbers in C

Given with ‘n’ numbers the task is to generate the fibonacci series till starting from 0 to n where fibonacci series of integer is in the form
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Where, integer 0 and 1 will have fixed space, after that two digits are added for example,
0+1=1(3rd place)
1+1=2(4th place)
2+1=3(5th place) and So on
Sequence F(n) of fibonacci series will have recurrence relation defined as −
Fn = Fn-1 + Fn-2
Where, F(0)=0 and F(1)=1 are always fixed
There can be multiple approaches that can be used to generate the fiboacce series −
Recursive approach − in this, approach function will make a call to itself after every integer value. It is simple and easy to implement but it will lead to exponential time complexity which makes this approach ineffective.
Using For Loop − By using For loop in generating Fibonacci series time complexity can be reduced to O(n) which makes this approach effective.
Input-: n=10
Output-: 0 1 1 2 3 5 8 13 21 34
Start
Step 1 -> Declare function for Fibonacci series
   Void Fibonacci(int n)
      Declare variables as int a=0,b=1,c,i
      Print a and b
      Loop For i=2 and i<n and ++i
         Set c=a+b
         Print c
         Set a=b
         Set b=c
      End
Step 2 -> In main()
   Declare int as 10
   Call Fibonacci(n)
Stop
#include<stdio.h>
void fibonacci(int n){
   int a=0,b=1,c,i;
   printf("fibonacci series till %d is ",n);
   printf("\n%d %d",a,b);//it will print 0 and 1
   for(i=2;i<n;++i) //loop starts from 2 because 0 and 1 are the fixed values that series will take{
      c=a+b;
      printf(" %d",c);
      a=b;
      b=c;
   }
}
int main(){
   int n=10;
   fibonacci(n);
   return 0;
}
fibonacci series till 10 is
0 1 1 2 3 5 8 13 21 34
Return the input of the Entry widget in Tkinter

An Entry widget in Tkinter is nothing but an input widget that accepts single-line user input in a text field. To return the data entered in an Entry widget, we have to use the get() method. It returns the data of the entry widget which further can be printed on the console.
The following example will return the input data that can be used to display in the window with the help of a Label Widget as well.
#Import the required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry
win.geometry("700x250")

# Define a function to return the Input data
def get_data():
   label.config(text= entry.get(), font= ('Helvetica 13'))

#Create an Entry Widget
entry = Entry(win, width= 42)
entry.place(relx= .5, rely= .5, anchor= CENTER)

#Inititalize a Label widget
label= Label(win, text="", font=('Helvetica 13'))
label.pack()

#Create a Button to get the input data
ttk.Button(win, text= "Click to Show", command= get_data).place(relx= .7, rely= .5, anchor= CENTER)

win.mainloop()
If we will execute the above code, it will display a window with an Entry widget and a button to display the input on the screen.
Now, click the "Click to Show" button and it will display the user input on the canvas.
Custom Multiplication in list of lists in Python

Multiplying two lists in python can be a necessity in many data analysis calculations. In this article we will see how to multiply the elements of a list of lists also called a nested list with another list.
In this approach we design tow for loops, one inside another. The outer loop keeps track of number of elements in the list and the inner loop keeps track of each element inside the nested list. We use the * operator to multiply the elements of the second list with respective elements of the nested list.
 Live Demo
listA = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]

multipliers = [5, 11, 0]

# Original list
print("The given list: " ,listA)

# Multiplier list
print(" Multiplier list : " ,multipliers )

# using loops
res = [[] for idx in range(len(listA))]
   for i in range(len(listA)):
      for j in range(len(multipliers)):
         res[i] += [multipliers[i] * listA[i][j]]

#Result
print("Result of multiplication : ",res)
Running the above code gives us the following result −
The given list: [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
Multiplier list : [5, 11, 0]
Result of multiplication : [[10, 55, 25], [33, 22, 88], [0, 0, 0]]
The enumerate method can be used to fetch each element of the nested list and then for loops can be used to do the multiplication.
 Live Demo
listA = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]

multipliers = [5, 11, 0]

# Original list
print("The given list: " + str(listA))

# Multiplier list
print(" Multiplier list : " ,multipliers )

# Using enumerate
res = [[multipliers[i] * j for j in x]
      for i, x in enumerate(listA)]

   #Result
print("Result of multiplication : ",res)
Running the above code gives us the following result −
The given list: [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
Multiplier list : [5, 11, 0]
Result of multiplication : [[10, 55, 25], [33, 22, 88], [0, 0, 0]]
Do Double Equal Sign exist in MySQL?

There is no double equal sign concept. It can be used to compare two values. If you use double equal sign(==) in MySQL, you will get an error message.
Let us verify the concept is true or not. Declare a variable −
mysql> set @Number=10;
Query OK, 0 rows affected (0.00 sec)
Now, compare the above variable value with 10. If both the values are same then the result will be 1 otherwise 0.
Using double equal sign −
mysql> select 10==@Number;
This will produce the following output i.e. an error −
ERROR 1064 (42000): You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version 
for the right syntax to use near '==@Number' at line 1
Let us now change the double equal sign(==) to single equal sign(=) −
mysql> select 10=@Number;
This will produce the following output −
+------------+
| 10=@Number |
+------------+
| 1          |
+------------+
1 row in set (0.00 sec)
How to add components with relative X and Y Coordinates in Java?

To add components with relative X and Y coordinates, you need to set both the gridx and gridy components −
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridy = GridBagConstraints.RELATIVE;
constraints.gridx = GridBagConstraints.RELATIVE;
The following is an example to add components with relative X and Y Coordinates −
package my;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel panel = new JPanel();
      panel.setLayout(new GridBagLayout());
      GridBagConstraints constraints = new GridBagConstraints();
      constraints.gridx = 1;
      constraints.gridy = GridBagConstraints.RELATIVE;
      panel.add(new JButton("1st row 1st column"), constraints);
      panel.add(new JButton("2nd row"), constraints);
      panel.add(new JButton("3rd row"), constraints);
      constraints.gridx = GridBagConstraints.RELATIVE;
      panel.add(new JButton("1st row 2nd column"), constraints);
      panel.add(new JButton("1st row 3rd column"), constraints);
      frame.add(panel);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
Materialize - File

The following example demonstrates different types of File Upload Controls.
materialize_file.htm
<html>
   <head>
      <title>The Materialize File Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">      
      <link rel = "stylesheet"
         href = "https://fonts.googleapis.com/icon?family=Material+Icons">
      <link rel = "stylesheet"
         href = "https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
      <script type = "text/javascript"
         src = "https://code.jquery.com/jquery-2.1.1.min.js"></script>           
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js">
      </script> 
   </head>
   
   <body class = "container">   
      <div class = "row">
         <form class = "col s12">
            <div class = "row">
               <label>Materialize File Input</label>
               <div class = "file-field input-field">
                  <div class = "btn">
                     <span>Browse</span>
                     <input type = "file" />
                  </div>
                  
                  <div class = "file-path-wrapper">
                     <input class = "file-path validate" type = "text"
                        placeholder = "Upload file" />
                  </div>
               </div>
            </div>
            
            <div class = "row">
               <label>Materialize Multi File Input</label>
               <div class = "file-field input-field">
                  <div class = "btn">
                     <span>Browse</span>
                     <input type = "file" multiple />
                  </div>
                  
                  <div class = "file-path-wrapper">
                     <input class = "file-path validate" type = "text"
                        placeholder = "Upload multiple files" />
                  </div>
               </div>    
            </div>
         </form>       
      </div>
   </body>   
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Date.now() function in JavaScript

The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The now() function of the Date object returns the number of milliseconds since 1st Jan 1970.
Its syntax is as follows
Date.now();
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      var birthDate = Date.parse('29 sep 1989 00:4:00 GMT');
      document.write(currentDate);
      document.write(", "+birthDate+", ");
      document.write(currentDate - birthDate);
   </script>
</body>
</html>
1537780591654, 623030640000, 914749951654
You can get the current date using this function but, since it returns the nu8mber of milliseconds from 1st Jan 1970 to get the formatted date pass the value obtained to the Date constructor.
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      document.write(currentDate);
      document.write("<br>");
      document.write(Date(currentDate).toString());
   </script>
</body>
</html>
1539758885099
Wed Oct 17 2018 12:18:05 GMT+0530 (India Standard Time)
Convert dictionary object into string in Python

For data manipulation in python we may come across situation to convert a dictionary object into a string object. This can be achieved in the following ways.
In this straight forward method we simple apply the str() by passing the dictionary object as a parameter. We can check the type of the objects using the type() before and after conversion.
 Live Demo
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
# using str
res = str(DictA)
# Print result
print("Result as string:\n", res)
print("Type of Result: ", type(res))
Running the above code gives us the following result −
Given dictionary :
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type :
Result as string:
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type of Result:
The json module gives us dumps method. Through this method the dictionary object is directly converted into string.
 Live Demo
import json
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
# using str
res = json.dumps(DictA)
# Print result
print("Result as string:\n", res)
print("Type of Result: ", type(res))
Running the above code gives us the following result −
Given dictionary :
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type :
Result as string:
{"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
Type of Result:
How to prevent a dialog from closing when a button is clicked using Kotlin?

This example demonstrates how to prevent a dialog from closing when a button is clicked using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="50dp"
   android:text="Tutorials Point"
   android:textAlignment="center"
   android:textColor="@android:color/holo_green_dark"
   android:textSize="32sp"
   android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val dialog: AlertDialog = AlertDialog.Builder(this)
      .setTitle("My Alert Dialog")
      .setMessage("Do you wanna dismiss this Dialog")
      .setPositiveButton("Ok", null)
      .setNegativeButton("Cancel", null)
      .show();
      val positiveButton: Button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
      positiveButton.setOnClickListener {
         Toast.makeText(this, "Do not dismiss", Toast.LENGTH_SHORT).show();
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
How to set default parameter values to a function in Python?

Python’s handling of default parameter values is one of a few things that can bother most new Python programmers.
What causes issues is using a “mutable” object as a default value; that is, a value that can be modified in place, like a list or a dictionary.
A new list is created each time the function is called if a second argument isn’t provided, so that the EXPECTED OUTPUT is:
[12]
[43]
A new list is created once when the function is defined, and the same list is used in each successive call.
Python’s default arguments are evaluated once when the function is defined, not each time the function is called. This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
What we should do
Create a new object each time the function is called, by using a default arg to signal that no argument was provided (None is often a good choice).
def func(data=[]):
    data.append(1)
    return data
func()
func()
def append2(element, foo=None):
    if foo is None:
        foo = []
    foo.append(element)
    return foo
print(append2(12))
print(append2(43))
[12]
[43]
PHP - Function preg_grep()

array preg_grep ( string $pattern, array $input [, int $flags] );

Returns the array consisting of the elements of the input array that match the given pattern.
If flag is set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.
Returns an array indexed using the keys from the input array.
Returns an array indexed using the keys from the input array.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
   $foods = array("pasta", "steak", "fish", "potatoes");
   
   // find elements beginning with "p", followed by one or more letters.
   $p_foods = preg_grep("/p(\w+)/", $foods);
   
   print "Found food is " . $p_foods[0];
   print "Found food is " . $p_foods[1];
?>
This will produce the following result −
Found food is pastaFound food is


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Python - API.statuses_lookup() in Tweepy - GeeksforGeeks

05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The statuses_lookup() method of the API class in Tweepy module is used to get the statuses specified by the status IDs, up to 100.
Syntax : API.statuses_lookup(parameters)
Parameters :
id_ : A list of Tweet IDs to fetch, up to 100
trim_user : A boolean indicating if user IDs should be provided, instead of complete user objects, the default value is False.
Returns : a list of objects of the class Status
Example 1 :
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # list of status IDs to be fetched id_ = [1266978261701210112, 1266735261012111360, 1266342841648898049]  # fetching the statusesstatuses = api.statuses_lookup(id_)  # printing the statusesfor status in statuses:    print("The status " + str(status.id) + " is posted by " + status.user.screen_name)    print("This status says : \n\n" + status.text, end = "\n\n")
Output :
The status 1266978261701210112 is posted by geeksforgeeks
This status says : 

Avoid errors, not client calls
.
Geeks, Keep this going...
.
#sundayvibes #programming #programmingmemes #coding https://t.co/JkA5iStofZ

The status 1266735261012111360 is posted by geeksforgeeks
This status says : 

With the access to our Job Portal, find the jobs that are best for you & experience happy placement journey....
.
L... https://t.co/mzMMFVzjMv

The status 1266342841648898049 is posted by geeksforgeeks
This status says : 

My reaction to this Lockdown : 

"Der Lagi Lekin... Maine Ab Hai Jeena Seekh Liya" 

What's your reaction to it?
.... https://t.co/nH9L0eewSr

Example 2: Using the statuses_lookup() method with the trim_user parameter.
# list of status IDs to be fetched id_ = [1266978261701210112, 1266735261012111360, 1266342841648898049]  # fetching the statusesstatuses = api.statuses_lookup(id_, trim_user = True)  # printing the statusesfor status in statuses:    print(status.user.id)
Output :
57741058
57741058
57741058

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
How to draw circle in HTML page?

To draw a circle in HTML page, use SVG or canvas. You can also draw it using CSS, with the border-radius property.
You can try to run the following code to learn how to draw a circle in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #circle {
            width: 50px;
            height: 50px;
            -webkit-border-radius: 25px;
            -moz-border-radius: 25px;
            border-radius: 25px;
            background: blue;
         }
      </style>
   <head>
   <body>
      <div id="circle"></div>
   </body>
</html>
queue::push() and queue::pop() in C++ STL

In this article we will be discussing the working, syntax and examples of queue::push() and queue::pop() functions in C++ STL.
Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.
queue::push() is an inbuilt function in C++ STL which is declared in  header file. queue::push() is used to push or insert a new element at the end or at the back of the queue container. push() accepts one parameter, that is the element which we want to push/insert in the associated queue container, also this function increases the size of container by 1.
This function further calls push_back() which helps in easy insertion of the element at the back of the queue.
myqueue.push(type_t& value);
This function accepts one parameter the value which is of type_t that is the type of elements in the queue container.
This function returns nothing.
Input: queue<int> myqueue = {10, 20 30, 40};
      myqueue.push(23);
Output:
      Elements in the queue are= 10 20 30 40 23
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   for(int i=0 ;i<=5 ;i++){
      Queue.push(i);
   }
      cout<<"Elements in queue are : ";
   while (!Queue.empty()){
      cout << ' ' << Queue.front();
      Queue.pop();
   }
}
If we run the above code it will generate the following output −
Elements in queue are : 0 1 2 3 4 5
queue::pop() is an inbuilt function in C++ STL which is declared in  header file. queue::pop() is used to push or delete an existing element from the beginning or start of the queue container. pop() accepts no parameter, and deletes the element from the beginning of the queue associated with the function and reduces the size of the queue container by 1.
myqueue.pop();
This function accepts no parameters
This function returns nothing.
Input: queue myqueue = {10, 20, 30, 40};
      myqueue.pop();
Output:
      Elements in the queue are= 20 30 40
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   for(int i=0 ;i<=5 ;i++){
      Queue.push(i);
   }
   for(int i=0 ;i<5 ;i++){
      Queue.pop();
   }
   cout<<"Element left in queue is : ";
   while (!Queue.empty()){
      cout << ' ' << Queue.front();
      Queue.pop();
   }
}
If we run the above code it will generate the following output −
Element left in queue is : 5
How to add a column in MongoDB collection?

To add a column, you need to update the collection. The syntax is as follows −
db.getCollection(yourCollectionName).update({}, {$set: {"yourColumnName": "yourValue"}},false,true);
To understand the above syntax, let us create a collection with documents −
> db.addColumnDemo.insertOne({"StudentId":101,"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04d66af5e889d7a519950f")
}
> db.addColumnDemo.insertOne({"StudentId":102,"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04d673f5e889d7a5199510")
}
> db.addColumnDemo.insertOne({"StudentId":103,"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04d67bf5e889d7a5199511")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.addColumnDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e04d66af5e889d7a519950f"),
   "StudentId" : 101,
   "StudentName" : "Chris"
}
{
   "_id" : ObjectId("5e04d673f5e889d7a5199510"),
   "StudentId" : 102,
   "StudentName" : "Robert"
}
{
   "_id" : ObjectId("5e04d67bf5e889d7a5199511"),
   "StudentId" : 103,
   "StudentName" : "David"
}
Here is the query to add a column in MongoDB −
> db.getCollection('addColumnDemo').update({}, {$set: {"StudentCityName": "New York"}},false,true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Following is the query to display all documents from a collection with the help of find() method −
> db.addColumnDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e04d66af5e889d7a519950f"),
   "StudentId" : 101,
   "StudentName" : "Chris",
   "StudentCityName" : "New York"
}
{
   "_id" : ObjectId("5e04d673f5e889d7a5199510"),
   "StudentId" : 102,
   "StudentName" : "Robert",
   "StudentCityName" : "New York"
}
{
   "_id" : ObjectId("5e04d67bf5e889d7a5199511"),
   "StudentId" : 103,
   "StudentName" : "David",
   "StudentCityName" : "New York"
}
Display tooltip text while hovering a textbox in jQuery

For this, use jQuery(selector).toolTip().
Following is the code: −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<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>
<body>
   <label>Write Your Favourite Subject Name:</label>
   <input id="demoTooltip" title="Your Favourite Subject may be JavaScript...">
</body>
<script>
   jQuery(".demoTooltip").toolTip()
</script>
</html>
To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor.
The output is as follows −
When you will hover the mouse inside the text box, you will get your tooltip −
Your Favourite Subject may be JavaScript...
Displayed in the below screenshot as well −
Python | Scipy integrate.quad() method - GeeksforGeeks

23 Jan, 2020
With the help of scipy.integrate.quad() method, we can get the integration of a given function from limit a to b by using scipy.integrate.quad() method.
Syntax : scipy.integrate.quad(func, a, b)
Return : Return the integration of a polynomial.
Example #1 :In this example we can see that by using scipy.integrate.quad() method, we are able to get the integration of a polynomial from limit a to b by using this method.
# import scipy.integrate.quadfrom scipy import integrategfg = lambda x: x**2  # using scipy.integrate.quad() methodgeek = integrate.quad(gfg, 0, 3)  print(geek)
Output :
9.000000000000002
Example #2 :
# import scipy.integrate.quadfrom scipy import integrategfg = lambda x: x**2 + x + 1  # using scipy.integrate.quad() methodgeek = integrate.quad(gfg, 1, 4)  print(geek)
Output :
31.5
Python-scipy
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
Angular10 Trigger Animation - GeeksforGeeks

02 Jun, 2021
In this article, we are going to see what is trigger in Angular 10 and how to use it.
The trigger in Angular10 is used to create an animation trigger containing state and transition of the animation.
Syntax:
animate(name | definations)
NgModule: Module used by trigger is:
animations
 
Approach: 
Create an angular app that to be used.
In app.module.ts, import BrowserAnimationsModule.
In app.component.html, make a div which will contain the animation element.
In app.component.ts, import the trigger, state, style, transition, animate to be used.
Make the trigger containing state and transition for the animation.
Serve the angular app using ng serve to see the output.
Parameters:
Name: Sets an identifying string.
definations: Sets an animation defination object.
Return Value:
AnimationTriggerMetadata: An object that encapsulates the trigger data.
Example:
app.module.ts
import { LOCALE_ID, NgModule } from '@angular/core';  import { BrowserModule }from '@angular/platform-browser';import {BrowserAnimationsModule} from '@angular/platform-browser/animations';import { AppRoutingModule }from './app-routing.module';import { AppComponent }from './app.component';  @NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    AppRoutingModule,    BrowserAnimationsModule  ],  providers: [      { provide: LOCALE_ID, useValue: 'en-GB' },  ],  bootstrap: [AppComponent]})export class AppModule { }
app.component.ts
import {   // Trigger is imported here  trigger,   state,   style,   transition,   animate } from '@angular/animations';import { Component } from '@angular/core';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ],  animations: [      // Trigger is used here    trigger('geek',[      state('green', style({        'background-color': 'green',        transform: 'translateX(0)'      })),      state('blu', style({        'background-color': '#49eb34',        transform: 'translateX(0)'      })),      transition('green => blu',animate(1200)),      transition('blu => green',animate(1000))    ])  ]})export class AppComponent  {  state = 'green';  anim(){    this.state == 'green' ?    this.state = 'blu' : this.state = 'green';  }}
app.component.html
<h1>GeeksforGeeks</h1><button (click)='anim()'>Animate</button><br><br><div   style="width: 150px; height: 100px; border-radius: 5px;"  [@geek]='state'></div>
Output:
Reference: https://angular.io/api/animations/trigger
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Golang - Environment Variables - GeeksforGeeks

04 Feb, 2021
An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc.
In Golang, we can use the os package to read and write environment variables.
1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any.
os.Setenv(key,value)  
2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value.
os.Getenv(key)
3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any.
os.Unsetenv(key)
4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned.
os.LookupEnv(key)
5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the “key=value” format.
os.Environ()
6. Delete all environment variables with os.Clearenv().
os.Clearenv()
Example 1:
Go
// Golang program to show the usage of// Setenv(), Getenv and Unsetenv method  package main  import (    "fmt"    "os")  // Main functionfunc main() {      // set environment variable GEEKS    os.Setenv("GEEKS", "geeks")      // returns value of GEEKS    fmt.Println("GEEKS:", os.Getenv("GEEKS"))      // Unset environment variable GEEKS    os.Unsetenv("GEEKS")      // returns empty string and false,    // because we removed the GEEKS variable    value, ok := os.LookupEnv("GEEKS")      fmt.Println("GEEKS:", value, " Is present:", ok)  }
Output:
Example 2:
Go
// Golang program to show the// usage of os.Environ() Methodpackage main  import (    "fmt"    "os")  // Main functionfunc main() {      // list all environment variables and their values    for _, env := range os.Environ() {        fmt.Println(env)    }}
Output:
Example 3: 
Go
// Golang program to show the// usage of os.Clearenv() Methodpackage main  import (    "fmt"    "os")  // Main functionfunc main() {      // this delete's all environment variables    // Don't try this in the home environment,    // if you do so  you will end up deleting    // all env variables    os.Clearenv()      fmt.Println("All environment variables cleared")  }
Output:
All environment variables cleared
Golang-Packages
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Convert text to lowercase with CSS

To convert text to lowercase with CSS, use the text-transform property with value lowercase.
You can try to run the following code to convert text to lowercase:
<html>
   <head>
   </head>
   <body>
      <p>Normal Text</p>
      <p style = "text-transform:lowercase;">
         Normal Text! This will be in lowercase!
      </p>
   </body>
</html>
Tryit Editor v3.7

Tryit: Use a PNG image as the mask layer
Why do we use const qualifier in C++?

We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value. So you should declare that as a const.
Objects declared with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in a program, it may not be stored at all.  For example,
#include<iostream>
using namespace std;
int main() {
   const int x = 10;
   x = 12;
   return 0;
}
This program would produce an error as we have tried to reassign a const value.
Python Pandas – Count the Observations

To count the observations, first use the groupby() and then use count() on the result. At first, import the required library −
dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})
Group the column with duplicate values −
group = dataFrame.groupby("Product Category")

Get the count −
group.count()
Following is the code −
import pandas as pd

# create a dataframe
dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})

# dataframe
print"Dataframe...\n",dataFrame

# count the observations
group = dataFrame.groupby("Product Category")

print"\nResultant DataFrame...\n",group.count()
This will produce the following output −
Dataframe...
   Product Category   Product Name   Quantity
0          Computer       Keyboard        10
1      Mobile Phone        Charger        50
2       Electronics        SmartTV        10
3       Electronics         Camera        20
4          Computer   Graphic Card        25
5      Mobile Phone       Earphone        50

Resultant DataFrame...
                   Product Name   Quantity
Product Category
Computer                     2           2
Electronics                  2           2
Mobile Phone                 2           2
How to implement a program to count the number in Java?

The program uses a JLabel to hold a count label, a JTextField component to hold the number count, JButton component to create add, remove and reset buttons. When we click the add button, the count in the JTextField will get incremented by '1' and by clicking the remove button the count will be decremented by '1'. If we click the Reset button, it will reset the count to '0'.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CounterTest extends JFrame implements ActionListener {
   private JLabel label;
   private JTextField text;
   private JButton addBtn, removeBtn, resetBtn;
   private int count;
   public CounterTest() {
      setTitle("Counter Test");
      setLayout(new FlowLayout());
      count = 0;
      label = new JLabel("Count:");
      text = new JTextField("0", 4);
      addBtn = new JButton("Add");
      removeBtn = new JButton("Remove");
      resetBtn = new JButton("Reset");
      addBtn.addActionListener(this);
      removeBtn.addActionListener(this);
      resetBtn.addActionListener(this);
      add(label);
      add(text);
      add(addBtn);
      add(removeBtn);
      add(resetBtn);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public void actionPerformed(ActionEvent ae) {
      if (ae.getSource() == addBtn) {
         count++; // increment the coiunt by 1
         text.setText(String.valueOf(count));
         repaint();
      } else if (ae.getSource() == removeBtn) {
         count--; // decrement the count by 1
         text.setText(String.valueOf(count));
         repaint();
      } else if (ae.getSource() == resetBtn) {
         count = 0; // reset the count to 0
         text.setText(String.valueOf(count));
         repaint();
      }
   }
   public static void main(String[] args) {
      new CounterTest();
   }
}
Iterate through elements of TreeSet in Java

First, create a TreeSet and add elements −
TreeSet<String> set = new TreeSet<String>();
set.add("34");
set.add("12");
set.add("67");
set.add("54");
set.add("76");
set.add("49");
Now, let us iterate through the elements −
Iterator<String> i = set.iterator();
while(i.hasNext()){
   System.out.println(i.next());
}
The following is an example that iterate through elements of TreeSet −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("34");
      set.add("12");
      set.add("67");
      set.add("54");
      set.add("76");
      set.add("49");
      System.out.println("TreeSet elements...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
   }
}
TreeSet elements...
12
34
49
54
67
76
How to create Python dictionary with duplicate keys?

Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround. This class is defined in collections module.
Use list as default factory for defaultdict object
>>> from collections import defaultdict
>>> d=defaultdict(list)
Here is a list of tuples each with two items. First item is found to be repeatedly used. This list is converted in defaultdict
>>> for k,v in l:
      d[k].append(v)
Convert this defaultdict in a dictionary object using dict() function
>>> dict(d)
{1: [111, 'aaa'], 2: [222, 'bbb'], 3: [333, 'ccc']}
Lodash _.toArray() Method - GeeksforGeeks

03 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.toArray() method is used to convert the given value to an array.
Syntax:
_.toArray( value )

Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to convert.
Return Value: This method returns the converted array.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");        // Use of _.toArray() method console.log(_.toArray(null)); console.log(_.toArray('gfg'));
Output:
[]
['g', 'f', 'g']

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");        // Use of _.toArray() method console.log(_.toArray(10)); console.log(_.toArray({ 'html': 1,     'css': 2, 'javascript': 3 }));
 Output:
[]
[1, 2, 3]

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
C - if...else statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
The syntax of an if...else statement in C programming language is −
if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}

If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 100;
 
   /* check the boolean condition */
   if( a < 20 ) {
      /* if condition is true then print the following */
      printf("a is less than 20\n" );
   } else {
      /* if condition is false then print the following */
      printf("a is not less than 20\n" );
   }
   
   printf("value of a is : %d\n", a);
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if...else if..else statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any else if's.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
   /* Executes when the boolean expression 2 is true */
} else if( boolean_expression 3) {
   /* Executes when the boolean expression 3 is true */
} else {
   /* executes when the none of the above condition is true */
}

#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 100;
 
   /* check the boolean condition */
   if( a == 10 ) {
      /* if condition is true then print the following */
      printf("Value of a is 10\n" );
   } else if( a == 20 ) {
      /* if else if condition is true */
      printf("Value of a is 20\n" );
   } else if( a == 30 ) {
      /* if else if condition is true  */
      printf("Value of a is 30\n" );
   } else {
      /* if none of the conditions is true */
      printf("None of the values is matching\n" );
   }
   
   printf("Exact value of a is: %d\n", a );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
None of the values is matching
Exact value of a is: 100

 Print
 Add Notes
 Bookmark this page