code-rag-bench/online-tutorials huggingface dataset:
How can we ignore the negative values return by MySQL DATEDIFF() function?

As we know that DATEDIFF() function is used to get the difference in a number of days between two dates. Hence, it is quite possible that it returns negative value as well.
mysql> select * from differ;
+------------+-------------+
| OrderDate  | WorkingDate |
+------------+-------------+
| 2017-10-22 | 2017-10-29  |
| 2017-10-25 | 2017-10-30  |
| 2017-10-25 | 2017-11-30  |
+------------+-------------+
3 rows in set (0.00 sec)
Above query will return the values from table ‘differ’. Now, if someone wants to get the difference between OrderDate and WorkingDate then the output would be negative as follows −
mysql> Select DATEDIFF(OrderDate, WorkingDate)AS 'DIFFERENCE IN DAYS' from differ;
+--------------------+
| DIFFERENCE IN DAYS |
+--------------------+
|                 -7 |
|                 -5 |
|                -36 |
+--------------------+
3 rows in set (0.00 sec)
But we can use MySQL ABS() function to ignore these negative values and it can be done as follows −
mysql> Select ABS(DATEDIFF(OrderDate, WorkingDate))AS 'DIFFERENCE IN DAYS' from differ;
+--------------------+
| DIFFERENCE IN DAYS |
+--------------------+
|                  7 |
|                  5 |
|                 36 |
+--------------------+
3 rows in set (0.00 sec)
Remove Seconds/ Milliseconds from Date and convert to ISO String?

