code-rag-bench/online-tutorials huggingface dataset:
PyQt5 - Using Qt Designer

The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application.
Start Qt Designer application which is a part of development tools and installed in scripts folder of the virtual environment.
Start designing GUI interface by choosing File → New menu.
You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form.
The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic5 command line utility. This utility is a wrapper for uic module of Qt toolkit. The usage of pyuic5 is as follows −
pyuic5 -x demo.ui -o demo.py

In the above command, -x switch adds a small amount of additional code to the generated Python script (from XML) so that it becomes a self-executable standalone application.
if __name__ == "__main__":
   import sys
   app = QtGui.QApplication(sys.argv)
   Dialog = QtGui.QDialog()
   ui = Ui_Dialog()
   ui.setupUi(Dialog)
   Dialog.show()
   sys.exit(app.exec_())
The resultant python script is executed to show the following dialog box −
python demo.py

The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling.

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Lodash _.pipeline() Method - GeeksforGeeks

18 Sep, 2020
The Lodash _.pipeline() method takes a list of functions, either as an array or as arguments, and returns a function that takes some value as its argument and runs it through a pipeline of the original functions given in this function.
Syntax:
_.pipeline( func1, func2,..., funcn );

Parameters: This method accepts a single parameter in the form of n functions and hence operate upon given value.
Return Value: This method returns a function.
Note: To execute the below examples, you have to install the lodash-contrib library by using this command prompt and execute the following command.
npm install lodash-contrib

Below examples illustrate the Lodash _.pipeline() method in JavaScript:
Example 1: Passing functions as arguments.
Javascript
// Defining lodash contrib variablevar _ = require('lodash-contrib');   function cb (x) {     return x * x * x; };function tp (x) {     return 3 * x; };function db (x) {     return 2 * x; };var func = _.pipeline(cb, tp, db);  console.log(func(5));
Output:
750

Example 2: Passing functions as an array.
Javascript
// Defining lodash contrib variablevar _ = require('lodash-contrib');   function cb (x) {     return x * x * x; };function tp (x) {     return 3 * x; };function db (x) {     return 2 * x; };  var func = _.pipeline([tp, cb, db]);  console.log(func(5));
Output:
6750

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python Program to Split the array and add the first part to the end

When it is required to split the list, and then add this first part to the end of the list, a simple iteration through the list and list slicing is required.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
Below is a demonstration for the same −
 Live Demo
def split_list(my_list, n_val, k_val):
   for i in range(0, k_val):
      first_val = my_list[0]
      for k in range(0, n_val-1):
         my_list[k] = my_list[k + 1]
      my_list[n_val-1] = first_val
my_list = [34, 42, 56, 78, 9, 0, 23]
list_len = len(my_list)
pos = 3
print("The list is :")
print(my_list)
print("The split_list method is being called")
split_list(my_list, list_len, pos)
for i in range(0, list_len):
print(my_list[i])
The list is :
[34, 42, 56, 78, 9, 0, 23]
The split_list method is being called
78
9
0
23
34
42
56
A method named ‘split_list’ is defined, that takes a list, and two values as parameters.
Using simple indexing, the array is split, and the first part of the list is put to the end of the list.
A list is created, and is displayed on the screen.
This method is called by passing the list as parameter.
The output is displayed on the console.
PyQt5 - Setting current text in ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can select the item with the help of its content. By default when we create a combo box it shows the first item to be selected but we can change it, in order to do this we will use setCurrentText method.
Syntax : combo_box.setCurrentText(item)
Argument : It takes string as argument
Note : item should belong to the combo box item list
Action performed : It will select the given item
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 a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # item        item ="Legend Geek"          # setting current item        self.combo_box.setCurrentText(item)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
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 ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
isupper(), islower(), lower(), upper() in Python and their applications
Graph Plotting in Python | Set 1
jQuery | click() with Examples - GeeksforGeeks

03 Aug, 2021
The click() is an inbuilt method in jQuery that starts the click event or attach a function to run when a click event occurs.Syntax:
$(selector).click(function);

