code-rag-bench/online-tutorials huggingface dataset:
C - typedef

The C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −
typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example..
BYTE  b1, b2;

By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −
typedef unsigned char byte;

You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
#include <stdio.h>
#include <string.h>
 
typedef struct Books {
   char title[50];
   char author[50];
   char subject[100];
   int book_id;
} Book;
 
int main( ) {

   Book book;
 
   strcpy( book.title, "C Programming");
   strcpy( book.author, "Nuha Ali"); 
   strcpy( book.subject, "C Programming Tutorial");
   book.book_id = 6495407;
 
   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Book  title : C Programming
Book  author : Nuha Ali
Book  subject : C Programming Tutorial
Book  book_id : 6495407

#define is a C-directive which is also used to define the aliases for various data types similar to typedef but with the following differences −
typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc.
typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc.
typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.
typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.
The following example shows how to use #define in a program −
#include <stdio.h>
 
#define TRUE  1
#define FALSE 0
 
int main( ) {
   printf( "Value of TRUE : %d\n", TRUE);
   printf( "Value of FALSE : %d\n", FALSE);

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of TRUE : 1
Value of FALSE : 0

 Print
 Add Notes
 Bookmark this page
Changing the color a Tkinter rectangle on clicking

The Canvas widget in Tkinter is one of the versatile widgets in Tkinter which is used for developing dynamic GUI interface of the application such as shapes, logo, arcs, animating objects, and many more. With the help of the create_rectangle(top, left, bottom, right, **options) constructor, we can create a rectangular shape in our canvas widget. All the Canvas items support multiple features such as shapes property, size, color, outline, etc.
Let us suppose that we want to change the color of the drawn rectangle with the help of a button event. Defining a callback function that extends the property such as fill= color would change the color of the rectangle.
# Import the required libraries
from tkinter import *

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

# Set the geometry of Tkinter Frame
win.geometry("700x250")

# Define a function to change the color of the rectangle
def change_color(*args):
   canvas.itemconfig(shape, fill='blue')

# Add a canvas inside the frame
canvas = Canvas(win, width=500, height=250)
canvas.pack()

# Add a rectangle inside the canvas widget
shape = canvas.create_rectangle(500, 100, 50, 50, fill='red')

# Add a button to change the color of the rectangle
button = Button(win, text="Change Color", font=('Helvectica 11'),
command = lambda: change_color(canvas))
button.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()
If we run the above code, it will display a window with a rectangle and a button widget.
On clicking the "Change Color" button, it will change the color of the rectangle to blue.
How can we implement Flow API using Publisher-Subscriber in Java 9?

Flow API (java.util.concurrent.Flow) has introduced in Java 9. It helps to understand different ways in which the Publisher and Subscriber interfaces interact to perform desired operations.
Flow API consists of Publisher, Subscriber, Subscription, and Processor interfaces, which can be based on reactive stream specification.
In the below example, we can implement Flow API by using Publisher-Subscriber interfaces.
import java.util.concurrent.Flow.Publisher;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;

public class FlowAPITest {
   public static void main(String args[]) {
      Publisher<Integer> publisherSync = new Publisher<Integer>() {   // Create publisher
         @Override
         public void subscribe(Subscriber<? super Integer> subscriber) {
            for(int i = 0; i < 10; i++) {
               System.out.println(Thread.currentThread().getName() + " | Publishing = " + i);
               subscriber.onNext(i);
            }
            subscriber.onComplete();
         }
      };
      Subscriber<Integer> subscriberSync = new Subscriber<Integer>() {   // Create subscriber
         @Override
         public void onSubscribe(Subscription subscription) {
         }
         @Override
         public void onNext(Integer item) {
            System.out.println(Thread.currentThread().getName() + " | Received = " + item);
            try {
               Thread.sleep(100);
            } catch(InterruptedException e) {
               e.printStackTrace();
            }
         }
         @Override
         public void onError(Throwable throwable) {
         }
         @Override
         public void onComplete() {
         }
      };
      publisherSync.subscribe(subscriberSync);
   }
}
main | Publishing = 0
main | Received = 0
main | Publishing = 1
main | Received = 1
main | Publishing = 2
main | Received = 2
main | Publishing = 3
main | Received = 3
main | Publishing = 4
main | Received = 4
main | Publishing = 5
main | Received = 5
main | Publishing = 6
main | Received = 6
main | Publishing = 7
main | Received = 7
main | Publishing = 8
main | Received = 8
main | Publishing = 9
main | Received = 9
spaCy - Command Line Helpers

This chapter gives information about the command line helpers used in spaCy.
spaCy v1.7.0 and above comes with new command line helpers. It is used to download as well as link the models. You can also use it to show the useful debugging information. In short, command line helpers are used to download, train, package models, and also to debug spaCy.
You can check the available commands by using spacy - -help command.
The example to check the available commands in spaCy is given below −
C:\Users\Leekha>python -m spacy --help
The output shows the available commands.
Available commands
download, link, info, train, pretrain, debug-data, evaluate, convert, package, init-model, profile, validate

The commands available in spaCy are given below along with their respective descriptions.
To download models for spaCy.
To create shortcut links for models.
To print the information.
To check compatibility of the installed models.
To convert the files into spaCy's JSON format.
To pre-train the “token to vector (tok2vec)” layer of pipeline components.
To create a new model directory from raw data.
To evaluate a model's accuracy and speed.
To generate a model python package from an existing model data directory.
To analyse, debug, and validate our training and development data.
To train a model.
 Print
 Add Notes
 Bookmark this page
MySQL query to increment one of the column values

Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(100),
-> Score int
-> );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Score) values('John',68);
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name,Score) values('Carol',98);
Query OK, 1 row affected (0.27 sec)