Let’s get the current date first −
var currentDate = new Date();
console.log("The current date is as follows="+currentDate);
Now, let us remove seconds/ milliseconds by setting them to 0 using setSeconds() −
currentDate.setSeconds(0,0);
Convert to ISO String using toISOString() −
currentDate.toISOString()
Let us now see the complete code with output −
var currentDate = new Date();
console.log("The current date is as follows="+currentDate);
currentDate.setSeconds(0,0);
console.log("After removing seconds from date, the new date is as
follows=");
console.log(currentDate.toISOString());
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo143.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo143.js
The current date is as follows=Sat Aug 01 2020 18:20:09 GMT+0530 (India Standard Time)
After removing seconds from date, the new date is as follows=
2020-08-01T12:50:00.000Z
GATE | GATE CS 2019 | Question 53

06 Oct, 2021
Consider the following matrix:The absolute value of the product of Eigenvalues of R is _________ .Note: This was Numerical Type question.(A) 12(B) 145(C) 125(D) 4Answer: (A)Explanation: The determinant of a matrix is equal to the product of eigenvalues. So, the determinant of above matrix will be calculated as follows: 
Apply row operation R2 → R2 – R1 and R3 → R3 – R1 and R4 → R4 – R1 
 
Apply row operation R3 → R3 – 2 * R2 and R4 → R4 – 3 * R2 
 
Apply row operation R4 → R4 – 3 * R3 
 
So, determinant of above matrix is,  
= 6 * (2 * (1*1))
= 12 
So, answer is 12.Quiz of this Question
ab8032496
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dart Programming - Map Property Keys

Returns an iterable object representing keys.
Map.keys

void main() { 
   var details = {'Usrname':'tom','Password':'pass@123'}; 
   print(details.keys); 
}
It will produce the following output −
(Usrname, Password)


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Python Dictionary | setdefault() method

10 Sep, 2020
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary. 
Syntax: dict.setdefault(key, default_value)Parameters: It takes two parameters: key – Key to be searched in the dictionary. default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.Returns: Value of the key if it is in the dictionary. None if key is not in the dictionary and default_value is not specified. default_value if key is not in the dictionary and default_value is specified.
  Example #1:  
Python3
# Python program to show working# of setdefault() method in Dictionary # Dictionary with single itemDictionary1 = { 'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # using setdefault() methodThird_value = Dictionary1.setdefault('C')print("Dictionary:", Dictionary1)print("Third_value:", Third_value)
Output:  
Dictionary: {'A': 'Geeks', 'C': 'Geeks', 'B': 'For'}
Third_value: Geeks

  Example #2: When key is not in the dictionary.  
Python3
# Python program to show working# of setdefault() method in Dictionary # Dictionary with single itemDictionary1 = { 'A': 'Geeks', 'B': 'For'} # using setdefault() method# when key is not in the DictionaryThird_value = Dictionary1.setdefault('C')print("Dictionary:", Dictionary1)print("Third_value:", Third_value) # using setdefault() method# when key is not in the Dictionary# but default value is providedFourth_value = Dictionary1.setdefault('D', 'Geeks')print("Dictionary:", Dictionary1)print("Fourth_value:", Fourth_value)
Output:  
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': None}
Third_value: None
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': None, 'D': 'Geeks'}
Fourth_value: Geeks

 
tarangagarwal
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | DESCRIBE Statement

21 Mar, 2018
Prerequisite : Sql Create Clause,
As the name suggests, DESCRIBE is used to describe something. Since in database we have tables, that’s why we use DESCRIBE or DESC(both are same) command to describe the structure of a table.Syntax:
DESCRIBE one;
  OR
DESC one;

Note : We can use either DESCRIBE or DESC(both are Case Insensitive).
Suppose our table whose name is one has 3 columns named FIRST_NAME, LAST_NAME and SALARY and all are of can contain null values.
Output:
Name          Null       Type
FIRST_NAME              CHAR(25)
LAST_NAME               CHAR(25)
SALARY                  NUMBER(6)

Here, above on using DESC or either DESCRIBE we are able to see the structure of a table but not on the console tab, the structure of table is shown in the describe tab of the Database System Software.
So desc or describe command shows the structure of table which include name of the column, data-type of column and the nullability which means, that column can contain null values or not.
All of these features of table are described at the time of Creation of table.
Example :
Creating table or defining the structure of a table
create table one
(
id int not null, 
name char(25)
)

Here, we created a table whose name is one and its columns are ID, NAME and the id is of not null type i.e, we can’t put null values in the ID column but we can put null values in the NAME column.
Example to demonstrate DESC:
Step 1: Defining structure of table i.e, Creating a table:
create table one
(
 id int not null,
 name char(25),
 city varchar2(25)
)

Step 2: Displaying the structure of table:
DESC one
  OR
DESCRIBE one

Output:
Name      Null       Type
ID       Not Null    INT
NAME                CHAR(25)
CITY                VARCHAR2(25)

Note: Here above ID column is of not null type and rest 2 column can contain null values.
Note: You have to execute DESC command on your system software only, because this command won’t run on any editor. Make sure to run this command on your own installed Database only
References: Oracle.com
This article is contributed by Rajat Rawat 4. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Writing data from a Python List to CSV row-wise

04 May, 2022
Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format.  A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class. 
Python3
# Importing libraryimport csv # data to be written row-wise in csv filedata = [['Geeks'], [4], ['geeks !']] # opening the csv file in 'w+' modefile = open('g4g.csv', 'w+', newline ='') # writing the data into the filewith file:       write = csv.writer(file)    write.writerows(data)
Output:  Example 2: Writing data row-wise into an existing CSV file using DictWriter class. 
Python3
# importing libraryimport csv # opening the csv file in 'w' modefile = open('g4g.csv', 'w', newline ='') with file:    # identifying header     header = ['Organization', 'Established', 'CEO']    writer = csv.DictWriter(file, fieldnames = header)         # writing data row-wise into the csv file    writer.writeheader()    writer.writerow({'Organization' : 'Google',                     'Established': '1998',                     'CEO': 'Sundar Pichai'})    writer.writerow({'Organization' : 'Microsoft',                     'Established': '1975',                     'CEO': 'Satya Nadella'})    writer.writerow({'Organization' : 'Nokia',                     'Established': '1865',                     'CEO': 'Rajeev Suri'})
Output:  Example 3: Appending data row-wise into an existing CSV file using writer class. 
Python3
# Importing libraryimport csv # data to be written row-wise in csv filedata = [['Geeks for Geeks', '2008', 'Sandeep Jain'],        ['HackerRank', '2009', 'Vivek Ravisankar']] # opening the csv file in 'a+' modefile = open('g4g.csv', 'a+', newline ='') # writing the data into the filewith file:       write = csv.writer(file)    write.writerows(data)
Output: 
rkbhola5
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the sum of first and last digit for a number using C language

The sum of first and last digit for a number can be calculated if we use the below mentioned algorithm in C programming language.
Refer an algorithm given herewith −
START
Step 1: Declare no, sum variables of type int
Step 2: Read a number at runtime
Step 3: Compute sum=no%10
Step 4: While loop no>9
   No=no/10
Step 5: Compute sum=sum+no;
Step 6: Print sum
STOP
Following is the C program to find the sum of first and last digit for a number −
 Live Demo
#include <stdio.h>
int main(){
   unsigned int no,sum;
   printf("enter any number:");
   scanf("%u",&no);
   sum=no%10;
   while(no>9){
      no=no/10;
   }
   sum=sum+no;
   printf("sum of first and last digit is:%d",sum);
   return 0;
}
You will see the following output −
enter any number:1242353467
sum of first and last digit is:8
Following is a C program to calculate sum all elements in an array −
 Live Demo
#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int array[5]={10,20,30,40,50};
   int i,sum=0,product=1;
   //Reading elements into the array//
   //For loop//
   for(i=0;i<5;i++){
      //Calculating sum and product, printing output//
      sum=sum+array[i];
   }
   //Displaying sum //
   printf("Sum of elements in the array is : %d\n",sum);
}
You will see the following output −
Sum of elements in the array is : 150
Python os.mknod() Method

