code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE CS 2019 | Question 27

17 Aug, 2021
Consider the following C program:
#include <stdio.h>  int jumble(int x, int y) {    x = 2 * x + y;    return x;  }int main() {  int x = 2, y = 5;  y = jumble(y, x);  x = jumble(y, x);  printf("%d\n", x);  return 0;  }
The value printed by program is __________ .
Note: This was Numerical Type question.(A) 26(B) 2(C) 5(D) 12Answer: (A)Explanation:
#include <stdio.h>  int jumble(int x, int y) {    x = 2 * x + y;    return x;  }int main() {  int x = 2, y = 5;  y = jumble(y, x);  x = jumble(y, x);  printf("%d\n", x);  return 0;  }
Initially x = 2, y = 5;jumble (5, 2) is called and y will updated as 12jumble (12, 2) is called and x will updated as 26Final value of x = 26
So, option (A) is correct.
GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:14 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
sooda367
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2004 | Question 31
What is the main difference between int.Parse() and Convert.ToInt32 in C#?

Convert a string representation of number to an integer, using the int.Parse or Convert.ToInt32 method in C#. If the string cannot be converted, then the int.Parse or Convert.ToInt32 method returns an exception
Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, and it throws an ArgumentNullException error.
 Live Demo
class Program {
   static void Main() {
      int res;
      string myStr = "5000";
      res = int.Parse(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}
Converting String is a numeric representation: 5000
 Live Demo
class Program {
   static void Main() {
      int res;
      string myStr = null;
      res = Convert.ToInt32(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}
Converting String is a numeric representation: 0
 Live Demo
class Program {
   static void Main() {
      int res;
      string myStr = null;
      res = int.Parse(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}
Unhandled exception. System.ArgumentNullException: Value cannot be null.
Set the width of a button with CSS

To set the button width, use the CSS width property.
You can try to run the following code to set the width of a button −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .btn {
            background-color: yellow;
            color: black;
            width: 120px;
            text-align: center;
            font-size: 15px;
            padding: 20px;
            border-radius: 15px;
            border: 3px dashed blue;
         }
      </style>
   </head>
   <body>
      <h2>Result</h2>
      <p>Click below for result:</p>
      <button class = "btn">Result</button>
   </body>
</html>
SQL Query to Convert VARCHAR to INT

28 Oct, 2021
SQL Server’s CAST() and CONVERT() methods can be used to convert VARCHAR to INT. We’ll also look at the more efficient and secure approach to transform values from one data type to another.
The CAST() function in SQL Server is used to cast or transform a value or an expression from one data type to another.
Syntax :
CAST ( expression AS target_type [ ( length ) ] )
Parameters:
expression – Any value of any type that will be converted.
target_type – Target data type to which the value will be converted. e.g. INT, BIT, SQL_VARIANT, etc.
length – Optional parameter that specifies the length of the target_type, default length is 30.
Let’s take an example where the CAST() function is used to convert VARCHAR to INT.
Query:
SELECT CAST('1234' AS INT) AS Result;
Output:
In SQL Server, the CONVERT() function is used to convert a value of one type to another. Converting anything involves changing its shape or value.
Syntax :
SELECT CONVERT ( target_type ( length ), expression )  
Parameters:
target_type – Data type to which the expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc.
length – It provides the length of the target_type. Length is not mandatory. The default length is set to 30.
expression – expression is anything that will be converted.
In the below example, the CONVERT() function is used to convert VARCHAR to INT.
Query:
SELECT CONVERT(INT,'5678') AS Result;
Now Lets us discuss a more efficient approach to convert the values from one data type to another using SQL Server’s TRY_CAST() and  TRY_CONVERT() function:
The TRY_CAST() function attempts to cast the input value to a value of the given data type. If the cast is successful, it returns the value in the provided data; else, it returns NULL. However, if you request a conversion that is not valid, the TRY_CAST() method will return an error.
Syntax :
TRY_CAST ( expression AS data_type [ ( length ) ] )  
Parameters used:
data_type: Valid data type into which the function will cast the expression.
expression: Value to be cast.
Query:
SELECT TRY_CAST('1234' as INT) as Result;
Query:
SELECT TRY_CAST('1234abc' as INT) as Result;
The TRY_CONVERT() method attempts to convert the value supplied to it to the data type specified. If the cast is successful, it returns the value as the given data; else, it returns NULL. If you request a conversion that is explicitly forbidden, the TRY CONVERT() method will return an error.
Syntax :
TRY_CONVERT ( data_type[(length)], expression [,style])
Parameters used:
data_type:  Valid data type into which the function will cast the expression.
expression:  Value to be cast.
style: Is a provided integer that specifies how the function will translate the expression.
Query:
SELECT TRY_CONVERT( INT ,'5678') as Result;
Query:
SELECT TRY_CONVERT( INT ,'56abc') as Result;
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DELETE method- Python requests

26 Feb, 2020
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make DELETE request to a specified URL using requests.delete() method. Before checking out the DELETE method, let’s figure out what a Http DELETE request is –
DELETE is a request method supported by HTTP used by the World Wide Web. The DELETE method deletes the specified resource. As with a PUT request, you need to specify a particular resource for this operation. A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.An example URI looks like for delete operation
http://www.example.com/articles/12345
Python’s requests module provides in-built method called delete() for making a DELETE request to a specified URI.
Syntax –
requests.delete(url, params={key: value}, args)

Example –
Let’s try making a request to httpbin’s APIs for example purposes.
import requests  # Making a DELETE requestr = requests.delete('https://httpbin.org / delete', data ={'key':'value'})  # check status code for response received# success code - 200print(r)  # print content of requestprint(r.json())
save this file as request.py and through terminal run,
python request.py
Output –
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.
Python-requests
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Get the sum of multiple row (not all) values from a MySQL table?

You can use aggregate function SUM() from MySQL for this. Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Amount int
);
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Amount) values(400);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Amount) values(10);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Amount) values(50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Amount) values(500);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Amount) values(80);
Query OK, 1 row affected (0.09 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+
| Id | Amount |
+----+--------+
| 1  | 400    |
| 2  | 10     |
| 3  | 50     |
| 4  | 500    |
| 5  | 80     |
+----+--------+
5 rows in set (0.00 sec)
Here is the query to get the sum of rows (not all) out of MySQL table −
mysql> select sum(Amount) from DemoTable where Id in(1,4,5);
This will produce the following output −
+-------------+
| sum(Amount) |
+-------------+
| 980         |
+-------------+
1 row in set (0.00 sec)
C | Arrays | Question 2 - GeeksforGeeks

11 Jan, 2013
Predict the output of below program:
#include <stdio.h>  int main(){    int arr[5];    // Assume base address of arr is 2000 and size of integer is 32 bit    printf("%u %u", arr + 1, &arr + 1);      return 0;} 
(A) 2004 2020(B) 2004 2004(C) 2004 Garbage value(D) The program fails to compile because Address-of operator cannot be used with array nameAnswer: (A)Explanation: Name of array in C gives the address(except in sizeof operator) of the first element. Adding 1 to this address gives the address plus the sizeof type the array has. Applying the Address-of operator before the array name gives the address of the whole array. Adding 1 to this address gives the address plus the sizeof whole array.
Arrays
C-Arrays
C Language
C Quiz
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Misc | Question 7
Output of C programs | Set 64 (Pointers)
Display two digits day number in Java

To display two-digit day number, use the SimpleDateFormat('dd') as shown below −
// displaying two-digit day number
f = new SimpleDateFormat("dd");
String strDay = f.format(new Date());
System.out.println("Day Number = "+strDay);
Since, we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date.
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
The following is an example.
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
      // current time
      Format f = new SimpleDateFormat("HH.mm.ss Z");
      String strResult = f.format(new Date());
      System.out.println("Time = "+strResult);
      // displaying two-digit day number
      f = new SimpleDateFormat("dd");
      String strDay = f.format(new Date());
      System.out.println("Day Number = "+strDay);
      // displaying hour
      f = new SimpleDateFormat("H");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
      // displaying minutes
      f = new SimpleDateFormat("mm");
      String strMinute = f.format(new Date());
      System.out.println("Current Minutes = "+strMinute);
      // displaying seconds
      f = new SimpleDateFormat("ss");
      String strSeconds = f.format(new Date());
      System.out.println("Current Seconds = "+strSeconds);
   }
}
Today's date = 26/November/2018 08:59:48
Time = 08.59.48 +0000
Day Number = 26
Current Hour = 8
Current Minutes = 59
Current Seconds = 48
p5.js | min() function - GeeksforGeeks

