code-rag-bench/online-tutorials huggingface dataset:
StringBuffer setCharAt() method in Java with Examples

04 Dec, 2018
The setCharAt() method of StringBuffer class sets the character at the position index to character which is the value passed as parameter to method. This method returns a new sequence which is identical to old sequence only difference is a new character ch is present at position index in new sequence. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBuffer object.
Syntax:
public void setCharAt(int index, char ch)
Parameters: This method takes two parameters:
index: Integer type value which refers to the index of character to be set.
ch: Character type value which refers to the new char.
Returns: This method returns nothing.
Exception: This method throws IndexOutOfBoundException if the index is negative or greater than length().
Below programs demonstrate the setCharAt() method of StringBuffer Class
Example 1:
// Java program to demonstrate// the setCharAt() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuffer object        // with a String pass as parameter        StringBuffer str            = new StringBuffer("Geeks For Geeks");          // print string        System.out.println("String = "                           + str.toString());          // set char at index 4 to '0'        str.setCharAt(7, '0');          // print string        System.out.println("After setCharAt() String = "                           + str.toString());    }}
String = Geeks For Geeks
After setCharAt() String = Geeks F0r Geeks

Example 2: To demonstrate IndexOutOfBoundsException.
// Java program to demonstrate// Exception thrown by the setCharAt() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuffer object        // with a String pass as parameter        StringBuffer str            = new StringBuffer("Geeks for Geeks");          try {              // pass index -1            str.setCharAt(-1, 'T');        }          catch (Exception e) {            System.out.println("Exception:" + e);        }    }}
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1

References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#setCharAt(int, char)
java-basics
Java-Functions
Java-lang package
java-StringBuffer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get table names using SELECT statement in MySQL?

To get table names using SELECT statement, use “information_schema.tables”. Let us see an example, wherein we have a database that contains 3 tables. The syntax to get all table names with the help of SELECT statement.
SELECT Table_name as TablesName from information_schema.tables where table_schema = 'yourDatabaseName';

Using database “test”, and applying the above syntax to get the table names using SELECT
mysql> use test;
Database changed
mysql> SELECT Table_name as TablesName from information_schema.tables where table_schema = 'test';
Output with the name of the three tables.
+--------------------+
| TablesName         |
+--------------------+
| destination        |
| myisamtoinnodbdemo |
| originaltable      |
+--------------------+
3 rows in set (0.00 sec)
Sorting a HashMap according to keys in Java

As we know that Hash map in Java does not maintain insertion order either by key or by order.Also it does not maintain any other order while adding entries to it.
But Java provide another API named as TreeMap which maintain its insertion order sorted according to the natural ordering of its keys.So in order to sort our given Hash map according to keys we would insert our map into a tree map which by default insert according to key sorting.After insertion we would transverse same tree map which is sorted and is our resultant sorted map.
 Live Demo
import java.util.HashMap;
import java.util.TreeMap;
public class HashMapSortByKey {
   public static void main(String[] args) {
      HashMap<String,Integer> hMap = new HashMap<>();
      TreeMap<String,Integer> sortedMap = new TreeMap<>();
      hMap.put("Akshay",5);
      hMap.put("Veer",8);
      hMap.put("Guang",3);
      hMap.put("Bakshi",7);
      hMap.put("TomTom",2);
      hMap.put("Chang",10);
      hMap.put("Sandy",1);
      sortedMap = sortByKey(hMap);
      System.out.println(sortedMap);
   }
   public static TreeMap<String,Integer> sortByKey(HashMap<String,Integer> mapToSort) {
      TreeMap<String,Integer> sortedMap = new TreeMap<>();
      sortedMap.putAll(mapToSort);
      return sortedMap;
   }
}
myCSV.csv file created with following text
{Akshay=5, Bakshi=7, Chang=10, Guang=3, Sandy=1, TomTom=2, Veer=8}
How to modify column default value in MySQL?