Python method mknod() creates a filesystem node (file, device special file or named pipe) named filename.
Following is the syntax for mknod() method −
os.mknod(filename[, mode=0600[, device=0]])

filename − This is the filesystem node to be created.
filename − This is the filesystem node to be created.
mode − The mode specifies both the permissions to use and the type of node to be created combined (bitwise OR) with one of the values  stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLK, and stat.S_IFIFO. They can be ORed base don requirement.
mode − The mode specifies both the permissions to use and the type of node to be created combined (bitwise OR) with one of the values  stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLK, and stat.S_IFIFO. They can be ORed base don requirement.
device − This is the device special file created and its optional to provide.
device − This is the device special file created and its optional to provide.
This method does not return any value.
The following example shows the usage of mknod() method.
# !/usr/bin/python

import os
import stat

filename = '/tmp/tmpfile'
mode = 0600|stat.S_IRUSR

# filesystem node specified with different modes
os.mknod(filename, mode)
Let us compile and run the above program, this will create a simple file in /tmp directory with a name tmpfile −
-rw-------. 1 root   root         0 Apr 30 02:38 tmpfile


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to share a windows folder using PowerShell?

To share a windows folder using PowerShell, we can use the New-SmbShare command. This command is a part of the module SmbShare.
In this example, we have a folder called “DSC” and we want to share. The below command will simply share folder
New-SmbShare -Path E:\DSC\ -Name "Shared Folder"
Output
Name          ScopeName Path Description
----          --------- ---- -----------
Shared Folder    *      E:\DSC
DSC folder will be shared with a “Shared Folder” name with everyone’s Read Permission by default because we haven’t specified the scope yet.
To assign the Full Access permission to the specific user, we can use the -FullAccess parameter followed by active directory username to provide the full access. For example,
New-SmbShare -Name "Shared Folder" -Path "E:\DSC\" -FullAccess "automationlab\delta","Automationlab\Beta"
Full access will be provided to Delta and Beta users of the domain AutomationLab.
Similarly, for only read-only permission we can use the -Readonly parameter.
For Change and Read permission use -ChangeAccess Parameter.
To provide multiple permissions,
New-SmbShare -Name "Shared Folder" -Path "E:\DSC\" -ChangeAccess "Automationlab\Beta" -FullAccess "AutomationLab\Delta"
The above example will provide Change Access to a Beta AD user and Full Access to a Delta AD user.
To create an encrypted shared folder, you can use -Encrypted parameter. For example,
New-SmbShare-Name"Shared Folder"-Path "E:\DSC\"-EncryptData $true
How to check if a String Contains a Substring in PHP ? - GeeksforGeeks

30 Apr, 2021
A string is a collection of given characters and a substring is a string present in a given string.
In this article, we are going to check if the given string contains a substring by using the PHP strpos() function.
Syntax:
strpos($original_string,$sub_string);
Parameters:
original_string : The input string
sub_string : The substring searched in the original input string.
Return type: Boolean value
True, If substring found
False, If substring not found.
Example:
PHP
<?php//input string$input_string = "sravan kumar author at geeks for geeks ";  //sub string to be checked$sub = "geeks";  // Test if string contains the wordif (strpos($input_string, $sub) !== false){    echo "True";}else{    echo "False";}?>
Output:
True
Example 2:
PHP
<?php//input string$input_string = "sravan kumar author at geeks for geeks ";  //sub string to be checked$sub = "computer";  // Test if string contains the wordif (strpos($input_string, $sub) !== false){    echo "True";}else{    echo "False";}?>
Output:
False
Example 3: The following example also considers space.
PHP
<?php//input string$input_string = "geeks for geeks java python php";  //sub string to be checked$sub = " ";  // Test if string contains the wordif (strpos($input_string, $sub) !== false){    echo "True";}else{    echo "False";}?>
Output:
True
Example 4:
PHP
<?php//input string$input_string = "geeks for geeks java python php";  //sub string to be checked$sub = " dbms";  // Test if string contains the wordif (strpos($input_string, $sub) !== false){    echo "True";}else{    echo "False";}?>
Output:
False
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
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?
How to make a mosaic plot in Matplotlib?