09 Apr, 2019
The min() function in p5.js is used to get the minimum value from the sequence of numbers.
Syntax:
min(a, b)
or
min(arr)
Parameters: The min(a, b) function accepts two parameters which are two different number and compared to get minimum value among them. The min(arr) function accepts a single parameter array.
Return Value: It returns the minimum value among the different numbers.
Below program illustrates the min() function in p5.js:
Example: This example uses min() function to get the minimum value.
function setup() {        // Create Canvas of size 270*80     createCanvas(350, 130); }    function draw() {            // Set the background color     background(220);            // Call to min() function     let u = min(1, 3);    let v = min(1, 1);    let w = min(5, 9);    let x = min(2, 3.9);    let y = min(1.5, 3.2);           // Set the size of text     textSize(16);            // Set the text color     fill(color('red'));          // Getting minimum value        text("Minimum value between (1, 3) is: " + u, 50, 30);    text("Minimum value between (1, 1) is: " + v, 50, 50);    text("Minimum value between (5, 9) is: " + w, 50, 70);    text("Minimum value between (2, 3.9) is: " + x, 50, 90);    text("Minimum value between (1.5, 3.2) is: " + y, 50, 110);     } 
Output:
Reference: https://p5js.org/reference/#/p5/min
JavaScript-p5.js
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 get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
java.time.LocalDateTime.parse() Method Example

The java.time.LocalDateTime.parse(CharSequence text) method obtains an instance of LocalDateTime from a text string such as 2017-02-03T10:15:30.
Following is the declaration for java.time.LocalDateTime.parse(CharSequence text) method.
public static LocalDateTime parse(CharSequence text)

text − the text to parse such as "2017-02-03T10:15:30", not null.
the local date, not null.
DateTimeParseException − if the text cannot be parsed.
The following example shows the usage of java.time.LocalDateTime.parse(CharSequence text) method.
package com.tutorialspoint;

import java.time.LocalDateTime;

public class LocalDateTimeDemo {
   public static void main(String[] args) {
 
      LocalDateTime date = LocalDateTime.parse("2017-02-03T10:15:30");
      System.out.println(date);  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T10:15:30

 Print
 Add Notes
 Bookmark this page
Solidity - Variable Scope

Scope of local variables is limited to function in which they are defined but State variables can have three types of scopes.
Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated.
Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated.
Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this.
Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this.
Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it.
Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it.
pragma solidity ^0.5.0;
contract C {
   uint public data = 30;
   uint internal iData= 10;
   
   function x() public returns (uint) {
      data = 3; // internal access
      return data;
   }
}
contract Caller {
   C c = new C();
   function f() public view returns (uint) {
      return c.data(); //external access
   }
}
contract D is C {
   function y() public returns (uint) {
      iData = 3; // internal access
      return iData;
   }
   function getResult() public view returns(uint){
      uint a = 1; // local variable
      uint b = 2;
      uint result = a + b;
      return storedData; //access the state variable
   }
}

    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
How to print div content using jQuery?

Let’s say we have the following button −
<input type='button' id='buttonId' value='Press Me To print the data'>
On click of the above button, call the function() with on() −
$('#buttonId').on('click', function () {
   displayTheData();
})
The above function is using the html() to display the following div −
<div id='printThisDivIdOnButtonClick'>
   <p>I am inside the div tag...</p>
</div>
Following is the complete code to print div content −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
   <div id='printThisDivIdOnButtonClick'>
      <p>I am inside the div tag...</p>
   </div>
   <p>I am not inside the div tag...</p>
   <input type='button' id='buttonId' value='Press Me To print the data'>
   <div id="printTheDivisionValue"></div>
</body>
<script>
   $('#buttonId').on('click', function () {
      displayTheData();
   })
   function displayTheData() {
      $(document).ready(function () {
         $("#printTheDivisionValue").html($("#printThisDivIdOnButtonClick").html());
      });
   }
</script>
</html>
To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor.
The output is as follows −
Now click the button, you will get the following output.
The output is as follows −
Difference between namespace and class - GeeksforGeeks

26 Jan, 2018
Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. In essence, a namespace defines a scope.Following are some points to justify :
1. A namespace is a way of grouping identifiers so that they don’t clash. Using a class implies that you can create an instance of that class, not true with namespaces.
2. You can use using-declarations with namespaces, and that’s not possible with classes unless you derive from them.
3. You can reopen a namespace and add stuff across translation units. You cannot do this with classes.For example:-
namespace A {int f1();}  namespace A {int f2();}
is legal, but:
class A {    int f1();};  class A { // illegal    int f2();};
is not.
4.You can have unnamed namespaces but you can’t have a unnamed class.For example:
namespace { // fine  // some code....}  class { // illegal}
5. If length of a name makes code difficult to read, or is tedious to type in a header file where using directives can’t be used, we can make a namespace alias which serves as an abbreviation for the actual name. For example:
#include <iostream>  namespace foo {    namespace bar {        namespace baz {            int qux = 42;        }    }}  namespace fbz = foo::bar::baz;  int main(){    std::cout << fbz::qux << '\n';}
Output :
 42 
In case of class we have to use typedef.
class Car {public:    typedef std::vector<Wheel> WheelCollection;    WheelCollection wheels;};
cpp-class
cpp-namespaces
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java
The best way to remove duplicates from an array of objects in JavaScript?

Let’s say the following is our array of objects with duplicates −
var studentDetails=[
   {studentId:101},
   {studentId:104},
   {studentId:106},
   {studentId:104},
   {studentId:110},
   {studentId:106},
]
Use the concept of set to remove duplicates as in the below code −
var studentDetails=[
   {studentId:101},
   {studentId:104},
   {studentId:106},
   {studentId:104},
   {studentId:110},
   {studentId:106},
]
const distinctValues = new Set
const withoutDuplicate = []
for (const tempObj of studentDetails) {
   if (!distinctValues.has(tempObj.studentId)) {
      distinctValues.add(tempObj.studentId)
      withoutDuplicate.push(tempObj)
   }
}
console.log(withoutDuplicate);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo158.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo158.js
[
   { studentId: 101 },
   { studentId: 104 },
   { studentId: 106 },
   { studentId: 110 }
]
Extending a list in Python (5 different ways) - GeeksforGeeks

11 Oct, 2019
Extending a list in python can be done is following ways:1. Using append() function: We can append at the end of the list by using append() function. For appending any single value to the list or appending a list to the list, the syntax stays the same. But we can only append a single value at a time using append() function
# Python program to extend a list using append()  a = [10, 12, 13, 17]   # appending multiple valuesa.append(20)a.append(22)print(a)
Output:
[10, 12, 13, 17, 20, 22]

2. Using ‘+’ operator: We can add values by using the “+” operator. We can use [] to add any number of values to the list. Adding multiple values can be done by using ‘, ‘ values.
# Python program to extend a list using '+'   a = [10, 12, 13, 17]   # Appending single valuea = a + [20]  # append more then one valuesa = a + [30, 40]print(a)
Output:
[10, 12, 13, 17, 20, 30, 40]

3. Using slicing: Using slicing in python, single or multiple values can be added to a list.
a[:0] = [x, y, z...]
Here a is the list in which the values(x, y, z..) are to be added. In this method the values are appended to the front of the list.
# Python program to extend a list using 'slicing'   # appending multiple value a =[10, 12, 13, 17]   # add 1 numbera[:0] = [30]  # add two numbersa[:0] = [40, 50]print(a)
Output:
[40, 50, 30, 10, 12, 13, 17]

4.Using chain(): Using chain() iterator function, we can extend a list by the syntax:
list(chain(a, [x, y, z..]))
Here a is the list in which the values(x, y, z..) are to be added. In this method the values are appended to the end of the list.
# python program to extend a list using # "chain" iterator functionsfrom itertools import *  a = [10, 20, 30]  # extend a listprint(list(chain(a, [40, 50, 60])))
Output:
[10, 20, 30, 40, 50, 60]

5. Using Extend
# Python program to extend a list using extend() a = [10, 12, 13, 17]   b = [30, 40]  a.extend(b)  print(a)
Output:
[10, 12, 13, 17, 30, 40]

Akanksha_Rai
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
Is it possible to sum two fields in MongoDB using the Aggregation framework?

Yes, it is possible using the $project operator. Let us first create a collection with documents
> db.sumTwoFieldsDemo.insertOne({"FirstValue":150,"SecondValue":350});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b4bfe15e86fd1496b38cd")
}
> db.sumTwoFieldsDemo.insertOne({"FirstValue":450,"SecondValue":1550});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b4c1215e86fd1496b38ce")
}
> db.sumTwoFieldsDemo.insertOne({"FirstValue":2560,"SecondValue":2440});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b4c2715e86fd1496b38cf")
}
Following is the query to display all documents from a collection with the help of find() method
> db.sumTwoFieldsDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9b4bfe15e86fd1496b38cd"),
   "FirstValue" : 150,
   "SecondValue" : 350
}
{
   "_id" : ObjectId("5c9b4c1215e86fd1496b38ce"),
   "FirstValue" : 450,
   "SecondValue" : 1550
}
{
   "_id" : ObjectId("5c9b4c2715e86fd1496b38cf"),
   "FirstValue" : 2560,
   "SecondValue" : 2440
}
Following is the query to sum 2 fields in MongoDB using the $project operator
> db.sumTwoFieldsDemo.aggregate(
...    { "$project" :
...       {
...          'First' : '$FirstValue',
...          'Second' : '$SecondValue',
...          'TotalValueOfBothFields' : { '$add' : [ '$FirstValue', '$SecondValue' ] },
...       }
...    }
... );
This will produce the following output
{ "_id" : ObjectId("5c9b4bfe15e86fd1496b38cd"), "First" : 150, "Second" : 350, "TotalValueOfBothFields" : 500 }
{ "_id" : ObjectId("5c9b4c1215e86fd1496b38ce"), "First" : 450, "Second" : 1550, "TotalValueOfBothFields" : 2000 }
{ "_id" : ObjectId("5c9b4c2715e86fd1496b38cf"), "First" : 2560, "Second" : 2440, "TotalValueOfBothFields" : 5000 }
PySpark - Serializers

Serialization is used for performance tuning on Apache Spark. All data that is sent over the network or written to the disk or persisted in the memory should be serialized. Serialization plays an important role in costly operations.
PySpark supports custom serializers for performance tuning. The following two serializers are supported by PySpark −
Serializes objects using Python’s Marshal Serializer. This serializer is faster than PickleSerializer, but supports fewer datatypes.
class pyspark.MarshalSerializer

Serializes objects using Python’s Pickle Serializer. This serializer supports nearly any Python object, but may not be as fast as more specialized serializers.
class pyspark.PickleSerializer

Let us see an example on PySpark serialization. Here, we serialize the data using MarshalSerializer.
--------------------------------------serializing.py-------------------------------------
from pyspark.context import SparkContext
from pyspark.serializers import MarshalSerializer
sc = SparkContext("local", "serialization app", serializer = MarshalSerializer())
print(sc.parallelize(list(range(1000))).map(lambda x: 2 * x).take(10))
sc.stop()
--------------------------------------serializing.py-------------------------------------

Command − The command is as follows −
$SPARK_HOME/bin/spark-submit serializing.py

Output − The output of the above command is −
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

 Print
 Add Notes
 Bookmark this page
How to Restrict User to Enter Date Manually in Date Field using AngularJS ? - GeeksforGeeks

17 Dec, 2020
In this article, we will see how to restrict the user to enter the date manually in the date field.
Approach:
First, we need to write the code for input, and we need to give its type as the date in the HTML file.
Then in-order to restrict the user to enter date manually we can use onkeydown event.
In the onkeydownevent we need to return false so that we can restrict the user to enter the date manually.
In order to achieve the above objective, we need to write and function and return false in the ts file.
As we restricted the user to enter the date normally, the user can only enter the date from the calendar.
After completing the above steps save and run the project in order to see the output.
Code Implementation:
app.component.html:
HTML
<h1>    Restricting the user to enter     date manually in date field</h1>  <label for="vote">Select a date:</label>  <input type="date" id="vote" name="vote"     (keydown)="disableDate()">
app.component.ts:
Javascript
import { Component } from '@angular/core';  @Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})  export class AppComponent  {      disableDate(){      return false;  }  }
app.module.ts:
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';  import { AppComponent } from './app.component';  @NgModule({  imports:      [ BrowserModule, FormsModule ],  declarations: [ AppComponent ],  bootstrap:    [ AppComponent ]})export class AppModule { }
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
AngularJS-Function
HTML-Misc
Picked
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to create module with Routing in Angular 9 ?
How to setup 404 page in angular routing ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to read an external JSON file in JavaScript

