code-rag-bench/online-tutorials huggingface dataset:
PySpark partitionBy() method

30 Jun, 2021
PySpark partitionBy() is used to partition based on column values while writing DataFrame to Disk/File system. When you write DataFrame to Disk by calling partitionBy() Pyspark splits the records based on the partition column and stores each partition data into a sub-directory. 
PySpark Partition is a way to split a large dataset into smaller datasets based on one or more partition keys. You can also create a partition on multiple columns using partitionBy(), just pass columns you want to partition as an argument to this method.
Syntax: partitionBy(self, *cols)
Let’s Create a DataFrame by reading a CSV file.  You can find the dataset at this link Cricket_data_set_odi.csv
Create dataframe for demonstration:
Python3
# importing moduleimport pysparkfrom pyspark.sql import SparkSessionfrom pyspark.context import SparkContext  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # create DataFramedf=spark.read.option(  "header",True).csv("Cricket_data_set_odi.csv")  # Display schemadf.printSchema() 
Output:
From the above DataFrame, we will be use Team as a partition key for our examples below:
Python3
df.write.option("header", True) \        .partitionBy("Team") \        .mode("overwrite") \        .csv("Team")  # change directorycd Team  # On our DataFrame, we have a total# of 9 different teams hence,# it creates 9 directories as shown below.# The name of the sub-directory would be# the partition column and its value # (partition column=value).ls
Output:
You can also create partitions on multiple columns using PySpark partitionBy(). Just pass columns you want to partition as arguments to this method.
From the above DataFrame, we are using Team and Speciality as a partition key for our examples below. 
Python3
# From above DataFrame, we will be using # Team and Speciality as a partition key # for our examples below.# partitionBy()df.write.option("header", True) \        .partitionBy("Team", "Speciality") \        .mode("overwrite") \        .csv("Team-Speciality")  # change directorycd Team = Indcd Team-Specialitycd Team = Indls
Output:
Use the option maxRecordsPerFile if you want to control the number of records for each partition. This is especially helpful when your data is skewed (some partitions with very few records and other partitions with high numbers of records).
Python3
# partitionBy() control number of partitionsdf.write.option("header",True) \        .option("maxRecordsPerFile", 2) \        .partitionBy("Team") \        .mode("overwrite") \        .csv("Team")# change directorycd Teamls
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Update MongoDB field using value of another field?