To make a mosaic plot in matplotlib, we can take the following steps.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Install statsmodel package (pip install statsmodels). It is required to create mosaic plots. statsmodels is a Python package that provides a complement to scipy for statistical computations including descriptive statistics and estimation and inference for statistical models.
Install statsmodel package (pip install statsmodels). It is required to create mosaic plots. statsmodels is a Python package that provides a complement to scipy for statistical computations including descriptive statistics and estimation and inference for statistical models.
Make a dictionary for mosaic plot.
Make a dictionary for mosaic plot.
Create a mosaic plot from a contingency table.
Create a mosaic plot from a contingency table.
To display the figure, use Show() method.
To display the figure, use Show() method.
import matplotlib.pyplot as plt
from statsmodels.graphics.mosaicplot import mosaic

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Dictionary for mosaic plot
data = {'John': 7, 'Joe': 10, 'James': 5, 'Kate': 1}

# Create mosaic plot
mosaic(data, title='Basic mosaic plot')

# Display the figure
plt.show()
It will produce the following output −
Beautiful Soup - Parsing only section of a document

There are multiple situations where you want to extract specific types of information (only <a> tags) using Beautifulsoup4. The SoupStrainer class in Beautifulsoup allows you to parse only specific part of an incoming document.
One way is to create a SoupStrainer and pass it on to the Beautifulsoup4 constructor as the parse_only argument.
A SoupStrainer tells BeautifulSoup what parts extract, and the parse tree consists of only these elements. If you narrow down your required information to a specific portion of the HTML, this will speed up your search result.
product = SoupStrainer('div',{'id': 'products_list'})
soup = BeautifulSoup(html,parse_only=product)

Above lines of code will parse only the titles from a product site, which might be inside a tag field.
Similarly, like above we can use other soupStrainer objects, to parse specific information from an HTML tag. Below are some of the examples −
from bs4 import BeautifulSoup, SoupStrainer

#Only "a" tags
only_a_tags = SoupStrainer("a")

#Will parse only the below mentioned "ids".
parse_only = SoupStrainer(id=["first", "third", "my_unique_id"])
soup = BeautifulSoup(my_document, "html.parser", parse_only=parse_only)

#parse only where string length is less than 10
def is_short_string(string):
   return len(string) < 10
   
only_short_strings =SoupStrainer(string=is_short_string)

    38 Lectures 
     3.5 hours 

 Chandramouli Jayendran

    22 Lectures 
     1 hours 

 TELCOMA Global

    6 Lectures 
     1 hours 

 AlexanderSchlee

    6 Lectures 
     1 hours 

 AlexanderSchlee

    6 Lectures 
     1 hours 

 AlexanderSchlee

    22 Lectures 
     4 hours 

 AlexanderSchlee
 Print
 Add Notes
 Bookmark this page
GATE-CS-2003 - GeeksforGeeks

02 Dec, 2021
Let A be a sequence of 8 distinct integers sorted in ascending order. How many distinct pairs of sequences, B and C are there such that (i) each is sorted in ascending order, (ii) B has 5 and C has 3 elements, and (iii) the result of merging B and C gives A? 
256 
56 
30 
2 
Suppose you have selected 3 elements from 8 in 8C3 ways, the remaining elements are treated as another array and merging both the arrays gives the sorted array. Here, you can select either 3 or 5. => 8C3 = 8C5 = 8!/(3!5!) = 7*8 = 56 Ways.  
1) Nobody goes to gathering
2) Wife alone goes
2) Both go
The left sub-tree of a node has a key less than or equal to its parent node's key.
The right sub-tree of a node has a key greater than to its parent node's key.
1. The j + 1-st instruction uses the result of the j-th instruction
    as an operand
2. The execution of a conditional jump instruction
3. The j-th and j + 1-st instructions require the ALU at the same 
   time
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Get Hired With GeeksforGeeks and Win Exciting Rewards!
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
Spring - REST Controller
Check the Dependencies of a Table in SQL Server - GeeksforGeeks

08 Apr, 2022
As a SQL DBA, you might need to find the Dependencies of a Table in SQL Server using SQL Server Management Studio or SQL Query. It will be useful to have information about the dependencies while altering or dropping any table. To find Table Dependencies in SQL Server using SQL Server Management Studio : Step-1 : Expand Database, Expand Tables, Right click on the table name. 
Step-2 : Click on View Dependencies.  
 To find Table Dependencies in SQL Server Using SQL Queries. Approach-1 : Using the SP_DEPENDS stored procedure. It will return all the dependencies on the specified Object, includes Tables, Views, Stored Procedures, Constraints, etc. Query –