Suppose we have a JSON file config.json that contains the following data −
{
   "secret": "sfsaad7898fdsfsdf^*($%^*$",
   "connectionString":
   "mongodb+srv://username:password@cluster0.laaif.mongodb.net/events?retryWrites=tr
   ue&w=majority",
   "localConnectionString":
   "mongodb+srv://username:password@cluster0.laaif.mongodb.net/eventsLocal?retryWrit
   es=true&w=majority",
   "frontendClient": "https://helloworld.com",
   "localFrontendClient": "http://localhost:3000"
}
And in the same directory (folder), we have a JavaScript file index.js.
Our task is to access the content of the json file through the JavaScript file.
We can use the require module to access the json file if we are running our JavaScript file in NodeJS environment.
The code for this will be −
const configData = require('./config.json');
console.log(typeof configData);
console.log(configData);
If we want to access the json file while running JavaScript in browser, we can use the ES6 import syntax to do that.
The code for this will be −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>READ JSON FILE</title>
</head>
<body>
<p id='main'></p>
<script type="module" src="./index.js"></script>
</body>
</html>
import configData from './config.json';
document.getElementById('main').innerHTML = JSON.stringify(configData);
And the output will be −
{
   secret: 'sfsaad7898fdsfsdf^*($%^*$',
   connectionString:
   'mongodb+srv://username:password@cluster0.laaif.mongodb.net/events?retryWrites=tr
   ue&w=majority',
   localConnectionString:
   'mongodb+srv://username:password@cluster0.laaif.mongodb.net/eventsLocal?retryWrit
   es=true&w=majority',
   frontendClient: 'https://helloworld.com',
   localFrontendClient: 'http://localhost:3000'
}
What are the SAM Interfaces in Java?