Let us first create a table −
mysql> create table DemoTable
(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(20) DEFAULT 'John'
);
Query OK, 0 rows affected (0.76 sec)
Let us check the description of table −
mysql> desc DemoTable;
This will produce the following output −
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| UserId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserName | varchar(20) | YES  |     | John    |                |
+----------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.17 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 −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 1      | John     |
+--------+----------+
1 row in set (0.00 sec)
Here is the query to modify column default value. We have set the default UserName to Chris −
mysql> alter table DemoTable modify UserName varchar(20) DEFAULT 'Chris';
Query OK, 0 rows affected (0.19 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table using desc command −
mysql> desc DemoTable;
This will produce the following output −
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| UserId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserName | varchar(20) | YES  |     | Chris   |                |
+----------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
Now insert some records in the table using insert command. Since we haven’t added a name, therefore the default “Chris” will get added −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.11 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 −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 1      | John     |
| 2      | Chris    |
+--------+----------+
2 rows in set (0.00 sec)
Find all substrings in a string using C#

Use the substring() method in C# to find all substrings in a string.
Let’s say our string is −
pqr
Loop through the length of the string and use the Substring function from the beginning to the end of the string −
for (int start = 0; start <= str.Length - i; start++) {
   string substr = str.Substring(start, i);
   Console.WriteLine(substr);
}
The following is the C# program to find all substrings in a string −
 Live Demo
using System;

class Demo {
   static void Main() {
      string str = "pqr";

      for (int i = 1; i < str.Length; i++) {
         for (int start = 0; start <= str.Length - i; start++) {
            string substr = str.Substring(start, i);
            Console.WriteLine(substr);
         }
      }
   }
}
p
q
r
pq
qr
JavaMail API - SMTP Servers

SMTP is an acronym for Simple Mail Transfer Protocol. It is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks. SMTP uses TCP port 25. SMTP connections secured by SSL are known by the shorthand SMTPS, though SMTPS is not a protocol in its own right.
JavaMail API has package com.sun.mail.smtp which act as SMTP protocol provider to access an SMTP server. Following table lists the classes included in this package: 
The following table lists the exceptions thrown:
The  com.sun.mail.smtp provider use SMTP Authentication optionally. To use SMTP authentication you'll need to set the mail.smtp.auth property or provide the SMTP Transport with a username and password when connecting to the SMTP server. You can do this using one of the following approaches: 
Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback. mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly. This approach allows you to use the static Transport send method to send messages. For example: 
Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback. mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly. This approach allows you to use the static Transport send method to send messages. For example: 
Transport.send(message);
Call the Transport connect method explicitly with username and password arguments. For example:
Transport tr = session.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges();
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();

Call the Transport connect method explicitly with username and password arguments. For example:

Transport tr = session.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges();
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
 The SMTP protocol provider supports the following properties, which may be set in the JavaMail Session object. The properties are always set as strings. For example:
 props.put("mail.smtp.port", "587");
Here the Type column describes how the string is interpreted.
In general, applications should not need to use the classes in this package directly. Instead, they should use the APIs defined by javax.mail package (and subpackages). Say for example applications should never construct instances of SMTPTransport directly. Instead, they should use the Session method getTransport to acquire an appropriate Transport object. 
Examples to use SMPT server is demonstrated in chapter Sending Emails.
 Print
 Add Notes
 Bookmark this page
Python Pandas - Get the Names of levels in MultiIndex

To get the Names of levels in MultiIndex, use the MultiIndex.names property in Pandas. At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a Multiindex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
Get the names of levels in Multiindex −
print("\nThe names of levels in Multi-index...\n",multiIndex.names)

Following is the code −
import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a Multiindex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# display the Multiindex
print("The Multi-index...\n",multiIndex)

# get the names of levels in Multiindex
print("\nThe names of levels in Multi-index...\n",multiIndex.names)

# get the levels in Multiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
This will produce the following output −
The Multi-index...
MultiIndex([(1, 'John'),
   (2, 'Tim'),
   (3, 'Jacob'),
   (4, 'Chris'),
   (5, 'Keiron')],
   names=['ranks', 'student'])

The names of levels in Multi-index...
['ranks', 'student']

The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
Remove first two characters of all fields in MySQL?

To remove the first two characters of all fields, you need to use SUBSTRING() function from MySQL. The syntax is as follows −
UPDATE yourTableName SET yourColumnName=SUBSTRING(yourColumnName,3)
WHERE yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table RemoveFirstTwoCharacterDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> StringValue varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.04 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('U:100');
Query OK, 1 row affected (0.13 sec)
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('S:20');
Query OK, 1 row affected (0.21 sec)
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('N/A');
Query OK, 1 row affected (0.12 sec)
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('T:8');
Query OK, 1 row affected (0.16 sec)
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('N/A');
Query OK, 1 row affected (0.12 sec)
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('W:99');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from RemoveFirstTwoCharacterDemo;
The following is the output −
+----+-------------+
| Id | StringValue |
+----+-------------+
|  1 | U:100       |
|  2 | S:20        |
|  3 | N/A         |
|  4 | T:8         |
|  5 | N/A         |
|  6 | W:99        |
+----+-------------+
6 rows in set (0.00 sec)
The following is the query to remove the first two characters −
mysql> update RemoveFirstTwoCharacterDemo set StringValue=SUBSTRING(StringValue,3)
   -> where StringValue <> 'N/A';
Query OK, 4 rows affected (0.27 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Check the table records once again using a select statement. The query is as follows −
mysql> select *from RemoveFirstTwoCharacterDemo;
The following is the output −
+----+-------------+
| Id | StringValue |
+----+-------------+
|  1 | 100         |
|  2 | 20          |
|  3 | N/A         |
|  4 | 8           |
|  5 | N/A         |
|  6 | 99          |
+----+-------------+
6 rows in set (0.00 sec)
Queries to check if substring[L...R] is palindrome or not in C++ Program

In this problem, we are given string str, Q number of queries each consisting of two values L and R for substring[L...R]. Our task is to create a program to solve Queries to check if substring[L...R] is palindrome or not.
Problem Description − For solving each query, we need to check whether the substring created within the range L to R is a palindrome or not.
Let’s take an example to understand the problem,
str = “abccbeba” , Q = 3
Query[][] = {{1, 4}, {0, 6}, {4, 6}}
Palindrome
Not Palindrome
Palindrome
Creating all substring for the given
substrings : Substring[1...4] = “bccb”, it is a palindrome
Substring[0...6] = “abccbeb”, it is a not palindrome
Substring[4...6] = “beb”, it is a palindrome
A simple solution to the problem is to solve each query. To solve it, we need to find the substring from index range L to R. And check if the substring is a palindrome or not.
Program to illustrate the working of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int isPallindrome(string str){
   int i, length;
   int flag = 0;
   length = str.length();
   for(i=0;i < length ;i++){
      if(str[i] != str[length-i-1]) {
         flag = 1; break;
      }
   }
   if (flag==1)
      return 1;
      return 0;
   }
   void solveAllQueries(string str, int Q, int query[][2]){
      for(int i = 0; i < Q; i++){ isPallindrome(str.substr(query[i][0] - 1, query[i][1] -       1))?cout<<"Palindrome\n":cout<<"Not palindrome!\n";
   }
}
int main() {
   string str = "abccbeba"; int Q = 3;
   int query[Q][2] = {{1, 3}, {2, 5}, {4, 5}};
   solveAllQueries(str, Q, query);
   return 0;
}
Palindrome
Not palindrome!
Palindrome
This is a naive approach but is not an efficient one.
An efficient solution to the problem is using dynamic programming approach. For solving, we need to create a DP array a 2-D array that stores a boolean value that denotes whether the substring[i...j] is a palindrome for DP[i][j].
We will create this DP matrix and check for all L-R values of each query.
Program to illustrate the working of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void computeDP(int DP[][50], string str){
   int length = str.size();
   int i, j;
   for (i = 0; i < length; i++) {
      for (j = 0; j < length; j++)
      DP[i][j] = 0;
   }
   for (j = 1; j <= length; j++) {
      for (i = 0; i <= length - j; i++) {
         if (j <= 2) {
            if (str[i] == str[i + j - 1])
            DP[i][i + j - 1] = 1;
         }
         else if (str[i] == str[i + j - 1])
         DP[i][i + j - 1] = DP[i + 1][i + j - 2];
      }
   }
}
void solveAllQueries(string str, int Q, int query[][2]){
   int DP[50][50];
   computeDP(DP, str);
   for(int i = 0; i < Q; i++){
      DP[query[i][0] - 1][query[i][1] - 1]?cout<<"not    palindrome!\n":cout<<"palindrome!\n";
   }
}
int main() {
   string str = "abccbeba"; int Q = 3;
   int query[Q][2] = {{1, 3}, {2, 5}, {4, 5}};
   solveAllQueries(str, Q, query);
   return 0;
}
palindrome!
not palindrome!
palindrome!
Is it possible to use variable for collection name using PyMongo?

PyMongo is a Python distribution containing tools for working with MongoDB. Use the following syntax to use a variable for collection name −
var yourVariableName="yourCollectionName";

db[storeCollectionName].yourOperationName;
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows. We have used variable for collection name −
> var storeCollectionName="new_Collection";

> db[storeCollectionName].insertOne({"UserName":"John","UserAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912aea4afe5c1d2279d6a0")
}
> db[storeCollectionName].insertOne({"UserName":"Carol","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912af54afe5c1d2279d6a1")
}
> db[storeCollectionName].insertOne({"UserName":"Mike","UserAge":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912afe4afe5c1d2279d6a2")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db[storeCollectionName].find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c912aea4afe5c1d2279d6a0"),
   "UserName" : "John",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c912af54afe5c1d2279d6a1"),
   "UserName" : "Carol",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c912afe4afe5c1d2279d6a2"),
   "UserName" : "Mike",
   "UserAge" : 27
}
Simulation

A simulation is a computer model that mimics the operation of a real or proposed system and it is time based and takes into account all the resources and constraints involved. 
Cost
Cost
Repeatability
Repeatability
Time
Time
A mobile simulator also known as emulator, a software that can be installed on a normal desktop which creates a virtual machine version of a mobile device such as a mobile phone, iPhone, other smartphone within the system. 
Mobile simulator allows the user to execute the application under test on their computer as if it was the actual mobile device.

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
Pascal - Sets

A set is a collection of elements of same type. Pascal allows defining the set data type. The elements in a set are called its members. In mathematics, sets are represented by enclosing the members within braces{}.  However, in Pascal, set elements are enclosed within square brackets [], which are referred as set constructor.
Pascal Set types are defined as
type
set-identifier = set of base type;
Variables of set type are defined as
var
s1, s2, ...: set-identifier;
or,
s1, s2...: set of base type;
Examples of some valid set type declaration are −
type
Days = (mon, tue, wed, thu, fri, sat, sun);
Letters = set of char;
DaySet = set of days;
Alphabets = set of 'A' .. 'Z';
studentAge = set of 13..20;
You can perform the following set operations on Pascal sets.
Union
This joins two sets and gives a new set with members from both sets.
Difference
Gets the difference of two sets and gives a new set with elements not common to either set.
Intersection
Gets the intersection of two sets and gives a new set with elements common to both sets.
Inclusion
A set P is included in set Q, if all items in P are also in Q but not vice versa.
Symmetric difference
Gets the symmetric difference of two sets and gives a set of elements, which are in either of the sets and not in their intersection.
In
It checks membership.
Following table shows all the set operators supported by Free Pascal. Assume that S1 and S2 are two character sets, such that −
S1 := ['a', 'b', 'c']; 
S2 := ['c', 'd', 'e']; 
S1 + S2 will give a set
['a', 'b', 'c', 'd', 'e']
S1 - S2 will give a set
['a', 'b']
S1 * S2 will give a set
['c']
Include (S1, ['d']) will give a set
['a', 'b', 'c', 'd']
Exclude (S2, ['d']) will give a set
['c', 'e']
The following example illustrates the use of some of these operators −
program setColors;
type  
color = (red, blue, yellow, green, white, black, orange);  
colors = set of color;  
 
procedure displayColors(c : colors);  
const  
names : array [color] of String[7]  
  = ('red', 'blue', 'yellow', 'green', 'white', 'black', 'orange');  
var  
   cl : color;  
   s : String;  

begin  
   s:= ' ';  
   for cl:=red to orange do  
      if cl in c then  
      begin  
         if (s<>' ') then s :=s +' , ';  
         s:=s+names[cl];  
      end;  
   writeln('[',s,']');  
end;  
 
var  
   c : colors;  
 
begin  
   c:= [red, blue, yellow, green, white, black, orange];
   displayColors(c);

   c:=[red, blue]+[yellow, green]; 
   displayColors(c);  

   c:=[red, blue, yellow, green, white, black, orange] - [green, white];     
   displayColors(c);    

   c:= [red, blue, yellow, green, white, black, orange]*[green, white];     
   displayColors(c);  

   c:= [red, blue, yellow, green]><[yellow, green, white, black]; 
   displayColors(c);  
end.
When the above code is compiled and executed, it produces the following result −
[ red , blue , yellow , green , white , black , orange]
[ red , blue , yellow , green]
[ red , blue , yellow , black , orange]
[ green , white]
[ red , blue , white , black]


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
HTML | Marquee scrollamount attribute

14 Jan, 2022
The Marquee scrollamount attribute in HTML is used to set the amount of scrolling at each interval in pixels. The default speed of the marquee value is 6.Syntax:  
<marquee scrollamount=number >
Attribute value:  
Number: Define the speed value.
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML Marquee scrollamount attribute</title>    <style>        .main {            text-align: center;        }                 .marq {            padding-top: 30px;            padding-bottom: 30px;        }    </style></head> <body>    <h1 style="color:green; text-align:center;">      GeeksforGeeks  </h1>    <div class="main">        <marquee class="marq"                 bgcolor="Green"                 direction="left"                 loop="">            scrollamount: default(6)        </marquee>        <marquee class="marq"                 Scrollamount=10                 bgcolor="Green"                 direction="left"                 loop="">            scrollamount: 10        </marquee>    </div></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML Marquee scrollamount attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Modifying tuple contents with list

20 Mar, 2019
In Python, tuples are immutable and hence no changes are required in them once they are formed. This restriction makes their processing harder and hence certain operations on tuples are quite useful to have knowledge of. This article deals with modifying the second tuple element with the list given. Let’s discuss certain ways in which this can be done.
Method #1 : Using zip() + list comprehensionIn this method, we just take the first element of list of tuple and the element at corresponding index and zip them together using the zip function.
# Python3 code to demonstrate# modifying tuple elements# using zip() + list comprehension  # initializing liststest_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]test_list2 = [4, 5, 6]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # using zip() + list comprehension# modifying tuple elementsres = [(i[0], j) for i, j in zip(test_list1, test_list2)]  # print resultprint("The modified resultant list of tuple : " + str(res))
The original list 1 : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2 : [4, 5, 6]
The modified resultant list of tuple : [('Geeks', 4), ('for', 5), ('Geeks', 6)]

 
Method #2 : Using zip() + map() + operator.itemgetter()The itemgetter function here does the task of fetching the constant of two tuple elements which is then mapped with the corresponding index using the map function. The zip function is used to extend this logic to the entire list.
# Python3 code to demonstrate# modifying tuple elements# using zip() + map() + operator.itemgetter()import operator  # initializing liststest_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]test_list2 = [4, 5, 6]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # using zip() + map() + operator.itemgetter()# modifying tuple elementstemp = map(operator.itemgetter(0), test_list1)res = list(zip(temp, test_list2))  # print resultprint("The modified resultant list of tuple : " + str(res))
The original list 1 : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2 : [4, 5, 6]
The modified resultant list of tuple : [('Geeks', 4), ('for', 5), ('Geeks', 6)]

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to log in as a different user on MySQL?

If you want to login as a different user on MySQL, you need to use “mysql -u -p command”. The syntax is as follows to login as a different user.
>mysql -u yourUsername -p After pressing enter key
Enter password −
To understand the above syntax, let us create a user in MySQL. The syntax is as follows −
CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';
Now I am going to create a user with name ‘John’ and password is ‘john123456’. The query is as follows −
mysql> CREATE USER 'John'@'localhost' IDENTIFIED BY 'john123456';
Query OK, 0 rows affected (0.15 sec)
Now check the user has been created in MySQL.user table or not. The query is as follows to list all users from MySQL.user table −
mysql> select user from MySQl.user;
The following is the output −
+------------------+
| user             |
+------------------+
| Manish           |
| User2            |
| mysql.infoschema |
| mysql.session    |
| mysql.sys        |
| root             |
| Adam Smith       |
| John             |
| User1            |
| am               |
+------------------+
10 rows in set (0.00 sec)
Now you need to give all privileges to the user John. The query is as follows:
mysql> GRANT ALL PRIVILEGES ON * . * TO 'John'@'localhost';
Query OK, 0 rows affected (0.19 sec)
Now to login as a different user, first open the command prompt by pressing Windows+R shortcut key and type CMD. Now you need to press OK button. The screenshot is as follows −
After pressing OK button, you will get a command prompt. The screenshot is as follows −
After that reach the location of bin. Follow the below given steps:
Step 1 −
Step 2 −
Now use the above syntax discussed at the beginning. Give the username ‘John’ and password ‘john123456’ which we created above to login. The command is as follows −
After pressing enter key you need to give password. The query is as follows −
How to execute an array of synchronous and asynchronous functions in Node.js?

07 Oct, 2021
We have an array of functions, some functions will be synchronous and some will be asynchronous. We will learn how to execute all of them in sequence.
Input:
listOfFunctions = [
    () => {
        console.log("Synchronous Function);
    },
    async () => new Promise(resolve => {
        setTimeout(() => {
            resolve(true);
            console.log("Asynchronous Function);
        }, 100);
    }),
    .
    .
    .
]
Approach 1: Treat all functions as asynchronous functions and execute them. Because in Javascript, even if you treat a synchronous function as asynchronous function, there is no problem.
Example:
index.js
// this is our list of functionslet listOfFunctions = [  () => {      console.log("Synchronous Function Called");  },  async () => new Promise(resolve => {      setTimeout(() => {          console.log("Asynchronous Function Called");          resolve(true);      }, 100);  })]  // this function will be responsible// for executing all functions of listlet executeListOfFunctions = async(listOfFunctions) => {  for(let func of listOfFunctions){      await func();  }}  // calling main functionexecuteListOfFunctions(listOfFunctions);
Output:
Approach 2: The Idea is same but, Implementation is easy in this approach.
Example:
index.js
// this is our list of functionslet listOfFunctions = [  () => {      console.log("Synchronous Function Called");  },  async () => new Promise(resolve => {      setTimeout(() => {          console.log("Asynchronous Function Called");          resolve(true);      }, 100);  })]  // this function will be responsible// for executing all functions of listlet executeListOfFunctions = async(listOfFunctions) => {  return Promise.all(listOfFunctions.map(func => func()));}  // calling main functionexecuteListOfFunctions(listOfFunctions);
Output:
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Sum of natural numbers using recursion

16 Jun, 2022
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().Examples :  
Input : 3
Output : 6
Explanation : 1 + 2 + 3 = 6

Input : 5
Output : 15
Explanation : 1 + 2 + 3 + 4 + 5 = 15
 
Below is code to find the sum of natural numbers up to n using recursion :  
C++
Java
Python
C#
PHP
Javascript
// C++ program to find the// sum of natural numbers up// to n using recursion#include <iostream>using namespace std; // Returns sum of first// n natural numbersint recurSum(int n){    if (n <= 1)        return n;    return n + recurSum(n - 1);} // Driver codeint main(){    int n = 5;    cout << recurSum(n);    return 0;}
// Java program to find the// sum of natural numbers up// to n using recursionimport java.util.*;import java.lang.*; class GFG{     // Returns sum of first    // n natural numbers    public static int recurSum(int n)    {        if (n <= 1)            return n;        return n + recurSum(n - 1);    }         // Driver code    public static void main(String args[])    {        int n = 5;        System.out.println(recurSum(n));    }} // This code is contributed by Sachin Bisht
# Python code to find sum# of natural numbers upto# n using recursion # Returns sum of first# n natural numbersdef recurSum(n):    if n <= 1:        return n    return n + recurSum(n - 1) # Driver coden = 5print(recurSum(n))
// C# program to find the// sum of natural numbers// up to n using recursionusing System; class GFG{     // Returns sum of first    // n natural numbers    public static int recurSum(int n)    {        if (n <= 1)            return n;        return n + recurSum(n - 1);    }         // Driver code    public static void Main()    {        int n = 5;        Console.WriteLine(recurSum(n));    }} // This code is contributed by vt_m
<?php// PHP program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction recurSum($n){    if ($n <= 1)        return $n;    return $n + recurSum($n - 1);} // Driver code$n = 5;echo(recurSum($n)); // This code is contributed by Ajit.?>
<script> // JavaScript program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction recurSum(n){    if (n <= 1)        return n;    return n + recurSum(n - 1);} // Driver codelet n = 5;document.write(recurSum(n)); // This code is contributed by mohan </script>
Output : 
15 
Time complexity : O(n)
Auxiliary space : O(n)
To solve this question , iterative approach is the best approach because it takes constant or O(1) auxiliary space and the time complexity will be same O(n).
jit_t
pulamolusaimohan
suruchikumarimfp4
Recursion
School Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
Print all subsequences of a string
Recursive Practice Problems with Solutions
Reverse a stack using recursion
Print all possible combinations of r elements in a given array of size n
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
How to Use Gzip and Keep Original File in Linux?

19 Oct, 2021
Gzip is a command-line tool that by default comes with any Linux Operating System. Gzip is commonly used to compress and decompress files. It reduces the size of the file and replaces the original file with the extension .gz file. It can restore the compressed file using the simple command. Now let’s see how to use the Gzip to compress and decompress files on Linux
Keep the original file: As we know the gzip deletes the original file and creates the gzip file. But we can create the gzip file without losing the original file We are going to see three methods of creating the gzip file without losing the original file:
Method 1: using -k option
To keep the original file as it while gzip, the gzip proves the one option -k. Following is the syntax 
gzip -k filename
After the compressing file using this command you can see there are new compressed files created by gzip and your original file is also be present there.
Method 2: Using the -c options
By using the -c option gzip writes output on the standard output without deleting the original file. Here is the syntax for using the -c option
gzip -c filename.extension > filename.extension.gz
Method 3: Using shell redirections
We can also use the shell redirections to keep the file as it is while using gzip. We are going to use the following direction operators 
“>” standard output
“<” standard input
Following is the syntax to use the redirection operator with the gzip:
gzip < filename.extension > myfile.extension.gz
Now let’s see what other things we can do using the gzip:
To replace the target file with compressed file format just simply use the gzip command. Following is the syntax of the command:
gzip filename
Here is one example of the above command:
 To gzip all files in the current folder and subfolders we can use the following command:
 sudo gzip -kr .
To unzip to decompress the gzip file we can use the -d option with gzip. Following is the syntax for decompressing the file:
gzip -d filename.extension.gz
as5853535
anikaseth98
linux-command
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert JSON data into a Python tuple?

You can first convert the json to a dict using json.loads and then convert it to a python tuple using dict.items(). You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −
{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}
You can load it in your python program and loop over its keys in the following way −
import json
f = open('data.json')
data = json.load(f)
f.close()
print(tuple(data.items()))
This will give the output −
(('id', 'file'), ('value', 'File'), ('popup', {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}))
readlink command in Linux with Examples

10 Apr, 2019
readlink command in Linux is used to print resolved symbolic links or canonical file names. In simple words whenever we have a symbolic link and we want to know what path it represents. Then, in that case, the readlink command comes into play to show the actual path of the symbolic link.
Syntax:
readlink [OPTION]... FILE...

Example: It will print the print resolved symbolic links or canonical file names of the symbolic link passed with the command as shown below.
Explanation: As you can see in the above example we have a symbolic link with the name of the desk with the help of readlink command we will be able to identify its actual path.
Options:
readlink -f: This option canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist.Example:readlink -f desk1
Example:
readlink -f desk1
readlink -e: This option will canonicalize by following every symlink in every component of the given name recursively, all components must exist.Example:readlink -e deskExplanation: This option is similar to -f option the only difference between -f and -e option is in -e, all components must exist and in -f, the last component must exist.
Example:
readlink -e desk
Explanation: This option is similar to -f option the only difference between -f and -e option is in -e, all components must exist and in -f, the last component must exist.
readlink -m : This option canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence.Example:readlink -m desk3
Example:
readlink -m desk3
readlink -n : This option will do not output the trailing delimiter.Example :readlink -n desk4
Example :
readlink -n desk4
readlink -q: This option will execute in quiet mode.Example:readlink -q deskExplanation: With the help of this option the user can read the symbolic links in every component and nothing like errors is being displayed on the console.
Example:
readlink -q desk
Explanation: With the help of this option the user can read the symbolic links in every component and nothing like errors is being displayed on the console.
readlink -s : This option will suppress most error messages.Example:readlink -s desk5
Example:
readlink -s desk5
readlink -v : This option will report error messages if any.Example:readlink -v desk6
Example:
readlink -v desk6
readlink -z : This option will end each output line with NUL, not newline.Example:readlink -z desk2
Example:
readlink -z desk2
readlink –help : This option will display this help and exit.readlink --help
readlink --help
readlink –version : This option will show the version information and exit.readlink --version
readlink --version
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.keys()

19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.keys() function returns the ‘info axis’ for the pandas object. If the pandas object is series then it returns index. If the pandas object is dataframe then it returns columns. If the pandas object is panel then it returns major_axis.
Syntax: DataFrame.keys()
For link to the CSV file, click here
Example #1: Use keys() function to find the columns of a dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
# find the keys of the dataframedf.keys()
Output : Example #2: Use keys() function to find the index of the pandas series object.
# importing pandas as pdimport pandas as pd  # Creating the series sr = pd.Series([12, 5, None, 5, None, 11])  # Print the seriessr
# to find the indexsr.keys()
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Python Program for Find the perimeter of a cylinder

06 Feb, 2018
Given diameter and height, find the perimeter of a cylinder.
Perimeter is the length of the outline of a two – dimensional shape. A cylinder is a three – dimensional shape. So, technically we cannot find the perimeter of a cylinder but we can find the perimeter of the cross-section of the cylinder. This can be done by creating the projection on its base, thus, creating the projection on its side, then the shape would be reduced to a rectangle.
Formula :Perimeter of cylinder ( P ) = here d is the diameter of the cylinderh is the height of the cylinder
Examples :
Input : diameter = 5, height = 10 
Output : Perimeter = 30

Input : diameter = 50, height = 150 
Output : Perimeter = 400

# Function to calculate # the perimeter of a cylinderdef perimeter( diameter, height ) :    return 2 * ( diameter + height )   # Driver functiondiameter = 5 ;height = 10 ;print ("Perimeter = ",            perimeter(diameter, height))
Output :
Perimeter = 30 units

Please refer complete article on Find the perimeter of a cylinder for more details!
area-volume-programs
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use PostgreSQL Database in Django?

15 Jul, 2021
This article revolves around how can you change your default Django SQLite-server to postgresSQL. PostgreSQL and SQLite are the most widely used RDBMS relational database management systems. They are both open-source and free. There are  some major differences that you should be consider when you are choosing a database for your applications.
Also checkout – Difference between SQLite and PostgreSQL
First create a virtual env so to do that first install virtualenv using this command
pip install virtualenv
then we will create a virtualenv named gfg using 
virtualenv gfg
to enter in the virtual environment create use 
now we will install Django here so I am using Django 2.2 
pip install django==2.2.*
To get Python working with Postgres, you will need to install the “psycopg2” module.
pip install psycopg2
now lets create a django project named geeks
django-admin startproject geeks
to check your django is running smoothly 
python manage.py runserver
Now, go to the below link and download and set up PostgreSQL. create a database name gfg in your Postgres server. Now its time to switch from SQLite to PostgreSQL.
Folder structure –
open the settings.py file 
now change database settings with this template code
DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.postgresql',
       'NAME': ‘<database_name>’,
       'USER': '<database_username>',
       'PASSWORD': '<password>',
       'HOST': '<database_hostname_or_ip>',
       'PORT': '<database_port>',
   }
}
Run these commands 
python manage.py makemigrations
python manage.py migrate
now lets create the default superuser:
 python manage.py createsuperuser
now again run your server with 
python manage.py runserver
go to this route and add the credential you did while creating superuser
http://127.0.0.1:8000/admin/
and if you are successfully able to log in, you have successfully switched to PostgreSQL
anikakapoor
Python Django
PostgreSQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - SELECT
PostgreSQL - TIME Data Type
Install PostgreSQL on Windows
PostgreSQL - INSERT
PostgreSQL - Removing Temporary Table
Iterate over a list in Python
How to iterate through Excel rows in Python?
Read JSON file using Python
Python map() function
Enumerate() in Python