Use DatabaseName ;
EXEC sp_depends @objname = N'ObjectName' ;
Example-1 :
Use SQL_DBA ;
EXEC sp_depends @objname = N'[dbo].[tbl_Errors_Stats]' ;
Output :
Approach-2 : Query –
Use DatabaseName ;
SELECT * FROM sys.dm_sql_referencing_entities('ObjectName', 
                      'OBJECT') ;
Example-1 :
use SQL_DBA ;
SELECT * FROM sys.dm_sql_referencing_entities('[dbo].[tbl_Errors_Stats]',
                                   'OBJECT') ;
Output :
Approach-3 : Query –
SELECT ROUTINE_SCHEMA,
      ROUTINE_NAME,  
      ROUTINE_TYPE,
      ROUTINE_DEFINITION  
FROM INFORMATION_SCHEMA.ROUTINES  
WHERE ROUTINE_DEFINITION LIKE '%ObjectName%'
Example-1 :
use SQL_DBA

SELECT ROUTINE_SCHEMA,
ROUTINE_NAME, 
ROUTINE_TYPE
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%tbl_Errors_Stats%'
Output :
Approach-4 : Query –
SELECT *
FROM sys.sql_expression_dependencies A, sys.objects B
WHERE referenced_id = OBJECT_ID(N'ObjectName') AND  
 A.referencing_id = B.object_id  

GO
Example-1 :
use SQL_DBA

SELECT referenced_id, referenced_database_name, referenced_schema_name, name
FROM sys.sql_expression_dependencies A, sys.objects B
WHERE referenced_id = OBJECT_ID(N'tbl_Errors_Stats') AND
A.referencing_id = B.object_id 

GO
Output :
simranarora5sos
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
How to Select Data Between Two Dates and Times in SQL Server?
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Delete Duplicate Rows
C# | How to copy a String into another String - GeeksforGeeks

01 Feb, 2019
String.Copy(String) Method is used to create a new instance of String with the same value as a specified String. In other words, this method is used to copy the data of one string into a new string.The new string contains same data like an original string but represents a different object reference.
Syntax:
public static string Copy (string value);
Parameter: Here value is the string which is to be copied.
Return Value: The return type of this method is System.String. This method returns a new string that contains the data similar to the value.
Exception: This method will give ArgumentNullException if the value is null.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# program to illustrate Copy() Methodusing System;   class GFG {       // Main Method    static public void Main()    {           // string which is to be copied        string strA = "GeeksforGeeks";           // Copy the data of strA string        // into strB string        // using Copy() method        string strB = String.Copy(strA);                  Console.WriteLine("Original String strA: {0}", strA);        Console.WriteLine("Copied String strB: {0}", strB);    }}
Original String strA: GeeksforGeeks
Copied String strB: GeeksforGeeks

Example 2:
// C# program to check reference of stringsusing System;  class GFG {          // Main Method    static public void Main()    {          // string        string strA = "GeeksforGeeks";        string strB = "C# Tutorials";        Console.WriteLine("Original string A: {0}", strA);        Console.WriteLine("Original string B: {0}", strB);        Console.WriteLine();          Console.WriteLine("After copy:");          // copy the data of strA string         // into strB string        // using Copy() method        strB = String.Copy(strA);                  Console.WriteLine("Value of string A: {0}", strA);        Console.WriteLine("Value of string B: {0}", strB);          // Checking the reference of both string        Console.WriteLine("Is reference of strings is equal : {0}",                               Object.ReferenceEquals(strA, strB));    }}
Original string A: GeeksforGeeks
Original string B: C# Tutorials

After copy:
Value of string A: GeeksforGeeks
Value of string B: GeeksforGeeks
Is reference of strings is equal : False

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.string.copy?view=netframework-4.7.2#definition
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Destructors in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Introduction to .NET Framework
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Different ways to sort an array in descending order in C#
Viewing information in M_PASSWORD_POLICY System View in SAP HANA

M_PASSWORD_POLICY System View contains several lines of information about the current password policy.
>Select * from M_PASSWORD_POLICY
Java program to find the GCD or HCF of two numbers

An H.C.F or Highest Common Factor, is the largest common factor of two or more values.
For example factors of 12 and 16 are −
12 → 1, 2, 3, 4, 6, 12
16 → 1, 2, 4, 8, 16
The common factors are 1, 2, 4 and the highest common factor is 4.
Define two variables - A, B
Define two variables - A, B
Set loop from 1 to max of A, B
Set loop from 1 to max of A, B
Check if both are completely divided by same loop number, if yes, store it
Check if both are completely divided by same loop number, if yes, store it
Display the stored number is HCF
Display the stored number is HCF
import java.util.Scanner;
public class GCDOfTwoNumbers {
   public static void main(String args[]){
      int a, b, i, hcf = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number :: ");
      a = sc.nextInt();
      System.out.println("Enter second number :: ");
      b = sc.nextInt();

      for(i = 1; i <= a || i <= b; i++) {
         if( a%i == 0 && b%i == 0 )
         hcf = i;
      }
      System.out.println("HCF of given two numbers is ::"+hcf);
   }
}
Enter first number ::
625
Enter second number ::
125
HCF of given two numbers is ::125
Load JSON String into Pandas DataFrame - GeeksforGeeks