An interface having only one abstract method is known as a functional interface and also named as Single Abstract Method Interfaces (SAM Interfaces). One abstract method means that either a default method or an abstract method whose implementation is available by default is allowed. The instances of SAM interfaces are java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator and java.util.concurrent.Callable. The SAM interfaces can be implemented using lambda expressions or method references.
@FunctionalInterface
public interface Changeable {
 public void change(T o);
}
@FunctionalInterface
interface MyInterface {
   String reverse(String n);
}
public class LambdaReverseTest {
   public static void main( String[] args ) {
      MyInterface myInterface = (str) -> { // Lambda Expression
         String result = "";
         for(int i = str.length()-1; i >= 0 ; i--)
            result += str.charAt(i);
         return result;
      };
      System.out.println("The reverse of string is: " + myInterface.reverse("TutorialsPoint"));
   }
}
The reverse of string is: tnioPslairotuT
GATE | GATE-CS-2007 | Question 37 - GeeksforGeeks

19 Nov, 2018
Consider a pipelined processor with the following four stages:
IF: Instruction Fetch
ID: Instruction Decode and Operand Fetch
EX: Execute
WB: Write Back
The IF, ID and WB stages take one clock cycle each to complete the operation. The number of clock cycles for the EX stage dependson the instruction. The ADD and SUB instructions need 1 clock cycle and the MUL instruction needs 3 clock cycles in the EX stage. Operand forwarding is used in the pipelined processor. What is the number of clock cycles taken to complete the following sequence of instructions?
ADD R2, R1, R0       R2 <- R0 + R1
MUL R4, R3, R2       R4 <- R3 * R2
SUB R6, R5, R4       R6 <- R5 - R4  