Parameter: It accepts an optional parameter “function” which is used to run when a click event occurs.Return Value: It returns the selected element with specified function to perform.
<html>  <head>    <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <!-- jQuery code to show the working of this method -->    <script>        $(document).ready(function() {            $("p").click();        });    </script>    <style>        p {            display: block;            width: 300px;            padding: 20px;            font-size: 30px;            border: 2px solid green;        }    </style></head>  <body>    <!-- click on this method -->    <p onclick="alert('paragraph was clicked')">This is a paragraph.</p></body>  </html>
Output:Both outputs get generated simultaneously-
Code #2:In the below code, function is passed to this method.
<html>  <head>    <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <script>        <!-- jQuery code to show the working of this method -->        $(document).ready(function() {            $("p").click(function() {                $(this).fadeOut();            });        });    </script>    <style>        p {            display: block;            width: 370px;            padding: 25px;            font-size: 25px;            border: 2px solid green;        }    </style></head>  <body>    <!-- click on this paragraph and the paragraph will disappear -->    <p>Click inside this block and whole block will disappear !!!</p></body>  </html>
Output:Before clicking inside the block-
After clicking inside the block-
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
input-lg Bootstrap class

The input-lg is used to set the height of forms in Bootstrap.
You can try to run the following code to implement the input-lg 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>
      <form role = "form">
         <div class = "form-group">
            <input class = "form-control input-lg" type = "text" placeholder =".input-lg">
         </div>
         <div class = "form-group"></div>
         <div class = "form-group">
            <select class = "form-control input-lg">
               <option value = "">.input-lg</option>
            </select>
         </div>
      </form>
   </body>
</html>
How to implement coin change problem using topDown approach using C#?

CoinChangeTopDownApproach takes 4 parameters, n is the amount, coins array contains the coins from which the amount needs to be calculated, t is the total number of coins, dp array will store all the pre calculated values. If amount is 0 then return 0. If the value is already calculated then return from the dp array. if the value is not calculated then call the CoinChangeTopDownApproach recursively.
Time complexity − O(N)
Space complexity − O(N)
public class DynamicProgramming{
   public int CoinChangeTopDownApproach(int n,int[] coins,int t,int[] dp){
      if (n == 0){
         return 0;
      }
      if (dp[n] != 0){
         return dp[n];
      }
      int ans = int.MaxValue;
      for (int i = 0; i < t; i++){
         if (n - coins[i] >= 0){
            int subprob = CoinChangeTopDownApproach(n - coins[i], coins, t, dp);
            ans = Math.Min(ans, subprob + 1);
      }
   }
   dp[n] = ans;
   return dp[n];
   }
}

static void Main(string[] args){
   DynamicProgramming dp = new DynamicProgramming();
   int N = 15;
   int[] coins = { 1, 7, 10 };
   int[] dp1 = new int[100];
   int t = coins.Count();
   int res = dp.CoinChangeTopDownApproach(15, coins, t, dp1);
   Console.WriteLine(res);
}
3
How to sort time in AM/ PM in MySQL?

To sort time in AM/PM in MySQL, you can use ORDER BY STR_TO_DATE().
 Following is the syntax −