mysql> insert into DemoTable(Name,Score) values('David',89);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name,Score) values('Robert',67);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------+
| Id | Name   | Score |
+----+--------+-------+
| 1 | John    | 68    |
| 2 | Carol   | 98    |
| 3 | David   | 89    |
| 4 | Robert  | 67    |
+----+--------+-------+
4 rows in set (0.00 sec)
Following is the query to increment one of the column values by 1 −
mysql> update DemoTable set Score=Score+1 where Id=3;
Query OK, 1 row affected (0.22 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------+
| Id | Name   | Score |
+----+--------+-------+
| 1 | John    | 68    |
| 2 | Carol   | 98    | 
| 3 | David   | 90    |
| 4 | Robert  | 67    |
+----+--------+-------+
4 rows in set (0.00 sec)
Close Bootstrap class

Use the generic close icon for dismissing content like models and alerts. Use the class close to getting the close icon.
You can try to run the following code to implement a close Bootstrap class
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>
      <p>Close Icon:
         <button type = "button" class = "close" aria-hidden = "true">
            ×
         </button>
      </p>
   </body>
</html>
How to set the layout weight of a TextView programmatically in Android using Kotlin?

This example demonstrates how to set the layout weight of a TextView programmatically in Android.
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"
   android:gravity="center"
   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" />
<Button
   android:id="@+id/button"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:onClick="expand"
   android:text="Hello World"
   android:textSize="24sp"
   android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   fun expand(view: View) {
      val height = RelativeLayout.LayoutParams.WRAP_CONTENT
      val width = 200
      val layoutParams = RelativeLayout.LayoutParams(width, height)
      val button: Button = findViewById(R.id.button)
      button.layoutParams = layoutParams
   }
}
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.
What is the meaning of ‘empty set’ in MySQL result set?

If there is ‘empty set’ in the result set of MySQL query then it means that MySQL is returning no rows and no error also in the query. It can be understood with the help of the following example −
mysql> Select * from Student_info WHERE Name = 'ABCD';
Empty set (0.00 sec)
We can see the empty set and execution time as output. It means that the query is correct but the MySQL table is not having the name ‘ABCD’.
PyQt5 - QDockWidget - GeeksforGeeks