(A) 7(B) 8(C) 10(D) 14Answer: (B)Explanation: Explanation:
Order of instruction cycle phases
IF”  ID”  EX”  WB”
We  have 3 instructions. which represents wait in pipeline due to result dependently.
 
This is the table shows the cycle phases and number of cycles require for given instruction.
No. of cycles required=8
So (B) is correct option.Quiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
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-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to concatenate MySQL distinct query results into a string?

Use group_concat() function from MySQL to concatenate. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Subject varchar(10)
   -> );
Query OK, 0 rows affected (0.43 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('C');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('C++');
Query OK, 1 row affected (0.25 sec)

mysql> insert into DemoTable values('C++');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values('MongoDB');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('MySQL');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('MongoDB');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('MongoDB');
Query OK, 1 row affected (0.34 sec)

mysql> insert into DemoTable values('Java');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('Java');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement:
mysql> select *from DemoTable;
This will produce the following output −
+---------+
| Subject |
+---------+
| C       |
| C++     |
| C++     |
| MongoDB |
| MySQL   |
| MongoDB |
| MongoDB |
| Java    |
| Java    |
+---------+
9 rows in set (0.00 sec)
Following is the query to concatenate SQL distinct query results into a string −
mysql> select group_concat(tbl.sub) from (select Subject sub from DemoTable group by Subject ) tbl;
This will produce the following output −
+--------------------------+
| group_concat(tbl.sub)    |
+--------------------------+
| C,C++,MongoDB,MySQL,Java |
+--------------------------+
1 row in set (0.04 sec)
Is name a reserved word in MySQL?

No, name is not a reserved word in MySQL, you can use without backtick symbol. If you are working on a reserved word then use backtick symbol. Let us first create a table −
mysql> create table name
   (
   name varchar(10)
   );
Query OK, 0 rows affected (0.78 sec)
Now you can insert some records in the table using insert command −
mysql> insert into name values('John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into name values('Carol');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from name;
+-------+
| name  |
+-------+
| John  |
| Carol |
+-------+
2 rows in set (0.00 sec)
If you have a reserved word then you need to use backtick symbol. Let us now create a table with table name as reserved word “select” −
mysql> create table `select`
   (
   `select` int
   );
Query OK, 0 rows affected (0.70 sec)
Above we have used a backtick symbol, since we are considering the table name as reserved word. Now you can insert some records in the table using insert command −
mysql> insert into `select` values(1);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select `select` from `select`;
+--------+
| select |
+--------+
| 1      |
+--------+
1 row in set (0.00 sec)
adduser command in Linux with Examples - GeeksforGeeks

22 Jun, 2020
adduser command in Linux is used to add a new user to your current Linux machine. This command allows you to modify the configurations of the user which is to be created. It is similar to the useradd command in Linux. The adduser command is much interactive as compared to useradd command.
To install adduser tool use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install adduser
In case of CentOS/RedHat
$sudo yum install adduser
In case of Fedora OS
$sudo dnf install adduser
1. To add a new user
adduser username
This command will add a new user to your Linux system. It will ask for some details and after entering those details a new user account would be created.
2. To add a user with a different shell.
sudo adduser username --shell /bin/sh
This command will change the default shell for the new user to /bin/sh.
3. To add a new user with a different configuration file.
adduser username --conf custom_config.conf
This command will take the configurations from the custom_config file and will create the new as per custom_config filename configurations.
4. To add a user with different home directory.
adduser username --home /home/manav/
This command will add the new user with /home/manav as the default directory.
5. To get the version of the adduser command.
adduser --version
This command will print the version details of the adduser command.
6. To display the help section of the adduser command
adduser -h
This command will display the help section of the adduser command.
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
'crontab' in Linux with Examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Tail command in Linux with examples
How to find and replace within a text file using Python?




The following code does the replacement in the given text file. 
After the replacement, the text is written to a new text file 'bar.txt'
f1 = open('foo.txt', 'r')
f2 = open('bar.txt', 'w')
for line in f1:
    print line
    f2.write(line.replace('Poetry', 'Prose'))
f2 = open('bar.txt', 'r')
for line in f2:
   print line,
f1.close()
f2.close()
This gives the output
Poetry is often considered the oldest form of literature. Poetry today is usually
 written down, but is still sometimes performed.
Prose is often considered the oldest form of literature. Prose today is usually
written down, but is still sometimes performed.
numpy.sum() in Python

03 Apr, 2020
numpy.sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis.
Parameters :arr : input array.axis : axis along which we want to calculate the sum value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : Different array in which we want to place the result. The array must have same dimensions as expected output. Default is None.initial : [scalar, optional] Starting value of the sum.
Return : Sum of the array elements (a scalar value if axis is none) or array with sum values along the specified axis.
Code #1:
# Python Program illustrating # numpy.sum() methodimport numpy as np        # 1D array arr = [20, 2, .2, 10, 4]     print("\nSum of arr : ", np.sum(arr))    print("Sum of arr(uint8) : ", np.sum(arr, dtype = np.uint8)) print("Sum of arr(float32) : ", np.sum(arr, dtype = np.float32))   print ("\nIs np.sum(arr).dtype == np.uint : ",        np.sum(arr).dtype == np.uint)   print ("Is np.sum(arr).dtype == np.float : ",        np.sum(arr).dtype == np.float) 
Output:
Sum of arr :  36.2
Sum of arr(uint8) :  36
Sum of arr(float32) :  36.2

Is np.sum(arr).dtype == np.uint :  False
Is np.sum(arr).dtype == np.uint :  True

 Code #2:
# Python Program illustrating # numpy.sum() methodimport numpy as np        # 2D array arr = [[14, 17, 12, 33, 44],          [15, 6, 27, 8, 19],         [23, 2, 54, 1, 4,]]     print("\nSum of arr : ", np.sum(arr))    print("Sum of arr(uint8) : ", np.sum(arr, dtype = np.uint8)) print("Sum of arr(float32) : ", np.sum(arr, dtype = np.float32))   print ("\nIs np.sum(arr).dtype == np.uint : ",                  np.sum(arr).dtype == np.uint)   print ("Is np.sum(arr).dtype == np.uint : ",               np.sum(arr).dtype == np.float) 
Output:
Sum of arr :  279
Sum of arr(uint8) :  23
Sum of arr(float32) :  279.0

Is np.sum(arr).dtype == np.uint :  False
Is np.sum(arr).dtype == np.uint :  False

 Code #3:
# Python Program illustrating # numpy.sum() method        import numpy as np        # 2D array  arr = [[14, 17, 12, 33, 44],          [15, 6, 27, 8, 19],         [23, 2, 54, 1, 4,]]     print("\nSum of arr : ", np.sum(arr)) print("Sum of arr(axis = 0) : ", np.sum(arr, axis = 0)) print("Sum of arr(axis = 1) : ", np.sum(arr, axis = 1))  print("\nSum of arr (keepdimension is True): \n",      np.sum(arr, axis = 1, keepdims = True))
Output:
Sum of arr :  279
Sum of arr(axis = 0) :  [52 25 93 42 67]
Sum of arr(axis = 1) :  [120  75  84]

Sum of arr (keepdimension is True): 
 [[120]
 [ 75]
 [ 84]]
HenryMoore
Python numpy-Mathematical Function
Python-numpy
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
Iterate over a list in Python
Convert integer to string in Python
PyQt5 – QCommandLinkButton Class

26 Jun, 2020
QCommandLinkButton is a control widget that was introduced by Windows Vista. Its intended use is similar to that of a radio button in that it is used to choose between a set of mutually exclusive options. The appearance of it is generally similar to that of a flat push button, but it allows for a descriptive text in addition to the normal button text. By default it will also carry an arrow icon, indicating that pressing the control will open another window or page or do something. Below is how the command link button looks like
Example :We will create a window having a label and the command link button and when the command link button pressed the counter will increment in the label
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys  class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()        # method for components    def UiComponents(self):          # counter value        self.n = 0          # creating label        label = QLabel("Counter", self)          # setting label geometry        label.setGeometry(100, 100, 100, 40)          # creating a command link button        cl_button = QCommandLinkButton("Next", self)          # setting geometry        cl_button.setGeometry(200, 100, 200, 40)          # adding action to the button        cl_button.clicked.connect(lambda: increment(self.n))            # method for incrementing the counter        def increment(n):                          # increment            self.n = n + 1              # setting text to the label            label.setText(str(self.n))    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QCommandLinkButton
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 ?
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