select yourColumnName from yourTableName ORDER BY STR_TO_DATE(yourColumnName , '%l:%i %p');
Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserLogoutTime varchar(200)
);
Query OK, 0 rows affected (0.97 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(UserLogoutTime) values('09:45 PM');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(UserLogoutTime) values('11:56 AM');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(UserLogoutTime) values('01:01 AM');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(UserLogoutTime) values('02:01 PM');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(UserLogoutTime) values('04:10 PM');
Query OK, 1 row affected (0.15 sec)
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+----+----------------+
| Id | UserLogoutTime |
+----+----------------+
| 1  | 09:45 PM       |
| 2  | 11:56 AM       |
| 3  | 01:01 AM       |
| 4  | 02:01 PM       |
| 5  | 04:10 PM       |
+----+----------------+
5 rows in set (0.00 sec)
Here is the query to sort time In AM/ PM in MySQL −
mysql> select UserLogoutTime from DemoTable ORDER BY STR_TO_DATE(UserLogoutTime, '%l:%i %p');
This will produce the following output −
+----------------+
| UserLogoutTime |
+----------------+
| 01:01 AM       |
| 11:56 AM       |
| 02:01 PM       |
| 04:10 PM       |
| 09:45 PM       |
+----------------+
5 rows in set (0.00 sec)
VBScript Join Function

A Function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method.
Join(List[,delimiter]) 

List, a Required parameter. An Array that contains the substrings that are to be joined.
List, a Required parameter. An Array that contains the substrings that are to be joined.
delimiter, an Optional Parameter. The Character, which used as a delimiter while returning the string. The Default delimiter is Space.
delimiter, an Optional Parameter. The Character, which used as a delimiter while returning the string. The Default delimiter is Space.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         ' Join using spaces
         a = array("Red","Blue","Yellow")
         b = join(a)
         document.write("The value of b " & " is :"  & b & "<br />")

         ' Join using $
         b = join(a,"$")
         document.write("The Join result after using delimiter is : " & b & "<br />")

      </script>
   </body>
</html>
When the above code is saved as .html and executed in Internet Explorer, it produces the following result −
The value of b is :Red Blue Yellow
The Join result after using delimiter is : Red$Blue$Yellow


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Prolog - Different and Not

Here we will define two predicates — different and not. The different predicate will check whether two given arguments are same or not. If they are same, it will return false, otherwise it will return true. The not predicate is used to negate some statement, which means, when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true.
So the term ‘different’ can be expressed in three different ways as given below −
X and Y are not literally the same
X and Y are not literally the same
X and Y do not match
X and Y do not match
The values of arithmetic expression X and Y are not equal
The values of arithmetic expression X and Y are not equal
So in Prolog, we will try to express the statements as follows −
If X and Y match, then different(X,Y) fails,
If X and Y match, then different(X,Y) fails,
Otherwise different(X,Y) succeeds.
Otherwise different(X,Y) succeeds.
The respective prolog syntax will be as follows −
different(X, X) :- !, fail.
different(X, X) :- !, fail.
different(X, Y).
different(X, Y).
We can also express it using disjunctive clauses as given below −
different(X, Y) :- X = Y, !, fail ; true.   % true is goal that always succeeds
different(X, Y) :- X = Y, !, fail ; true.   % true is goal that always succeeds
Following example shows how this can be done in prolog −
different(X, X) :- !, fail.
different(X, Y).
| ?- [diff_rel].
compiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/diff_rel.pl:2: warning: singleton variables [X,Y] for different/2
D:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 2 lines read - 327 bytes written, 11 ms

yes
| ?- different(100,200).

yes
| ?- different(100,100).

no
| ?- different(abc,def).

yes
| ?- different(abc,abc).

no
| ?-

Let us see a program using the disjunctive clauses −
different(X, Y) :- X = Y, !, fail ; true.
| ?- [diff_rel].
compiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 0 lines read - 556 bytes written, 17 ms

yes
| ?- different(100,200).

yes
| ?- different(100,100).

no
| ?- different(abc,def).

yes
| ?- different(abc,abc).

no
| ?-

The not relation is very much useful in different cases. In our traditional programming languages also, we use the logical not operation to negate some statement. So it means that when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true.
In prolog, we can define this as shown below −
not(P) :- P, !, fail ; true.

So if P is true, then cut and fail, this will return false, otherwise it will be true. Now let us see one simple code to understand this concept.
not(P) :- P, !, fail ; true.
| ?- [not_rel].
compiling D:/TP Prolog/Sample_Codes/not_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/not_rel.pl compiled, 0 lines read - 630 bytes written, 17 ms

yes
| ?- not(true).

no
| ?- not(fail).

yes
| ?-


    65 Lectures 
     5 hours 

 Arnab Chakraborty

    78 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
C++ program to find ways an integer can be expressed as sum of n-th power of unique natural numbers

In this article, we will be discussing a program to find ways an integer (say X) can be expressed as sum of n-th power of unique natural numbers.
For example, let X = 100 and n = 2
Then there would be 3 ways to express 100 as sum of squares of natural numbers.
100 = 102
100 = 62 + 82
100 = 12 + 32 + 42 + 52 + 72
This can be done easily by using recursion. We would start from 1 and go till the n-th root of the given number. In every run, we would subtract the n-th power of natural numbers (starting from 1) from the given number till the number become less than. This would give us the ways the number can be represented in as sum of n-th powers of natural numbers.
 Live Demo
#include<iostream>
#include <math.h>
using namespace std;
int result = 0;
int ways(int number, int a, int init, int n){
   if (a == 0) {
      result++;
   }
   //setting the higher limit
   int max = (int)floor(pow(number, 1.0 / n));
   for (int i = init + 1; i <= max; i++) {
      //subtracting n-th power values starting from 1
      int b = a - (int)pow(i, n);
      if (b >= 0)
         ways(number, a - (int)pow(i, n), i, n);
   }
   return result;
}
int main() {
   int a = 100, n = 2;
   cout << ways(a, a, 0, n);
   return 0;
}
3
Simple interest in Python Program

In this article, we will learn about the calculation of simple interest in Python 3.x. Or earlier.
is calculated by multiplying the daily interest rate by the principal amount by the number of days that elapse between the payments.
Mathematically,
Simple Interest = (P x T x R)/100
Where,
P is the principal amount
T is the time and
R is the rate
For Example,
If P = 1000,R = 1,T = 2
Then SI=20.0
Now let’s see how we can implement a simple interest calculator in Python.
 Live Demo
P = 1000
R = 1
T = 2
# simple interest
SI = (P * R * T) / 100
print("simple interest is", SI)
simple interest is 20.0

Here the simple interest is obtained three arithmetic products and one arithmetic division.
Now let’s see the scope of the variables declared. As shown in the figure below all variables are declared in the global scope.
In this article, we learnt about simple interest and it’s implementation using Python script.
HTML | DOM Dialog close() Method - GeeksforGeeks

31 May, 2019
The DOM Dialog close() method is used to close the dialog. The Dialog element is accessed by getElementById(). It is used in HTML5.While using this method, the user can interact with other elements on the page. It is used with Dialog show() method.
Syntax:
dialogObject.close()
Example: This example shows the working of Dialog close() Method:
<!DOCTYPE html><html><body>  <h3> HTML | DOM Dialog close() Method</h3><p>Click on the below buttons to show or close the dialog window.</p>  <button onclick="showDialog()">Show dialog box</button><button onclick="closeDialog()">Close dialog box</button>    <dialog id="showDialog" style= "color:green">            Welcome to GeeksforGeeks</dialog>  <script>var gfg = document.getElementById("showDialog");   function showDialog() { gfg.show(); }   function closeDialog() { gfg.close(); } </script>  </body></html>                                        
Output:Before Clicking on Button:
After Clicking on Show Button:
After Clicking on Close Button:
Supported Browsers:
Google Chrome 37.0
Opera 24.0
Safari 6.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Angular File Upload
Search Bar using HTML, CSS and JavaScript
How to fix the height of rows in the table?
How to get values from html input array using JavaScript ?
Make a div horizontally scrollable using CSS
Moment.js moment().fromNow() Function - GeeksforGeeks

24 Jul, 2020
The moment().fromNow() function is used to calculate the time from now in Node.js. This function returns the time, spend from the date which is passed in parameter.
Syntax:
moment().fromNow(Boolean);
Parameters: This function has one optional boolean parameter which is passed to get the value without the suffix.
Return Value: This function returns the date calculated.
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below.
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js as shown below.
Example 1: Filename: index.js
// Requiring the moduleconst moment = require('moment');   // Function callvar result = moment([2010, 8, 24]).fromNow();console.log(result);
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:10 years ago

The project structure will look like this:
Run index.js file using below command:node index.jsOutput:10 years ago

node index.js
Output:
10 years ago

Example 2: Filename: index.js
// Requiring the moduleconst moment = require('moment');   function timeFromNow(date){   return moment([2015, 8, 24]).fromNow(true);}   // Function callvar result = timeFromNow(moment);console.log("Result:", result);
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Result: 5 years

The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Result: 5 years

node index.js
Output:
Result: 5 years

Reference: https://momentjs.com/docs/#/displaying/fromnow/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js path.resolve() Method
Node.js crypto.createCipheriv() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Node.js fs.readdir() Method
Express.js res.render() Function
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page?
SQL - Foreign Key

A foreign key is a key used to link two tables together. This is sometimes also called as a referencing key.
A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).
Consider the structure of the following two tables.
CUSTOMERS table
CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25) ,
   SALARY   DECIMAL (18, 2),       
   PRIMARY KEY (ID)
);
ORDERS table
CREATE TABLE ORDERS (
   ID          INT        NOT NULL,
   DATE        DATETIME, 
   CUSTOMER_ID INT references CUSTOMERS(ID),
   AMOUNT     double,
   PRIMARY KEY (ID)
);
If the ORDERS table has already been created and the foreign key has not yet been set, the use the syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS 
   ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);