You can use aggregate function to update MongoDB field using the value of another field. Here, we will create two collections:
name
name
studentInformation
studentInformation
<name> Collection
The query to create first collection with documents is as follows:
> db.name.insert({"FirstName":"John","LastName":"Smith"});
WriteResult({ "nInserted" : 1 })
Now you can display all documents from the collection with the help of find() method. The query is as follows:
> db.name.find().pretty();
The following is the output that displays the collection “name” documents:
{
   "_id" : ObjectId("5c6c00dd68174aae23f5ef55"),
   "FirstName" : "John",
   "LastName" : "Smith"
}
<studentInformation> Collection
The query to create second collection with documents is as follows:
> db.studentInformation.insert({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
WriteResult({ "nInserted" : 1 })
Now you can display all documents from the collection with the help of find() method. The query is as follows:
> db.studentInformation.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6c013068174aae23f5ef56"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor"
}
Now, let us update collection “name” with another collection “studentInformation”. The query is as follows:
> db.studentInformation.aggregate( [
   {"$addFields":{"FullName":{"$concat":["$StudentFirstName"," ","$StudentLastName"]} }},
   {"$out":"name"} ] );
Now you can check the documents of the collection “name”. The query is as follows:
> db.name.find().pretty();
The following is the output that displays that we have successfully updated the fields:
{
   "_id" : ObjectId("5c6c013068174aae23f5ef56"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor",
   "FullName" : "Carol Taylor"
}
How to extract floating number from text using Python regular expression?

The following code extracts floating numbers from given text/string using Python regex.
import re
s = "Sound Level: -11.7 db or 15.2 or 8 db"
result = re.findall(r"[-+]?\d*\.\d+|\d+", s)
print result
This gives the output
['-11.7', '15.2', '8']
JavaTuples getSize() method - GeeksforGeeks

27 Aug, 2018
The getSize() method in org.javatuples is used to fetch the size of the TupleClassObject. That is, it is used to fetch the number of values present in the TupleClassObject. This method can be used to any tuple class object of the javatuples library. It returns a integer value equal to the number of the elements present in the TupleClassObject.
Method Declaration:
public abstract int getSize()
Syntax:
int size = TupleClassObject.getSize()
Here TupleClassObject represents the JavaTuple Class object used like Unit, Quintet, Decade, etc.
Parameters: This method do not takes any parameter.
Return Value: This method returns the number of elements present in the TupleClassObject, in integer format.
Below programs illustrate the various ways to use getSize() method:
Program 1: Using getSize() with Unit class:
// Below is a Java program to use getSize() method  import java.util.*;import org.javatuples.Unit;  class GfG {    public static void main(String[] args)    {        // Creating an Unit with one value        Unit<String> unit = Unit.with("GeeksforGeeks");          // Using getSize() method        int size = unit.getSize();          System.out.println("Size = " + size);    }}
Output:
Size = 1
Program 2: Using getSize() with Quartet class:
// Below is a Java program to use getSize() method  import java.util.*;import org.javatuples.Quartet;  class GfG {    public static void main(String[] args)    {        // Creating an Quartet with four values          Quartet<String, String, String, String> quartet            = Quartet.with("GeeksforGeeks",                           "A computer portal",                           "for geeks",                           "by Sandeep Jain");          // Using getSize() method        int size = quartet.getSize();          System.out.println("Size = " + size);    }}
Output:
Size = 4
Note: Similarly, it can be used with any other JavaTuple Class.
Java-Functions
JavaTuples
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
Set in Java
Initializing a List in Java
Singleton Class in Java
How to pass a dictionary as argument in Python function?

In the code given below we pass given dictionary as an argument to a python function and then call the function which works on the keys/value pairs and gives the result accordingly
d = {'a' : 1, 'b' : 2, 'c' : 3}
def f(dict):
    for k, v in dict.iteritems():
        print k, 2*v
f(d)
a 2
c 6
b 4
Explain the log based recovery in DBMS

Log is nothing but a file which contains a sequence of records, each log record refers to a write operation. All the log records are recorded step by step in the log file. We can say, log files store the history of all updates activities.
Log contains start of transaction, transaction number, record number, old value, new value, end of transaction etc. For example, mini statements in bank ATMs.
If within an ongoing transaction, the system crashes, then by using log files, we can return back to the previous state as if nothing has happened to the database.
The log is kept on disk so that it is not affected by failures except disk and failures.
Different types of log records are as follows −
<Ti, Xi, V1, V2> − update log record, where Ti=transaction, Xi=data, V1=old data, V2=new value.
<Ti, Xi, V1, V2> − update log record, where Ti=transaction, Xi=data, V1=old data, V2=new value.
<Ti, start> − Transaction Ti starts execution.
<Ti, start> − Transaction Ti starts execution.
<Ti, commit> − Transaction Ti is committed.
<Ti, commit> − Transaction Ti is committed.
<Ti, abort> − Transaction Ti is aborted
<Ti, abort> − Transaction Ti is aborted
The log records can be written as follows −
Create a log for the given transaction T1 and T2.
  T1            T2              Log
 Read A        Read A        <T1, start>
 A=A-2000      A=A+5000     <T1,A,5000, 3000>
 Write A      Write A       <T1, B, 8000, 10000>
 Read B       Read B        <T1, commit>
 B=B+2000     B= B+7000     <T2, start>
 Write B      Write B      <T2, A, 3000, 8000>
                           <T2, B, 10000, 17000>
                           <T2, commit>
Log based recovery uses one of the techniques −
It modifies the database after completion of transaction. The database modification is deferred or delayed until the last operation of the transaction is executed. Update log records maintain the new value of the data item.
Recover system uses one operation which is as follows −
Redo(Ti) − All data items updated by the transaction Ti are set to a new value.
Redo(Ti) − All data items updated by the transaction Ti are set to a new value.
It modifies the database after a write operation, database modification is immediately done when a transaction performs an update/ write operation. Update log records maintain both old and new values of data items.
The recovery system uses two operations, which are as follows −
Undo(Ti) − All data items updated by the transaction Ti, are set to old value.
Undo(Ti) − All data items updated by the transaction Ti, are set to old value.
Redo(Ti) − All data items updated by the transaction Ti are set to a new value.
Redo(Ti) − All data items updated by the transaction Ti are set to a new value.
DAX Aggregation - AVERAGE function

Returns the average (arithmetic mean) of all the numbers in a column.
AVERAGE (<column>)

Column
The column that contains the numbers for which you want the average.
Returns a decimal number that represents the arithmetic mean of the numbers in the column.
If the column contains logical values or empty cells, those values are ignored and the rows are not counted.
If the column contains logical values or empty cells, those values are ignored and the rows are not counted.
Cells with the value zero are included and the rows are counted for the divisor.
Cells with the value zero are included and the rows are counted for the divisor.
Whenever there are no rows to aggregate, the function returns a blank. However, if there are rows, but none of them meet the specified criteria, the function returns 0.
Whenever there are no rows to aggregate, the function returns a blank. However, if there are rows, but none of them meet the specified criteria, the function returns 0.
= AVERAGE (Sales[Sales Amount]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to plot a circle in Matplotlib?

To plot a circle in matplotlib, we can take the following steps −
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add a subplot arrangement to the current axis.
Add a subplot arrangement to the current axis.
Create a true circle at a center using Circle class.
Create a true circle at a center using Circle class.
Add a patch to the current axis.
Add a patch to the current axis.
Set limits of the x and y axes.
Set limits of the x and y axes.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot()
circle1 = patches.Circle((0.2, 0.2), radius=0.5, color='green')
ax.add_patch(circle1)
ax.axis('equal')
plt.show()
Git Commit

Since we have finished our work,  
we are ready move from stage to commit 
for our repo.
Adding commits keep track of our progress and changes as we work. Git 
considers each commit change point or "save point". It is a point in the project 
you can go back to if you find a bug, or want to make a change.
When we commit, we should always include a message.
By adding clear messages to each commit, it is easy for yourself (and others) 
to see what has changed and when.
git commit -m "First release of Hello World!"
[master (root-commit) 221ec6e] First release of Hello World!
 3 files changed, 26 insertions(+)
 create mode 100644 README.md
 create mode 100644 bluestyle.css
 create mode 100644 index.html
The commit  command performs a commit, and the -m "message" adds a message.
The Staging Environment has been committed to our repo, with the message:"First release of Hello World!"
Sometimes, when you make small changes, using the staging environment seems like a waste of time. It is possible to commit changes directly, skipping the staging environment.
The -a option will automatically stage every 
changed, already tracked file.
Let's add a small update to index.html:
And check the status of our repository. But this time, we will use the --short option to see the changes in a more compact way:
git status --short
 M index.html
Note: Short status flags are:
?? - Untracked files
A - Files added to stage
M - Modified files
D - Deleted files
We see the file we expected is modified. So let's commit it directly:
git commit -a -m "Updated index.html with a new line"
[master 09f4acd] Updated index.html with a new line
 1 file changed, 1 insertion(+)
Warning: Skipping the Staging Environment is not generally recommended.
Skipping the stage step can sometimes make you include unwanted changes.
To view the history of commits for a repository, you can use the log command:
git log
commit 09f4acd3f8836b7f6fc44ad9e012f82faf861803 (HEAD -> master)
Author: w3schools-test 
Date:   Fri Mar 26 09:35:54 2021 +0100

    Updated index.html with a new line

commit 221ec6e10aeedbfd02b85264087cd9adc18e4b26
Author: w3schools-test 
Date:   Fri Mar 26 09:13:07 2021 +0100

    First release of Hello World!
Commit the changes to the current repository with the message "First release!
git   "First release!"


Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
What is the purpose of using a dumpStack() method in Java?

The dumpStack() method is a static method of Thread class and it can be used to print or display stack tracing of the current thread to System.err. The purpose of the dumpStack() method is basically for debugging and Internally this method is calling the printStackTrace() method of Throwable class. This method does not raise any exceptions.
public static void dumpStack()
public class ThreadDumpStackTest {
   public static void main(String args[]) {
      Thread t = Thread.currentThread();
      t.setName("ThreadDumpStackTest");
      t.setPriority(1);
      System.out.println("Current Thread: " + t);
      int count = Thread.activeCount();
      System.out.println("Active threads: " + count);
      Thread threads[] = new Thread[count];
      Thread.enumerate(threads);
      for (int i = 0; i < count; i++) {
         System.out.println(i + ": " + threads[i]);
      }
      Thread.dumpStack();
   }
}
Current Thread: Thread[ThreadDumpStackTest,1,main]
Active threads: 1
0: Thread[ThreadDumpStackTest,1,main]
java.lang.Exception: Stack trace
        at java.lang.Thread.dumpStack(Thread.java:1336)
        at ThreadDumpStackTest.main(ThreadDumpStackTest.java:14)
Pytest - Conftest.py

We can define the fixture functions in this file to make them accessible across multiple test
files.
Create a new file conftest.py and add the below code into it  −
import pytest

@pytest.fixture
def input_value():
   input = 39
   return input
Edit the test_div_by_3_6.py to remove the fixture function −
import pytest

def test_divisible_by_3(input_value):
   assert input_value % 3 == 0

def test_divisible_by_6(input_value):
   assert input_value % 6 == 0
Create a new file test_div_by_13.py −
import pytest

def test_divisible_by_13(input_value):
   assert input_value % 13 == 0
Now, we have the files test_div_by_3_6.py and test_div_by_13.py making use of the fixture defined in conftest.py.
Run the tests by executing the following command −
pytest -k divisible -v

The above command will generate the following result −
test_div_by_13.py::test_divisible_by_13 PASSED
test_div_by_3_6.py::test_divisible_by_3 PASSED
test_div_by_3_6.py::test_divisible_by_6 FAILED
============================================== FAILURES
==============================================
________________________________________ test_divisible_by_6
_________________________________________
input_value = 39
   def test_divisible_by_6(input_value):
>  assert input_value % 6 == 0
E  assert (39 % 6) == 0
test_div_by_3_6.py:7: AssertionError
========================== 1 failed, 2 passed, 6 deselected in 0.09 seconds
==========================

The tests will look for fixture in the same file. As the fixture is not found in the file, it will check for fixture in conftest.py file. On finding it, the fixture method is invoked and the result is returned to the input argument of the test.

    21 Lectures 
     4 hours 

 Lucian Musat

    22 Lectures 
     1.5 hours 

 Fanuel Mapuwei

    44 Lectures 
     3.5 hours 

 Rohit Dharaviya
 Print
 Add Notes
 Bookmark this page
reflect.MapOf() Function in Golang with Examples - GeeksforGeeks

28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.MapOf() Function in Golang is used to get the map type with the given key and element types, i.e., if k represents int and e represents string, MapOf(k, e) represents map[int]string. To access this function, one needs to imports the reflect package in the program.
Syntax:
func MapOf(key, elem Type) Type

Parameters: This function takes three parameters of Type type(key, elem).
Return Value: This function returns the map type with the given key and element types.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.MapOf() Function   package main  import (    "fmt"    "reflect")  // Main function func main() {      var i interface{}          // use of MapOf method    tm := reflect.MapOf(reflect.TypeOf("string"),                      reflect.TypeOf(&i).Elem())          fmt.Println(tm)}
Output:
map[string]interface {}

Example 2:
// Golang program to illustrate// reflect.MapOf() Function   package main  import (    "fmt"    "reflect")  // Main function func main() {      ta := reflect.ArrayOf(5, reflect.TypeOf(123))          tc := reflect.ChanOf(reflect.SendDir, ta)          //use of MapOf method    tm := reflect.MapOf(ta, tc)          fmt.Println(tm)}
Output:
map[[5]int]chan<- [5]int

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Golang Maps
Slices in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
How to align an image and text vertically on the same line in React Bootstrap? - GeeksforGeeks

14 Jan, 2021
ReactJS has a very beautiful way to align images and text vertically in the same line in React Bootstrap. ReactJS is a front-end library developed by Facebook to build various components of the front-end. Bootstrap is a CSS framework developed by Twitter for building CSS enriched front end websites. 
Including Bootstrap: Bootstrap can be embedded in the React application by including the following link in the <head> section of our HTML page:
<link rel="stylesheet" 
      href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
      integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 
      crossorigin="anonymous" />

The above code will embed the CSS Bootstrap framework into our HTML webpage.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
We can align an image and text vertically by placing a break line tag in between an image and text tags. React HTML tags are self-closing tags, so make sure that as you open a tag, you close the tag also.
Filename: App.js
Javascript
import React from "react";import Container from "react-bootstrap/Container";import Card from "react-bootstrap/Card";import "./App.css";  const App = () => {  const subtitle = "Hi There";  const infoIcon = "https://www.pixelstalk.net/wp-content/uploads/" +   "images1/Free-Download-Sunrise-Desktop-Images-Wallpapers.jpg"    return (    <Container className="p-3">      <Card>        <div>          <img            src={infoIcon}            alt="Info"            style={{              width: 20,              backgroundColor: "red",              verticalAlign: "center"            }}          />          <br />          <i className="text-muted p-0" style={{ backgroundColor: "red" }}>            {subtitle}          </i>        </div>      </Card>    </Container>  );};  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Output
Picked
react-js
Technical Scripter 2020
Bootstrap
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
Tailwind CSS vs Bootstrap
How to place table text into center using Bootstrap?
How to use Top Navigation with Left Navigation Bar using Bootstrap ?
How to make vertical scrollable rows in bootstrap?
JavaScript Project on Todo List
How to toggle password visibility in forms using Bootstrap-icons ?
How to calculate total time of an array in PHP ? - GeeksforGeeks

19 Jan, 2022
Given an array containing the time in hr:min:sec format. The task is to calculate the total time. If the total time is greater then 24 hours then the total time will not start with 0. It will display the total time. There are two ways to calculate the total time from the array.  
Using strtotime() functionUsing explode() function
Using strtotime() function
Using explode() function
Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format.Syntax  
strtotime( string )
Example 1: This example reads the values from the array and converts it into the time format. 
php
<?php // Array containing time in string format$time = [    '00:04:35', '00:02:06', '01:09:12',    '09:19:04', '00:17:49', '02:13:59',    '10:10:54']; $sum = strtotime('00:00:00'); $totaltime = 0; foreach( $time as $element ) {         // Converting the time into seconds    $timeinsec = strtotime($element) - $sum;         // Sum the time with previous value    $totaltime = $totaltime + $timeinsec;} // Totaltime is the summation of all// time in seconds // Hours is obtained by dividing// totaltime with 3600$h = intval($totaltime / 3600); $totaltime = $totaltime - ($h * 3600); // Minutes is obtained by dividing// remaining total time with 60$m = intval($totaltime / 60); // Remaining value is seconds$s = $totaltime - ($m * 60); // Printing the resultecho ("$h:$m:$s"); ?>
23:17:39
 
Using explode() function: The explode() function is used to break a string into an array.Syntax  
array explode( separator, string, limit )
Example 2: This example reads the values from an array and converts it into the time format. 
php
<?php // Declare an array containing times$arr = [    '00:04:35', '00:02:06', '01:09:12',    '09:19:04', '00:17:49', '02:03:59',    '10:10:54']; $total = 0; // Loop the data itemsforeach( $arr as $element):         // Explode by separator :    $temp = explode(":", $element);         // Convert the hours into seconds    // and add to total    $total+= (int) $temp[0] * 3600;         // Convert the minutes to seconds    // and add to total    $total+= (int) $temp[1] * 60;         // Add the seconds to total    $total+= (int) $temp[2];endforeach; // Format the seconds back into HH:MM:SS$formatted = sprintf('%02d:%02d:%02d',                ($total / 3600),                ($total / 60 % 60),                $total % 60); echo $formatted; ?>
23:07:39
 
sagartomar9927
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to Upload Image into Database and Display it using PHP ?
How to pass JavaScript variables to PHP ?
PyQt5 QSpinBox - Adding background color to the up arrow when pressed - GeeksforGeeks

17 May, 2020
In this article we will see how we can set background color to the up arrow of the spin box when it get pressed. Spin box is basically have three components one is the line edit other two are up and down button. Up arrow is the inner part of the up button, this background color will only appear when up arrow gets pressed.
In order to do this we have to change the style sheet associated with the spin box, below is the style sheet code
QSpinBox::up-arrow:pressed
{
background-color : blue;
}

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, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):        # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting prefix to spin        self.spin.setPrefix("Prefix ")          # setting suffix to spin        self.spin.setSuffix(" Suffix")          # setting style sheet of spin box        # adding background color to the up-arrow when it get pressed        self.spin.setStyleSheet("QSpinBox::up-arrow::pressed"                                "{"                                "background-color : blue;"                                "}")      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python PyQt-SpinBox-stylesheet
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
GATE | GATE-CS-2017 (Set 1) | Question 37 - GeeksforGeeks

28 Jun, 2021
Let G = (V, E) be any connected undirected edge-weighted graph. The weights of the edges in E are positive any distinct. Consider the following statements:
I. Minimum Spanning Tree of G is always unique.
II. Shortest path between any two vertices of G is always unique.

Which of the above statements is/are necessarily true?(A) I only(B) II only(C) both I and II(D) neither I and IIAnswer: (A)Explanation: I. Minimum Spanning Tree of G is always unique – MST will wlways be distinct if the edges are unique so CorrectII. Shortest path between any two vertices of G is always unique – Shortest path between any two vertices can be same so incorrect
Therefore, option A is correctAlternate solution:We know that minimum spanning tree of a graph is always unique if all the weight are distinct, so statement 1 is correct.Now statement 2 , this might not be true in all cases. Consider the graph.There are two shortest paths from a to b (one is direct and other via node c) So statement 2 is falseHence option a is correct.Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Apache Camel - Message Queues

Most of the integration projects use messaging as it helps in creating loosely coupled application architecture. Messaging can be either synchronous or asynchronous. JMS supports both point-to-point and publish-subscribe models. You use a Queue for point-to-point and Topic for a publish-subscribe model. On a Java platform, JMS - Java Messaging Service provides an interface to a messaging server. Apache activeMQ is one such open source JMS provider. Camel does not ship with a JMS provider; however, it can be configured to use activeMQ. To use this component, you need to include the following jars in your project - activemq, camel-spring, and camel-jms.
The following code snippet shows how to configure Camel for activeMQ.
<bean id = "jms" class = "org.apache.camel.component.jms.JmsComponent">
   <property name = "connectionFactory">
      <bean class="org.apache.activemq.ActiveMQConnectionFactory">
         <property name = "orderQueue" value = "tcp://localhost:61000" />
      </bean>
   </property>
</bean>
Here, the Camel application will start listening to a queue called orderQueue. The queue itself is set up in the activeMQ messaging server running on the local host and listing to port 61000. Once this is done, your application can send or receive message to this queue from any of the endpoints defined in your application.
Finally, it is time now to put everything together in a project to get a deeper understanding of how Camel applications are created.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
How we can iterate through list of tuples in Python - GeeksforGeeks

24 Feb, 2022
In this article, we will discuss different ways to iterate the list of tuples in Python.
It can be done in these ways:
Using Loop.
Using enumerate().
Here we are going to form a list of tuples using for loop.
Python3
# create a list of tuples with student# detailsname = [('sravan',7058,98.45),        ('ojaswi',7059,90.67),        ('bobby',7060,78.90),        ('rohith',7081,67.89),        ('gnanesh',7084,98.01)] # iterate using for loopfor x in name:     # iterate in each tuple element  for y in x:      print(y)         print()
Output:
sravan
7058
98.45

ojaswi
7059
90.67

bobby
7060
78.9

rohith
7081
67.89

gnanesh
7084
98.01
Here we are going to use enumerate() function to Iterate the list of tuples. A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method. 
Syntax: enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is to be started, by default it is 0
Python3
# create a list of tuples with with student# detailsname = [('sravan',7058,98.45),        ('ojaswi',7059,90.67),        ('bobby',7060,78.90),        ('rohith',7081,67.89),        ('gnanesh',7084,98.01)]l = [] # iterate using index with enumerate functionfor index, tuple in enumerate(name):           # access through index      # by appending to list    l.append(name[index])     # iterate through the listfor x in l:    for y in x:       print(y)    print()
Output:
sravan
7058
98.45

ojaswi
7059
90.67

bobby
7060
78.9

rohith
7081
67.89

gnanesh
7084
98.01
kashishsoda
varshagumber28
Picked
Python List-of-Tuples
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python – Maximum Value in Nested Dictionary

14 May, 2020
Sometimes, while working with python dictionary, we can have problem in which each key in itself is a record with several keys and we desire to substitute the value as maximum value of keys of dictionary. This kind of problem can have application in many domains that involves data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute way in which this task can be performed. In this, we iterate for each key’s keys to get maximum value and set in resultant dictionary.
# Python3 code to demonstrate working of # Maximum Value in Nested Dictionary# Using loop  # initializing dictionarytest_dict = {'gfg' : {'a' : 15, 'b' : 14},             'is' : {'d' : 2, 'e' : 10, 'f' :  3},             'best' : {'g' : 19}}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Maximum Value in Nested Dictionary# Using loopres = {}for key, val in test_dict.items():    max_val = 0    for ele in val.values():        if ele > max_val:            max_val = ele    res[key] = max_val      # printing result print("The modified dictionary : " + str(res)) 
The original dictionary is : {‘is’: {‘f’: 3, ‘e’: 10, ‘d’: 2}, ‘gfg’: {‘a’: 15, ‘b’: 14}, ‘best’: {‘g’: 19}}The modified dictionary : {‘best’: 19, ‘is’: 10, ‘gfg’: 15}
 
Method #2 : Using max() + dictionary comprehensionThis is yet another way in which this task can be performed. In this, we perform the task of extracting maximum using max() and dictionary comprehension is used to iterate and construct new dictionary.
# Python3 code to demonstrate working of # Maximum Value in Nested Dictionary# Using max() + dictionary comprehension  # initializing dictionarytest_dict = {'gfg' : {'a' : 15, 'b' : 14},             'is' : {'d' : 2, 'e' : 10, 'f' :  3},             'best' : {'g' : 19}}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Maximum Value in Nested Dictionary# Using max() + dictionary comprehensionres = {key: max(val.values()) for key, val in test_dict.items()}      # printing result print("The modified dictionary : " + str(res)) 
The original dictionary is : {‘is’: {‘f’: 3, ‘e’: 10, ‘d’: 2}, ‘gfg’: {‘a’: 15, ‘b’: 14}, ‘best’: {‘g’: 19}}The modified dictionary : {‘best’: 19, ‘is’: 10, ‘gfg’: 15}
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
MoviePy – Getting Size of Video File Clip

30 Aug, 2020
In this article we will see how we can get the size of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Size is basically dimensions of the video, normally the higher the dimension of the video, the higher is the quality of the video. Displaying size is different from the actual size of the video clip.
In order to do this we will use size attribute with the VideoFileClip object
Syntax : clip.size
Argument : It takes no argument
Return : It returns tuple
Below is the implementation
# Import everything needed to edit video clips from moviepy.editor import *    # loading video dsa gfg intro video clip = VideoFileClip("dsa_geek.mp4")      # getting only first 5 secondsclip = clip.subclip(0, 5)  # getting clip sizevalue = clip.size  # printing sizeprint("Clip Size ", end = " : ")print(value)    # displaying new clipclip.ipython_display(width = 420)
Output :
Clip Size  : (854, 480)
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")    # getting only first 5 secondsclip = clip.subclip(0, 5)  # getting clip sizevalue = clip.size  # printing sizeprint("Clip Size ", end = " : ")print(value)    # displaying new clipclip.ipython_display(width = 420)
Output :
Clip Size  : (656, 404)
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – turtle.done()

20 Jul, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to starts event loop – calling Tkinter’s main loop function. It does not require any argument. Must be the last statement in a turtle graphics program. Must NOT be used if a script is run from within IDLE in -n mode (No subprocess) – for interactive use of turtle graphics.
Syntax : turtle.done() Parameters : None Returns : None  
Below is the implementation of the above method with some examples :
Example 1 : At the end. 
python3
# import packageimport turtle # motionturtle.forward(100)turtle.right(90)turtle.forward(100) # stop executionturtle.done()
Output :  
Example 2 : Stop the execution at any step.  
python3
# import packageimport turtle # motionturtle.circle(20)turtle.circle(30) # stop executionturtle.done() # motionturtle.circle(40)turtle.circle(50)
Output :  
 
anikakapoor
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Rexx - DATE

This method returns the local date in the following format.
dd mon yyyy
DATE(options)

Options − This is the option for formatting the date value. They can be anyone of the following options given. −
Base − This parameter returns the number of complete days since the day 1 January 0001
Base − This parameter returns the number of complete days since the day 1 January 0001
Days − This parameter returns the number of days that have passed for the current year
Days − This parameter returns the number of days that have passed for the current year
European − This parameter returns the date in the format dd/mm/yy
European − This parameter returns the date in the format dd/mm/yy
Full − This parameter returns the number of microseconds since the day 1 January 0001
Full − This parameter returns the number of microseconds since the day 1 January 0001
Month − This parameter returns the full English name of the current month. An example can be, September
Month − This parameter returns the full English name of the current month. An example can be, September
Normal − This parameter returns the date in the normal format as shown below. This is the default parameter option which is dd mon yyyy
Normal − This parameter returns the date in the normal format as shown below. This is the default parameter option which is dd mon yyyy
Ordered − This parameter returns the date in the format – yy/mm/dd
Ordered − This parameter returns the date in the format – yy/mm/dd
Standard − This parameter returns the date in the format – yyyymmdd
Standard − This parameter returns the date in the format – yyyymmdd
Weekday − This parameter returns the English name for the day of the week. An example can be, Wednesday
Weekday − This parameter returns the English name for the day of the week. An example can be, Wednesday
Returns, by default, the local date in the format: dd mon yyyy.
/* Main program */ 
say DATE() 
say DATE("B") 
say DATE("D") 
say DATE("E")
When we run the above program we will get the following result. This depends on the current date on the system.
The following program is just an example.
2 Jun 2016
numpy.inner() in python

28 Nov, 2018
numpy.inner(arr1, arr2): Computes the inner product of two arrays.
Parameters : 
arr1, arr2 : array to be evaluated.

Return:  Inner product of the two arrays.
Code #1 :
# Python Program illustrating # numpy.inner() method   import numpy as geek   # Scalars product = geek.inner(5, 4) print("inner Product of scalar values : ", product)   # 1D array vector_a = 2 + 3jvector_b = 4 + 5j  product = geek.inner(vector_a, vector_b) print("inner Product : ", product) 
Output:
inner Product of scalar values :  20
inner Product :  (-7+22j)

 Code #2 : As normal matrix multiplication
# Python Program illustrating # numpy.inner() method   import numpy as geek   # 1D array vector_a = geek.array([[1, 4], [5, 6]]) vector_b = geek.array([[2, 4], [5, 2]])   product = geek.inner(vector_a, vector_b) print("inner Product : \n", product)   product = geek.inner(vector_b, vector_a) print("\ninner Product : \n", product) 
Output:
inner Product : 
 [[18 13]
 [34 37]]

inner Product : 
 [[18 34]
 [13 37]]

Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Prime Factorization using Sieve O(log n) for multiple queries in C++

In this problem, we need to create a program to calculate Prime Factorization using Sieve O(log n) for multiple queries. 
As the general method takes O(sqrt(n) ) time which will increase the time required to a huge extent from multiple queries.
Let’s recap first,
Prime factorization of a number includes ONLY the prime factors, not any products of those prime factors.
Sieve of Eratosthenes is an algorithm to generate all prime numbers within the given range.
The solution to the problem is found by finding the smallest factor that divides the number, saving it as a factor and updating the number by dividing it by the factor. This process is done recursively till the number becomes 1 after division, which means no other factors are possible.
The calculation is done using sieve of eratosthenes which reduces the time complexity in finding the smallest prime factor.
Live Demo
#include <iostream>
using namespace std;
int primes[100001];

void sieveOfEratosthenes(int N) {
   
   N+=2;
   primes[1] = 1;
   for (int i=2; i<N; i++)
      primes[i] = i;
   for (int i=4; i<N; i+=2)
      primes[i] = 2;
   for (int i=3; i*i<N; i++) {
      if (primes[i] == i) {
         for (int j=i*i; j<N; j+=i)
            if (primes[j]==j)
               primes[j] = i;
      }
   }
}
void findPrimeFactors(int num) {
   
   sieveOfEratosthenes(num);
   int factor;
   while (num != 1) {
      factor = primes[num];
      cout<<factor<<" ";
      num /= factor;
   }
}

int main() {
   int N = 45214;
   cout<<"Prime factorization of the number "<<N<<" using sieve is ";
   findPrimeFactors(N);
   return 0;
}
Prime factorization of the number 45214 using sieve is 2 13 37 47