11 Aug, 2021
QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Dock windows can be moved inside their current area, moved into new areas and floated (e.g., undocked) by the end-user. The QDockWidget API allows the programmer to restrict the dock widgets ability to move, float and close, as well as the areas in which they can be placed.Below is how the dock widget looks like  
When we open this widget it looks like this  
Example : We will create a dock widget and add push button to it and when push button will get pressed a message will get printed on the labelBelow is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 500, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating dock widget        dock = QDockWidget("GeeksforGeeks", self)         # push button        push = QPushButton("Press", self)         # setting widget to the dock        dock.setWidget(push)         # setting geometry tot he dock widget        dock.setGeometry(100, 0, 200, 30)          # creating a label        label = QLabel("GeeksforGeeks", self)         # setting geometry to the label        label.setGeometry(100, 200, 300, 80)         # making label multi line        label.setWordWrap(True)         # adding action to the push button        push.clicked.connect(lambda: label.setText("Dock Widget's Push button pressed"))       # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
singghakshay
Python PyQt-QDockWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
Creating a Multilevel Inheritance Hierarchy in Java

Inheritance involves an object acquiring the properties and behaviour of another object. So basically, using inheritance can extend the functionality of the class by creating a new class that builds on the previous class by inheriting it.
Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A.
A program that demonstrates a multilevel inheritance hierarchy in Java is given as follows:
 Live Demo
class A {
   void funcA() {
      System.out.println("This is class A");
   }
}
class B extends A {
   void funcB() {
      System.out.println("This is class B");
   }
}
class C extends B {
   void funcC() {
      System.out.println("This is class C");
   }
}
public class Demo {
   public static void main(String args[]) {
      C obj = new C();
      obj.funcA();
      obj.funcB();
      obj.funcC();
   }
}
This is class A
This is class B
This is class C
Validate the ZIP code with Java Regular expressions

In order to match the ZIP code using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression.
Declaration − The java.lang.String.matches() method is declared as follows −
public boolean matches(String regex)
Let us see a program which validates the ZIP code with Java Regular Expressions −
 Live Demo
public class Example {
   public static void main( String[] args ) {
      System.out.println(zipIndia("400709"));
      System.out.println(zipUS("10060"));
   }
   // validate zip
   public static boolean zipIndia( String z ) {
      return z.matches( "\\d{6}" );
   }
   public static boolean zipUS( String z ) {
      return z.matches( "\\d{5}" );
   }
}
true
true
Quickly Transfer a Kaggle dataset into a Google bucket | by Alex Federation | Towards Data Science

15 days. I was shocked at how long it was going to take to upload a relatively small (20GB) image dataset from my local machine to a Google Cloud Platform (GCP) bucket.
In this article, I’ll go through the alternative approach that shortened this process to a 2-hour operation using a GCP Virtual Machine (VM). The key is creating a VM in the same zone as your bucket, downloading the file there and then transferring it to the bucket.
If you don’t have a bucket, go set that up first, and remember what zone you decide to use. You can use all the standard settings without issue.
The next step was to create a VM. I went with 4 cores, so we could take advantage of the multiprocessing option during the image transfer. Other than that, it was a pretty standard set-up, keeping all the defaults. The exceptions were expanding startup disk to 100 GB to accommodate the unzipped data and using Ubuntu 18 LTS, just a personal preference.
Once the VM spun up, I connected with the ssh tool provided by the Google CLI (which you may need to install on your local machine)
gcloud compute ssh --project [NAME OF YOUR PROJECT] --zone [ZONE NAME] [NAME OF VM]
Once on the VM, I installed pip and the kaggle API.
## Install pip> curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py> sudo apt-get install python3-distutils> sudo python3 get-pip.py## Install kaggle API> pip install kaggle
In order to download files from Kaggle, you need an API token saved on the VM. You can go into your Kaggle account, download a new token and scp it onto the VM. Once on the VM, create a hidden folder called “.kaggle” and move the key there
On your local machine:
> gcloud compute scp Downloads/kaggle.json kaggle-download:~
On the VM:
> mkdir .kaggle> mv kaggle.json .kaggle
At this point, the Kaggle API should be good to go! Navigate to the competition or dataset you’re interested in and copy the API command into the VM and the download should start. Many of the datasets are zipped, so you’ll need to install the unzip tool and extract the data.
> sudo apt-get install unzip> unzip [DATASET].zip
Then all that’s left is to authenticate your google account on the VM and transfer the data! The -m flag allows us to use multithread processing and the -r recursively transfers everything in the data folder. For me, it took ~2h to run this whole process for ~20GB of data.
> gcloud auth login> gsutil -m cp -r [DATA FOLDER] gs://[BUCKET NAME]
Remember to kill the VM when you finish. I just delete it and spin up a new one whenever I need to download something new. Happy Kaggling!
Bootstrap 4 .card-footer class