18 Aug, 2020
Let us see how can we use a dataset in JSON format in our Pandas DataFrame. This can be done using the built-in read_json() function. It enables us to read the JSON in a Pandas DataFrame.
Example : Consider the JSON file path_to_json.json :
path_to_json.json
# importing the moduleimport pandas  # reading the filedata = df.read_json("path_to_json.json")  # displaying the DataFrameprint(data)
Output :
Now, the final data frame also depends on the type of the JSON file. So there are mainly 3 types of orientations in JSON : 
Index Oriented
Value-Oriented 
Column Oriented
1. Index Oriented
This is an example of an Index Oriented JSON file. 
# importing the moduleimport pandas  # reading the filedata = df.read_json("sample.json")  # displaying the DataFrameprint(data)
Output :
2. Value-Oriented
This is an example of a Value-Oriented JSON file.
# importing the moduleimport pandas  # reading the filedata = df.read_json("sample.json")  # displaying the DataFrameprint(data)
Output :
3. Column Oriented
This is an example of a Column-oriented JSON file.
# importing the moduleimport pandas  # reading the filedata = df.read_json("sample.json")  # displaying the DataFrameprint(data)
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
Python Program to Check Overlapping Prefix - Suffix in Two Lists - GeeksforGeeks

02 Feb, 2021
Given 2 Strings, our task is to check overlapping of one string’s suffix with prefix of other string. 
Input : test_str1 = "Gfgisbest", test_str2 = "bestforall"
Output : best

Explanation : best overlaps as suffix of first string and prefix of next.

Input : test_str1 = "Gfgisbest", test_str2 = "restforall"
Output : ''

Explanation : No overlapping.
Method : Using loop + slicing + startswith()
In this, we increment the first list and slice till list end and keep comparing with the prefix substring of other string using startswith(). In this, the word that occurs at end of string is compared with once with prefix of 2nd string. 
Python3
# Python3 code to demonstrate working of# Overlapping Prefix - Suffix in Two Lists# Using loop + slicing + startswith()import re  # initializing stringstest_str1 = "Gfgisbest"test_str2 = "bestforall"  # printing original stringsprint("The original string 1 is : " + str(test_str1))print("The original string 2 is : " + str(test_str2))  res = ''for char in range(len(test_str1)):          # using startswith() to get prefix    if test_str2.startswith(test_str1[char:]):        res = test_str1[char:]        break  # printing resultprint("Overlapped String  : " + str(res))
Output:
The original string 1 is : Gfgisbest
The original string 2 is : bestforall
Overlapped String  : best
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Chef - Solo Setup

Chef-Solo is an open source tool that runs locally and allows to provision guest machines using Chef cookbooks without the complication of any Chef client and server configuration. It helps to execute cookbooks on a self-created server.
Before running Chef-Solo on the local machine, one needs to install the following two files on the local machine.
Solo.rb − This file tells Chef about where to find cookbooks, roles, and data bags.
Solo.rb − This file tells Chef about where to find cookbooks, roles, and data bags.
Node.json − This file sets the run list and any node-specific attribute, if required.
Node.json − This file sets the run list and any node-specific attribute, if required.
Following are the steps to configure solo.rb.
Step 1 − Create a solo.rb file inside the chef repo.
current_dir       = File.expand_path(File.dirname(__FILE__)) 
file_cache_path   "#{current_dir}" 
cookbook_path     "#{current_dir}/cookbooks" 
role_path         "#{current_dir}/roles" 
data_bag_path     "#{current_dir}/data_bags" 
Step 2 − Add the file to git repo.
$ git add solo.rb 

Step 3 − Create a node.json file inside the chef repo with the following content.
{ 
   "run_list": [ "recipe[ntp]" ] 
} 
Step 4 − Get the ntp cookbook inside the chef repo using knife.
vipin@laptop:~/chef-repo $ knife cookbook site install ntp 
Installing ntp to /Users/mma/work/chef-repo/cookbooks 
...TRUNCATED OUTPUT... 
Cookbook ntp version 1.3.0 successfully installed 