To drop a FOREIGN KEY constraint, use the following SQL syntax.
ALTER TABLE ORDERS
   DROP FOREIGN KEY;

    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
p5.js preload() Function

22 Feb, 2021
The preload() function in p5.js is used to asynchronously load files before the setup() function. It runs exactly once in when the sketch is loaded.
Most users do not use the preload() function as the same task can be done in setup() function. However, it is nice to separate similar code in our program to improve its scalability and modularity. Generally preload() function is used to load things like, images, 3D models, fonts, etc. in the sketch. The “loading...” text is displayed during the loading of the resources.
Syntax:
preload() {
   // All loading calls here
}
Parameters: This function does not accept any parameters.
Below example illustrates the preload() function in p5.js:
Example 1:
Javascript
let gfg_img;function preload() {    // Loading the image  gfg_img = loadImage('/gfg.png');}  function setup() {  createCanvas(400, 400);}  function draw() {    // Set background color to green  background('green');    // Show loaded image on screen at (100, 100)  image(gfg_img, 100, 100);}
Output:
Example 2:
Javascript
let cylinder;function preload() {    // Loading a cylinder model  cylinder = loadModel('/cylinder.stl', true);}  function setup() {  createCanvas(400, 400, WEBGL);  noLoop();}  function draw() {    // Set background color to green  background('green');    // Display and rotate the model  rotateX(90);  model(cylinder);}
Output:
JavaScript-p5.js
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
First Class functions in Python

25 Nov, 2020
First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions.
Properties of first class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, ...
Examples illustrating First Class functions in Python
1. Functions are objects: Python functions are first class objects. In the example below, we are assigning function to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell.
# Python program to illustrate functions# can be treated as objectsdef shout(text):    return text.upper()  print (shout('Hello'))  yell = shout  print (yell('Hello'))
Output:
HELLO
HELLO

2. Functions can be passed as arguments to other functions: Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, we have created a function greet which takes a function as an argument.
# Python program to illustrate functions# can be passed as arguments to other functionsdef shout(text):    return text.upper()  def whisper(text):    return text.lower()  def greet(func):    # storing the function in a variable    greeting = func("""Hi, I am created by a function                    passed as an argument.""")    print (greeting)   greet(shout)greet(whisper)
Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

3. Functions can return another function: Because functions are objects we can return a function from another function. In the below example, the create_adder function returns adder function.
# Python program to illustrate functions# Functions can return another function  def create_adder(x):    def adder(y):        return x+y      return adder  add_15 = create_adder(15)  print (add_15(10))
Output:
25

This article is contributed by Mayank Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Reversing a Tuple

27 Dec, 2017
As we know that in Python, tuples are immutable, thus it cannot be changed or altered. This provides us with limited ways of reversing a tuple, unlike a list. We will go through few techniques on how a tuple in python can be reversed.Examples:
Input : tuples = ('z','a','d','f','g','e','e','k')
Output : ('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')

Input : tuples = (10, 11, 12, 13, 14, 15)
Output : (15, 14, 13, 12, 11, 10)

Method 1: Using the slicing technique.In this technique, a copy of the tuple is made and the tuple is not sorted in-place. Since tuples are immutable, there is no way to reverse a tuple in-place. Creating a copy requires more space to hold all of the existing elements. Therefore, this exhausts memory.
# Reversing a tuple using slicing technique# New tuple is createddef Reverse(tuples):    new_tup = tuples[::-1]    return new_tup      # Driver Codetuples = ('z','a','d','f','g','e','e','k')print(Reverse(tuples))
Output:
('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')

Method 2: Using the reversed() built-in function.In this method, we do not make any copy of the tuple. Instead, we get a reverse iterator which we use to cycle through the tuple, similar to the list.
# Reversing a list using reversed()def Reverse(tuples):    new_tup = ()    for k in reversed(tuples):        new_tup = new_tup + (k,)    print new_tup  # Driver Codetuples = (10, 11, 12, 13, 14, 15)Reverse(tuples)
Output:
(15, 14, 13, 12, 11, 10)

python-tuple
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Instance and class methods in Dart

11 May, 2020
Dart provides us with the ability to create methods of our own. The methods are created to perform certain actions in class. Methods help us to remove the complexity of the program. It must be noted that methods may and may not return any value and also it may or may not take any parameter as input. Methods in a class can be either an object method or a class method.
There are two types of methods in Dart:
Instance MethodClass Method
Instance Method
Class Method
Unless the method is declared as static it is classified as an instance method in a class. They are allowed to access instance variables. To call the method of this class you have to first create an object.
Syntax:
  
// Declaring instance method
return_type method_name() {

  // Body of method
}

// Creating object
class_name object_name = new class_name();

// Calling instance method
object_name.method_name();
Creating instance method in Dart –
// Creating Class named Gfgclass Gfg {    // Declaring instance variable    int a;    int b;      // Creating instance method name     // sum with two parameters    void sum(int c, int d)    {        // Using this to set the values of the        // input to instance variable        this.a = c;        this.b = d;          // Printing the result        print('Sum of numbers is ${a + b}');    }}  void main(){    // Creating instance of the class Gfg(Creating Object)    Gfg geek = new Gfg();      // Calling the method sum with the use of object    geek.sum(21, 12);}
Output:
Sum of numbers is 33
All the methods declared with static keyword are termed as class method. They can’t access non-static variables and can’t invoke non-static methods of the class. It must be noted that unlike instance method class method can directly be called by using class name.
Syntax:
 
// Creating class method
static return_type method_name() {

   // Body of method
}

// Calling class method
class_name.method_name();
Creating class method in Dart –
// Creating Class named Gfgclass Gfg {      // Creating a class method name    // sum with two parameters    static void sum(int c, int d)    {        // Printing the result        print('Sum of numbers is ${c + d}');    }}  void main(){    // Calling the method sum without the    // use of object i.e with class name    Gfg.sum(11, 32);}
Output:
Sum of numbers is 43
Dart Methods
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Stack Widget
Dart Tutorial
How to Append or Concatenate Strings in Dart?
Flutter - Search Bar
Operators in Dart
Flutter - Dialogs
Difference Between su and su – Command in Linux

15 Mar, 2021
As a new Linux user, you may always face confusion regarding the difference between su command and su – command. But before knowing about the difference between su and su – command, we need to make ourselves familiar with Linux User Environment 
Linux User Environment: Linux’s systems are multi-user environments. Whenever Linux operating system creates a new shell session(after a new terminal being started on Linux) it started preparing an environment for itself. This environment basically holds the Environment variable(Environmental depends on shell type, Bash is generally used by most of the Linux distribution).
For example, pwd command is an environmental variable.
The major difference between su & su – command
su command is an abbreviation for “substitute user” because it is used for switching to another user during a normal login session, but it is often mistaken as an abbreviation for “super user” as mainly su command is used for getting “super user” privileges as when su command is run without a username, we automatically become the superuser after giving the correct root password and after that, we will enter root’s default environment, by only typing the following command:
su
Now logged in as root user/super user
When we switch from one user to another user using the normal su command the current directory remains the same as of the previous user like this
When we switch from one user to another user using su — command the current directory changes to the home directory of the target user like this:
su command does not create a new User Environment (in the simple term they pretends to be the target user) but su — creates a totally new User Environment (in the simple term they are actually the target user) that we can check with environment variables like:
echo $PATH
For su command
 
For su – command
 
 
For more info check the su manual by typing:
man su
tithimukherjee
linux-command
Picked
Technical Scripter 2020
Difference Between
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Compile-time and Run-time Polymorphism in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
Python | Lowercase first character of String

27 Jun, 2019
The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the first character of string to lowercase. Let’s discuss certain ways in which this can be performed.
Method #1 : Using string slicing + lower()This task can easily be performed using the lower method which lowercases the characters provided to it and slicing can be used to add the remaining string after the lowercase first character.
# Python3 code to demonstrate working of# Lowercase first character of String# Using lower() + string slicing  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + str(test_str))  # Using lower() + string slicing# Lowercase first character of Stringres = test_str[0].lower() + test_str[1:]  # printing result print("The string after lowercasing initial character : " + str(res))
The original string is : GeeksforGeeks
The string after lowercasing initial character : geeksforGeeks

 
Method #2 : Using lambda + string slicing + lower()The recipe of lambda function has to be added if we need to perform the task of handling None values or empty strings as well, and this becomes essential to handle edge cases.
# Python3 code to demonstrate working of# Lowercase first character of String# Using lower() + string slicing + lambda  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + str(test_str))  # Using lower() + string slicing + lambda# Lowercase first character of Stringres = lambda test_str: test_str[:1].lower() +               test_str[1:] if test_str else ''  # printing result print("The string after lowercasing initial character : " + str(res(test_str)))
The original string is : GeeksforGeeks
The string after lowercasing initial character : geeksforGeeks

Python string-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Vim - Diff

Similar to UNIX diff command we can use Vim to show diff in much better manner. It will show diff in colorful manner. In this chapter, we will discuss following items −
Show differences between files
Activate and deactivate diff mode
Navigation in diff mode
Applying changes from diff window
To show differences between files execute below command −
$ vimdiff <file> <file> 
OR 
$ vim –d <file> <file>

For instance below command shows differences −
In above image, text highlighted in magenta color is common. Remaining text is highlighted in red color which indicates that there are some differences after common text.
If you are already in vim and you want to perform diff action, then use one of the following command −
Use below command to perform horizontal split −
:diffsplit filename

Above images shows that we are comparing two files namely message-1.txt and message-2.txt.
To perform vertical split use following command −
:vert diffsplit <filename>

It opens following window −
Above images shows that we are comparing two files namely message-1.txt and message-2.txt.
Navigation in diff mode is little bit different. For instance, when you scroll text from one window then text from adjacent window also scrolled. This is called scrollbind. To enable this use −
:set scrollbind

To disable this use −
:set noscrollbind

If you edit file in this mode then use following command to update diff −
:diffupdate

To switch between diff windows execute following command −
Ctrl + w Ctrl + w

Please note that, we have to press Ctrl + w 2 times.
In diff window, execute following command to jump to previous change −
[c

In diff window, execute following command to jump to next change −
]c

To apply change from adjacent diff window to current diff windows execute −
:diffget

For instance, if you are in left window and you want to take change from right window to current window then you will execute above command.
To apply change from current diff window to adjacent diff window execute −
:diffput

For instance, if you are in left window and you want apply change from current window to right window then you will execute above command.
Python Tkinter | Create different type of lines using Canvas class

02 Nov, 2021
In Tkinter, Canvas.create_line() method is used to create lines in any canvas. These lines can only be seen on canvas so first, you need to create a Canvas object and later pack it into the main window. 
Syntax: 
Canvas.create_line(x1, y1, x2, y2, ...., options = ...)
Note: Minimum of 4 points are required to create a line, but you can also add multiple points to create different drawings.Class parameters: 
Data members used: master canvasMember functions used for the given class: create() methodWidgets used: CanvasTkinter method used: canvas.create_line() pack() title() geometry()  
Below is the Python code –  
Python3
# Imports each and every method and class# of module tkinter and tkinter.ttkfrom tkinter import *from tkinter.ttk import * class GFG:    def __init__(self, master = None):        self.master = master         # Calls create method of class GFG        self.create()     def create(self):         # This creates a object of class canvas        self.canvas = Canvas(self.master)         # This creates a line of length 200 (straight horizontal line)        self.canvas.create_line(15, 25, 200, 25)         # This creates a lines of 300 (straight vertical dashed line)        self.canvas.create_line(300, 35, 300, 200, dash = (5, 2))                 # This creates a triangle (triangle can be created by other methods also)        self.canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)                 # This pack the canvas to the main window and make it expandable        self.canvas.pack(fill = BOTH, expand = True) if __name__ == "__main__":         # object of class Tk, responsible for creating    # a tkinter toplevel window    master = Tk()    geeks = GFG(master)     # This sets the title to Lines    master.title("Lines")     # This sets the geometry and position of window    # on the screen    master.geometry("400x250 + 300 + 300")     # Infinite loop breaks only by interrupt    master.mainloop()
Output:  
Example 2: For filing color in the shapes.
Python3
from tkinter import *root=Tk()root.title("canvas line")root.geometry("555x555")our_canvas=Canvas(root,width=300,height=200,bg="white")our_canvas.pack()#creating rectangleour_canvas.create_rectangle(50,150,250,50,fill="blue")root.mainloop()
Output:
 
ysachin2314
kapoorsagar226
simmytarika5
Python-gui
Python-tkinter
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
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
How to Check if the Number is Prime Number in Excel?

11 Aug, 2021
A prime number is a number that is greater than 1 and has no positive divisor other than 1 and the number itself.
To check whether the number is prime or not we have to divide the number with all the numbers between 2 and the square root of that number. And if it gives remainder 0 in any of the divisions it means that the number is a positive factor and ultimately results in a non-prime number. So if any of the divisions don’t result in the remainder 0 then it means that the number doesn’t have any positive factor and ultimately results in the Prime number.
Take the number
If the number is 2 then it is a Prime number else follow the next steps
Derive the square root of the number
Take the upper bound of the square root obtained and then minus it by one
Divide the number with all the numbers between 2 and the square root of the number
If the remainder is 0 in any of the divisions then non-prime.
Else it is the prime number
Formula:
=IF(F6=2,"Prime",IF(AND(MOD(F6,ROW(OFFSET($C$2,,,ROUNDUP(SQRT(F6),0)-1)))<>0),"Prime","Not Prime"))
Let’s see each of these functions one by one so that it is clearly understood.
Step1: First of all check if the given number is 2 or not and if it is TRUE then print out that it is PRIME.
Step 2: If the number is not 2 then derive the square root of the given number.
Step 3: Round off the output of the square root and minus one from it ( we have to check from 2 to square root of a given number which is not included)
Step 4: Taking the range of numbers from the 2 to the one less than the square root of the given number.
Step 5: Taking one by one, the numbers from that range to evaluate further for the division.
Step-6: Dividing the given number from the number in the range of 2 to one less then square root of the given number and checking whether it is 0 or not. If it is 0 then the given number is NOT-PRIME and if it is not 0 then the given number is PRIME.
Output:
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.