Use the card-footer class in Bootstrap 4 to set the footer of a Bootstrap card.
Add it using the class −
<div class="card-footer">
  Add footer message here
</div>
The card-footer class comes after the card-header and card-body class −
<div class="card">
  <div class="card-header">Details</div>
  <div class="card-body">Timings: 4PM - 8PM</div>
  <div class="card-footer">Reach before 4PM</div>
</div>
You can try to run the following code to implement the card-footer class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h2>Conference</h2>
    <div class="card">
      <div class="card-header">Details</div>
      <div class="card-body">Timings: 4PM - 8PM</div>
      <div class="card-footer">Reach before 4PM</div>
    </div>
  </div>

</body>
</html>
Java Program to fill an array with random numbers

Let us first crate an array −
double[] arr = new double[5];
Now, create Random class object −
Random randNum = new Random();
Now, fill the above array with random numbers −
for (int i = 0; i < 5; i++) {
arr[i] = randNum.nextInt();
}
 Live Demo
import java.util.Arrays;
import java.util.Random;
public class Demo {
   public static void main(String args[]) {
      double[] arr = new double[5];
      Random randNum = new Random();
      for (int i = 0; i < 5; i++) {
         arr[i] = randNum.nextInt();
      }
      System.out.println("Random numbers = "+Arrays.toString(arr));
   }
}
Random numbers = [-6.59888981E8, 1.141160731E9, -9.931249E8, 1.335266582E9, 8.27918412E8]
Google AMP - Caching

Google amp provides caching facility which is a proxy based content delivery network to serve pure amp pages. Amp cache is available by default to all the valid amp pages. It helps in rendering the pages faster in comparison to non amp pages.
Currently, there are 2 amp cache providers Google AMP Cache and Cloudflare AMP Cache. As said earlier, amp caching is made available to all valid amp pages. Incase if the user does not want to use amp cache feature, you need to make your amp page invalid. Amp cache is not applied for invalid amp pages.
The moment Google search crawls and finds amp () for the html content, it considers for caching.
In this section, we will discuss various components of Google amp cache URL.
Google AMP adds a subdomain to the url requested. There are some rules followed for amp cache subdomain url. They are shown here −
Converting the AMP document domain from IDN (Punycode) to UTF-8.
Converting the AMP document domain from IDN (Punycode) to UTF-8.
The dash (-) in the url is replaced with two dashes (--)
The dash (-) in the url is replaced with two dashes (--)
The dot (.) in the url is replaced with dash(-).
The dot (.) in the url is replaced with dash(-).
Converting back to IDN (Punycode).
Converting back to IDN (Punycode).
For example pub.mypage will be replaced with pub-mypage.cdn.ampproject.com. Here cdn.ampproject.com is the subdomain added by google amp. Now the cached url is Pub-mypage.cdn.ampproject.com.
The content type available are c for AMP HTML Document, i for image and r for resource like for example font. You will get 404 error if the content type does not match with the ones specified.
If s is present, the content will be fetched from the origin https:// ; else, it will fetch from http://
An example for the request made to cached image from https and http is shown here −
https://pub-mypage-com.cdn.ampproject.org/i/s/examples/images/testimage.png
So, in the above example the url is having i which means image and s for https −
http://pub-mypage-com.cdn.ampproject.org/i/examples/images/testimage.png
Thus, in the above example the url is having i which means image and there is no s, so the url will be fetched from http.
For a font cached file, the url will be as follows −
https://pub-mypage-com.cdn.ampproject.org/r/s/examples/themes/lemon/fonts/Genericons.ttf
Content type r is used for resources like fonts and s for secure url.
For html document the url is as follows −
https://pub-mypage-com.cdn.ampproject.org/c/s/trends/main.html
It has c in the url is for HTML document, followed by s which is for https://
Google AMP cache uses http headers like Max-age to decide whether the content cache is stale or fresh and automatically sends fresh requests and updates the contents so that next user gets the contents updated.

    20 Lectures 
     2.5 hours 

 Asif Hussain

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    33 Lectures 
     2.5 hours 

 Sasha Miller

    22 Lectures 
     1.5 hours 

 Zach Miller

    16 Lectures 
     1.5 hours 

 Sasha Miller

    23 Lectures 
     2.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Date setTime() method in Java with Examples