Step 5 − Add the node.json file to Git.
$ git add node.json 

Step 6 − Commit and push the files to git repo.
vipin@laptop:~/chef-repo $ git commit -m "initial setup for Chef Solo" 
vipin@laptop:~/chef-repo $ git push 
Counting objects: 4, done. 
Delta compression using up to 4 threads. 
...TRUNCATED OUTPUT... 
To git@github.com:mmarschall/chef-repo.git 
b930647..5bcfab6 master -> master 

Step 1 − Login to the node where one wants to provision the Chef-Solo.
Step 2 − Clone the Chef repo on the machine.
$ git clone $URL_PATH 

Step 3 − cd to the chef repo.
$ cd chef-repo 

Finally, run the Chef-Solo to converge the node −
$ sudo chef-solo -c solo.rb -j node.json 
[2017-20-08T22:54:13+01:00] INFO: *** Chef 11.0.0 *** 
[2017-20-08T22:54:13+01:00] INFO: Setting the run_list to 
["recipe[ntp]"] from JSON 
...TRUNCATED OUTPUT... 
[2012-12-08T22:54:16+01:00] INFO: Chef Run complete in 2.388374 
seconds 
[2012-12-08T22:54:16+01:00] INFO: Running report handlers 

solo.rb configures Chef-Solo to look for its cookbooks, roles, and data bags inside the current directory: the Chef repository.
Chef-Solo takes its node configuration from a JSON file. In our example, we called it node.json. If you're going to manage multiple servers, you'll need a separate file for each node. Then, Chef-Solo just executes a Chef run based on the configuration data found in solo.rb and node.json.
 Print
 Add Notes
 Bookmark this page
How to set action command to JButton in Java

With set action command, here we are displaying a message in the console on the click of a button.
Set the button first:
JButton btn = new JButton("Demo Button");
Now, set Action Listener to fire when the button is clicked:
ActionListener actionListener = new ActionListener() {
   public void actionPerformed(ActionEvent event) {
      String str = event.getActionCommand();
      System.out.println("Clicked = " + str);
   }
};
The following is an example to set action command to JButton:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(final String args[]) {
      JButton btn = new JButton("Demo Button");
      ActionListener actionListener = new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            String str = event.getActionCommand();
            System.out.println("Clicked = " + str);
         }
      };
      btn.setActionCommand("FirstButton");
      btn.addActionListener(actionListener);
      JOptionPane.showMessageDialog(null, btn);
   }
}
When you will click the “Demo Button” above, the following text would be visible in EclipseIDE output window:
MySQL Query to remove all characters after last comma in string?

To remove all characters after the last comma in the string, you can use SUBSTRING_INDEX().
If you do not know the location of the last comma, then you need to find the last comma dynamically using LENGTH().
The syntax is as follows −
UPDATE yourTableName
set yourColumnName = SUBSTRING_INDEX(yourColumnName, ',',
LENGTH(yourColumnName) - LENGTH(REPLACE(yourColumnName, ',', '')));
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table RemoveAllCharacters
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FullInfo varchar(200),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.83 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into RemoveAllCharacters(FullInfo) values('John,Smith,23,98,4565886');
Query OK, 1 row affected (0.23 sec)

mysql> insert into RemoveAllCharacters(FullInfo) values('Carol,Taylor,26,91');
Query OK, 1 row affected (0.28 sec)

mysql> insert into RemoveAllCharacters(FullInfo) values('David,Miller,21');
Query OK, 1 row affected (0.11 sec)

mysql> insert into RemoveAllCharacters(FullInfo) values('Robert,Jones,22,97');
Query OK, 1 row affected (0.09 sec)

mysql> insert into RemoveAllCharacters(FullInfo)
values('Sam,Williams,27,88,456788,97877');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from RemoveAllCharacters;
The following is the output −
+----+---------------------------------+
| Id | FullInfo                        |
+----+---------------------------------+
| 1  | John,Smith,23,98,4565886        |
| 2  | Carol,Taylor,26,91              |  
| 3  | David,Miller,21                 |
| 4  | Robert,Jones,22,97              |
| 5  | Sam,Williams,27,88,456788,97877 |
+----+---------------------------------+
5 rows in set (0.00 sec)
The following is the query to remove all characters after last comma in string −
mysql> update RemoveAllCharacters
   -> set FullInfo = SUBSTRING_INDEX(FullInfo, ',', LENGTH(FullInfo) - LENGTH(REPLACE(FullInfo, ',', '')));