07 Nov, 2019
The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT.Syntax:
public void setTime(long time)

Parameters: The function accepts a single parameter time which specifies the number of milliseconds.
Return Value: It method has no return value.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
Program 1:
// Java code to demonstrate// setTime() function of Date class  import java.util.Date;import java.util.Calendar;public class GfG {    // main method    public static void main(String[] args)    {          // creating a date object with specified time.        Date dateOne = new Date();          System.out.println("Date initially: "                           + dateOne);          // Sets the time        dateOne.setTime(1000);          // Prints the time        System.out.println("Date after setting"                           + " the time: "                           + dateOne);    }}
Date initially: Wed Jan 02 09:34:03 UTC 2019
Date after setting the time: Thu Jan 01 00:00:01 UTC 1970

Program 2:
// Java code to demonstrate// setTime() function of Date class  import java.util.Date;import java.util.Calendar;public class GfG {    // main method    public static void main(String[] args)    {          // creating a Calendar object        Calendar c1 = Calendar.getInstance();          // set Month        // MONTH starts with 0 i.e. ( 0 - Jan)        c1.set(Calendar.MONTH, 11);          // set Date        c1.set(Calendar.DATE, 05);          // set Year        c1.set(Calendar.YEAR, 1996);          // creating a date object with specified time.        Date dateOne = c1.getTime();          System.out.println("Date initially: "                           + dateOne);          // Sets the time        dateOne.setTime(1000999);          // Prints the time        System.out.println("Date after setting"                           + " the time: "                           + dateOne);    }}
Date initially: Thu Dec 05 09:32:53 UTC 1996
Date after setting the time: Thu Jan 01 00:16:40 UTC 1970

ManasChhabra2
Java - util package
Java-Functions
Java-util-Date
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Use of COALESCE() function in SQL Server

10 Dec, 2020
Introduction :The SQL Server COALESCE() function is useful to handle NULL values. The NULL values are replaced with the user-given value during the expression value evaluation process. The SQL Server Coalesce function evaluates the expression in a definite order and always results first not null value from the defined expression list.
Syntax :
COALESCE ( exv1, exv2..., exvN )