Query OK, 5 rows affected (0.28 sec)
Rows matched: 5 Changed: 5 Warnings: 0
Now check all the records of table once again. The query is as follows −
mysql> select *from RemoveAllCharacters;
The following is the output displaying the records without the characters after the last comma:
+----+---------------------------+
| Id | FullInfo                  |
+----+---------------------------+
|  1 | John,Smith,23,98          |
|  2 | Carol,Taylor,26           |
|  3 | David,Miller              |
|  4 | Robert,Jones,22           |
|  5 | Sam,Williams,27,88,456788 |
+----+---------------------------+
5 rows in set (0.00 sec)
Exporting an svg file from a Matplotlib figure

To export an SVG file from a matplotlib figure, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
Create random x and y data points using numpy.
Create random x and y data points using numpy.
Plot x and y data points using plot() method.
Plot x and y data points using plot() method.
Save the .svg format file using savefig() method.
Save the .svg format file using savefig() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.random.rand(10)
y = np.random.rand(10)
ax.plot(x, y, ls='dotted', linewidth=2, color='red')
plt.savefig("myimg.svg")
When we execute this code, it will create an SVG file called "myimg.svg" and save it in the current directory.
React Native - Alert

In this chapter, we will understand how to create custom Alert component.
import React from 'react'
import AlertExample from './alert_example.js'

const App = () => {
   return (
      <AlertExample />
   )
}
export default App
We will create a button for triggering the showAlert function.
import React from 'react'
import { Alert, Text, TouchableOpacity, StyleSheet } from 'react-native'

const AlertExample = () => {
   const showAlert = () =>{
      Alert.alert(
         'You need to...'
      )
   }
   return (
      <TouchableOpacity onPress = {showAlert} style = {styles.button}>
         <Text>Alert</Text>
      </TouchableOpacity>
   )
}
export default AlertExample

const styles = StyleSheet.create ({
   button: {
      backgroundColor: '#4ba37b',
      width: 100,
      borderRadius: 50,
      alignItems: 'center',
      marginTop: 100
   }
})
When you click the button, you will see the following −

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to add rows to a table using JavaScript DOM?

To add rows to a table with JavaScript, use the DOM method insertRow().
You can try to run the following code to learn how to add a row to a table one at a time −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script>
         function rowFunction(x) {
            var a = document.getElementById(x).insertRow(0);
            var b = a.insertCell(0);
            var c = a.insertCell(1);
            b.innerHTML = c.innerHTML = "row";
         }
      </script>
   </head>
   <body>
      <table style="border:2px solid black" id="newtable">
         <tr>
            <td>One</td>
            <td>Two</td>
         </tr>
         <tr>
            <td>Three</td>
            <td>Four</td>
         </tr>
         <tr>
            <td>Five</td>
            <td>Six</td>
         </tr>
      </table>
      <p>
         <input type="button" onclick="rowFunction('newtable')" value="Add a row">
      </p>
   </body>
</html>
Matplotlib.axes.Axes.format_xdata() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.format_xdata() function in axes module of matplotlib library is used to return x formatted as an x-value.
Syntax:
Axes.format_xdata(self, x)

Below examples illustrate the matplotlib.axes.Axes.format_xdata() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook  years = mdates.YearLocator()   months = mdates.MonthLocator()  years_fmt = mdates.DateFormatter('% Y')  with cbook.get_sample_data('goog.npz') as datafile:    data = np.load(datafile)['price_data'].view(np.recarray)      fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data, color ="green")  ax.xaxis.set_major_locator(years)ax.set_ylim((100, 300))  ax.format_xdata = mdates.DateFormatter('% m')ax.grid(True)  fig.suptitle('matplotlib.axes.Axes.format_xdata() function\ Example', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook  years = mdates.YearLocator()   months = mdates.MonthLocator()  years_fmt = mdates.DateFormatter('% Y')  with cbook.get_sample_data('goog.npz') as datafile:    data = np.load(datafile)['price_data']  fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data)  ax.xaxis.set_major_locator(years)ax.xaxis.set_major_formatter(years_fmt)ax.xaxis.set_minor_locator(months)  ax.format_xdata = mdates.DateFormatter('% Y')ax.grid(True)  fig.autofmt_xdate()  fig.suptitle('matplotlib.axes.Axes.format_xdata() function \Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How do we set the input type for an Android EditText programmatically using Kotlin?

This example demonstrates how to set the input type for an Android EditText programmatically using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/editText"
      android:layout_centerInParent="true"
      android:onClick="setInputTypeNumber"
      android:text="Click here" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.widget.EditText
class MainActivity : AppCompatActivity() {
   private lateinit var editText: EditText
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      editText= findViewById(R.id.editText)
   }
   fun setInputTypeNumber(view: View) {
      editText.inputType = InputType.TYPE_CLASS_NUMBER
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.