Where –exv1, exv2..., exvN are expression values.
Properties of the Syntax of SQL Server Coalesce function :
All expressions must be have same data-type.
It could have multiple expressions.
Example-1 :
SELECT COALESCE (NULL, 'X', 'Y') 
AS RESULT ;
Output :
Example-2 :
SELECT COALESCE (NULL, 13, 24, 35, 46) 
AS RESULT ;
Output :
Example-3 :
SELECT COALESCE (NULL, NULL, 45, NULL, NULL) 
AS RESULT ;
Output :
Example-4 :
SELECT COALESCE (NULL, NULL, NULL, NULL, NULL, 'GFG') 
AS RESULT ;
Output :
Example-5 :
SELECT COALESCE (NULL, NULL, NULL, NULL, 5, ‘GFG’) AS RESULT ;
Output :when the queries are run in SQL Server Management Studio.
Example-6 :
SELECT COALESCE 
(NULL, NULL, NULL, NULL, NULL, 'GFG', 1)
Output :
Using SQL Server Coalesce function in a string concatenation operation :Let us suppose we have below table name “GeekName”.
Example-7 :Output :
Select * from GeekName;
Example-8 :
SELECT F_Name + ' ' +M_Name+ ' ' 
+ L_Name FullName FROM GeekName ;
Output :
Using SQL server function called COALESCE to handle the NULL values :The SQL statement will concatenate all three names, but no NULL values will appear in the output.
Example-9 :
SELECT F_Name +' '+COALESCE(M_Name, '') +' '
+ L_Name   FullName  FROM GeekName ;
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
What is a modulo operator (%) in Python?

28 Jul, 2020
When we see a ‘%’ the first thing that comes to our mind is the “Percentage-sign”, but when we think of it from the perspective of computer language, this sign has, in fact, another name and meaning. In computing, the modulo operation(%) finds the remainder or signed remainder after the division of one number by another (called the modulus of the operation).
Given two positive numbers, a and n, a modulo n (a % n, abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
Basically, Python modulo operation is used to get the remainder of a division. The modulo operator(%) is considered an arithmetic operation, along with +, –, /, *, **, //. In most languages, both operands of this modulo operator have to be an integer. But Python Modulo is versatile in this case. The operands can be either integer or float.
Syntax:
a % b


Here, a is divided by b, and the remainder of that division is returned.
Code: 
Python3
# inputsa = 13b = 5  # Stores the remainder obtained # when dividing a by b, in cc = a % b      print(a, "mod", b, "=",      c, sep = " ")  # inputsd = 15.0e = 7.0  # Stores the remainder obtained # when dividing d by e, in ff = d % eprint(d, "mod", e, "=",       f, sep = " ")
Output:
13 mod 5 = 3
15.0 mod 7.0 = 1.0

This was a simple example showing the use of the syntax, and a basic operation performed by the modulo operator. Suppose, we want to calculate the remainder of every number from 1 to n when divided by a fixed number k.
Python3
# function is defined for finding out # the remainder of every number from 1 to ndef findRemainder(n, k):      for i in range(1, n + 1):    # rem will store the remainder     # when i is divided by k.    rem = i % k            print(i, "mod", k, "=",           rem, sep = " ")  # Driver codeif __name__ == "__main__" :      # inputs  n = 5  k = 3      # function calling  findRemainder(n, k)
 Output:
1 mod 3 = 1
2 mod 3 = 2
3 mod 3 = 0
4 mod 3 = 1
5 mod 3 = 2

The only Exception you get with python modulo operation is ZeroDivisionError. This happens if the divider operand of the modulo operator becomes zero. That means the right operand can’t be zero. Let’s see the following code to know about this python exception.
Python3
# inputsa = 14b = 0  # exception handlingtry:    print(a, 'mod', b, '=',          a % b, sep = " ")      except ZeroDivisionError as err:    print('Cannot divide by zero!' +          'Change the value of the right operand.')
 Output:
Cannot divide by zero! Change the value of the right operand.

Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Update two columns with a single MySQL query

For this, you need to use SET command only once. Let us first create a table −
mysql> create table DemoTable1909
   (
   Id int NOT NULL,
   FirstName varchar(20),
   LastName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1909 values(101,'John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(102,'John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(103,'Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(104,'David','Miller');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1909;
This will produce the following output −
+-----+-----------+----------+
| Id  | FirstName | LastName |
+-----+-----------+----------+
| 101 | John      |    Smith |
| 102 | John      |      Doe |
| 103 | Adam      |    Smith |
| 104 | David     |   Miller |
+-----+-----------+----------+
4 rows in set (0.00 sec)
Here is the query to update two column values −
mysql> update DemoTable1909
     set FirstName='Carol',LastName='Taylor'
     where Id=103;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1909;
This will produce the following output −
+-----+-----------+----------+
| Id  | FirstName | LastName |
+-----+-----------+----------+
| 101 | John      |    Smith |
| 102 | John      |      Doe |
| 103 | Carol     |   Taylor |
| 104 | David     |   Miller |
+-----+-----------+----------+
4 rows in set (0.00 sec)
InsertionSort - GeeksforGeeks

28 Jun, 2021
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Algorithm// Sort an arr[] of size ninsertionSort(arr, n)Loop from i = 1 to n-1 ... More on Insertion Sort 
Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above.
Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done while doing insertion sort in the array.  
4 5 3 2 1
3 4 5 2 1
2 3 4 5 1
1 2 3 4 5
5 4 3 1 2
5 4 1 2 3
5 1 2 3 4
1 2 3 4 5
4 3 2 1 5
3 2 1 5 4
2 1 5 4 3
1 5 4 3 2
4 5 3 2 1
2 3 4 5 1
3 4 5 2 1
1 2 3 4 5
In the insertion sort , just imagine that the first element is already sorted and all the right side Elements are unsorted, we need to insert all elements one by one from left to right in the sorted Array. Sorted : 5
 unsorted : 4 3 2 1 Insert all elements less than 5 on the left (Considering 5 as the key ) Now key value is 4 and array will look like this Sorted : 4 5
unsorted : 3 2 1 Similarly for all the cases the key will always be the newly inserted value and all the values will be compared to that key and inserted in to proper position.
In best case, 

Quick sort: O (nlogn) 
Merge sort: O (nlogn)
Insertion sort: O (n)
Selection sort: O (n^2)  
*Online - can sort a list at runtime
*Stable - doesn't change the relative 
          order of elements with equal keys. 
 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Software Testing - Boundary Value Analysis
TCS NQT Coding Sheet
A Freshers Guide To Programming
Difference Between @Controller and @RestController Annotation in Spring
Inserting data using a CSV file in Cassandra

31 Mar, 2021
In this article, we will discuss how you can insert data into the table using a CSV file. And we will also cover the implementation with the help of examples. Let’s discuss it one by one.
Pre-requisite – Introduction to Cassandra
Introduction :If you want to store data in bulk then inserting data from a CSV file is one of the nice ways. If you have data in a file so, you can directly insert your data into the database by using the COPY command in Cassandra. It will be very useful when you have a very large database, and you want to store data quickly and your data is in a CSV file then you can directly insert your data. 
Syntax – You can see the COPY command syntax for your reference as follows.
COPY table_name [( column_list )]
FROM 'file_name path'[, 'file2_name path', ...] | STDIN
[WITH option = 'value' [AND ...]]
Now, let’s create the sample data for implementing the approach. 
Step-1 :Creating keyspace – dataHere, you can use the following cqlsh command to create the keyspace as follows.
CREATE KEYSPACE data
 WITH REPLICATION = {  
  'class' : 'NetworkTopologyStrategy',  
  'datacenter1' : 1  
  } ;
Step-2 :Creating the Student_personal_data table –Here, you can use the following cqlsh command to create the Student_personal_data table as follows.
CREATE TABLE data.Student_personal_data (  
 S_id UUID PRIMARY KEY,  
S_firstname text,  
S_lastname text,    
);
Step-3 :Creating the CSV file –Consider the following given table as a CSV file namely as personal_data.csv. But, in actual you can insert data in CSV file and save it in your computer drive. 
Step-4 :Inserting data from the CSV file –In this, you will see how you can insert data into the database from existed CSV file you have, and you can use the following cqlsh command as follows.  
COPY data.Student_personal_data (S_id, S_firstname, S_lastname) 
FROM 'personal_data.csv' 
WITH HEADER = TRUE;
Step-5 :Verifying the result –Once you will execute the above command, then you will get the following result as follows.
Using 7 child processes

Starting copy of data.Student_personal_data with columns [S_id, S_firstname, S_lastname].
Processed: 6 rows; Rate:      10 rows/s; Avg. rate:      14 rows/s
6 rows imported from 1 files in 0.422 seconds (0 skipped).
You can use the following command to see the output as follows.
select * from data.Student_personal_data;
Output :
Apache
NoSQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
Difference between Star Schema and Snowflake Schema
What is Cursor in SQL ?
PyQt5 QDateEdit – Getting Date Time

07 Jul, 2020
In this article we will see how we can get the date time of the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records, which can be done with the help of setDate method. Unlike normal date, date time has date as well as the time although time is not shown on the date edit. Date time can set tot he date edit with the help of setDate method.
In order to do this we use dateTime method with the QDateEdit object
Syntax : date.dateTime()
Argument : It takes no argument
Return : It returns QDateTime object
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating a QDateEdit widget        date = QDateEdit(self)          # setting geometry of the date edit        date.setGeometry(100, 100, 150, 40)          # date time        d = QDateTime(2020, 10, 10, 10, 20)          # setting date time        date.setDateTime(d)            # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry        label.setGeometry(100, 150, 200, 60)          # making label multiline        label.setWordWrap(True)          # getting date time        value = date.dateTime()          # setting text to the label        label.setText("Date Time : " + str(value))      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
OpenCV - Writing an Image

The write() method of the Imgcodecs class is used to write an image using OpenCV. To write an image, repeat the first three steps from the previous example.
To write an image, you need to invoke the imwrite() method of the Imgcodecs class.
Following is the syntax of this method.
imwrite(filename, mat)

This method accepts the following parameters −
filename − A String variable representing the path where to save the file.
filename − A String variable representing the path where to save the file.
mat − A Mat object representing the image to be written.
mat − A Mat object representing the image to be written.
Following program is an example to write an image using Java program using OpenCV library.
import org.opencv.core.Core; 
import org.opencv.core.Mat; 
import org.opencv.imgcodecs.Imgcodecs;
 
public class WritingImages {  
   public static void main(String args[]) { 
      //Loading the OpenCV core library  
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME); 
      
      //Instantiating the imagecodecs class 
      Imgcodecs imageCodecs = new Imgcodecs(); 

      //Reading the Image from the file and storing it in to a Matrix object 
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";   
      Mat matrix = imageCodecs.imread(file); 

      System.out.println("Image Loaded ..........");
      String file2 = "C:/EXAMPLES/OpenCV/sample_resaved.jpg"; 

      //Writing the image 
      imageCodecs.imwrite(file2, matrix); 
      System.out.println("Image Saved ............"); 
   } 
}
On executing the above program, you will get the following output −
Image Loaded .......... 
Image Saved ...........

If you open the specified path, you can observe the saved image as shown below −
YetAnotherSMSBomber – SMS Bomber in kali linux

17 Jun, 2021
YetAnotherSMSBomber is a free and open-source tool available on GitHub. This tool doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. You must ensure that you always install the latest version of YetAnotherSMSBomber from GitHub in order to not get stuck with the working of the tool. This tool is used to perform call and SMS bombing on the target phone number. This tool is written in python, so you must have python installed in your kali Linux operating system. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. 
Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/AvinashReddy3108/YetAnotherSMSBomber.git
cd YetAnotherSMSBomber
Step 2: Now you have to download some dependencies of the tool using the following command.
pip3 install -r requirements.txt
Step 3: The tool has been downloaded and now the tool using the following command.
python3 bomber.py -h
Example : 
You can see that the tool has been downloaded successfully. Now let’s see an example of using the tool by running the following command to perform SMS bombing on a number.
python3 bomber.py <phone number>
The tool has started sending SMS and some of them get success whereas some of them failed, but you can try again and again to have the best results. The SMS failed due to a poor internet connection. If your internet is good, then no SMS of yours will fail.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
refresh driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around refresh driver method in Selenium. refresh method refreshes the current page.
Syntax –
driver.refresh()
Example –Now one can use refresh method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.refresh()

To demonstrate, refresh method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s refresh window,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # refresh window driver.refresh()
Output –Screenshot added –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.