code-rag-bench/online-tutorials huggingface dataset:
How to specify an input field must be filled out before submitting the form in HTML ? - GeeksforGeeks

25 Dec, 2020
In this article, we will specify an input field that must be filled out before submitting the form. The HTML required attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the form. This attribute works with other types of input like radio, checkbox, number, text, etc.
Syntax:
<input required>
Example: This example that illustrates the use of required attribute in input field.
HTML
<!DOCTYPE html><html>  <head>    <title>        How to specify an input field        must be filled out before        submitting the form in HTML?    </title>      <style>        h1 {            color: green;        }          body {            text-align: center;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>        How to specify an input field        must be filled <br>out before        submitting the form in HTML?    </h2>    <form action="">        Username:        <input type="text" name="usrname" required>        <br><br>          Password:        <input type="password"             name="password" required>        <br><br>          <input type="submit">    </form></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
MySQL status in terms of active or total connections?

The active or total connection can be known with the help of threads_connected variable. The variable tells about the number of currently open connections.
The query is as follows −
mysql> show status where `variable_name` = 'Threads_connected';
Here is the output.
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_connected | 1     |
+-------------------+-------+
1 row in set (0.06 sec)

We can check the same with the help of show command. The query is as follows −
mysql> show processlist;
Here is the output.
+----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+
| Id | User            | Host            | db       | Command | Time   | State                  | Info             |
+----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+
|  4 | event_scheduler | localhost       | NULL     | Daemon  | 349012 | Waiting on empty queue | NULL             |
| 11 | root            | localhost:54746 | business | Query   |      1 | starting               | show processlist |
+----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+
2 rows in set (0.31 sec)
Trim (Remove leading and trailing spaces) a string in C#

To trim a string in C#, use regular expression.
Firstly, set the pattern for regex −
string pattern = "\\s+";
Let’s say the following is our string with leading and trailing spaces −
string input = " Welcome User ";
Now using Regex, set the pattern and get the result in a new string in C#.
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
The following is the complete example −
using System;
using System.Text.RegularExpressions;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         string input = " Welcome User ";
         string pattern = "\\s+";
         string replacement = " ";

         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);

         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String:{0}", result);
         Console.ReadKey();
      }
   }
}
Python | Maximum distance between elements - GeeksforGeeks

01 Mar, 2020
Sometimes, while working with lists, we can have a problem in which we need to find maximum distance between reoccurring elements. This kind of problem can have application in competitive programming and web development domain. Let’s discuss certain way in which this task can be performed.
Method : Using loop + max() + defaultdict() + enumerate()The combination of above functions can be used to perform this particular task. In this, we first initialize the temp dict with list using defaultdict(). The iteration is using enumerate() and max() performs the maximum distance between all similar numbers in list.
# Python3 code to demonstrate # Maximum distance between elements# using max() + enumerate() + loop + defaultdict()from collections import defaultdict  # Initializing listtest_list = [4, 5, 6, 4, 6, 3]  # printing original listprint("The original list is : " + str(test_list))  # Maximum distance between elements# using max() + enumerate() + loop + defaultdict()temp = defaultdict(list)for idx, ele in enumerate(test_list):    temp[ele].append(idx)res = max(temp[ele][-1]-temp[ele][0] for ele in temp)  # printing result print ("Maximum distance between same element is : " + str(res))
The original list is : [4, 5, 6, 4, 6, 3]
Maximum distance between same element is : 3

 
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
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
C program to find frequency of each digit in a string

Suppose we have a string s. The s contains letters and digits both. We shall have to find frequencies of each digit and display them. To do this we can make an array of size 10 for each digits (0 through 9), initially all elements are 0 inside the array, then when we encounter a digit simply increase the value of that index and finally print them all.
So, if the input is like s = "we85abc586wow236h69", then the output will be (Number 2, Freq 1) (Number 3, Freq 1) (Number 5, Freq 2) (Number 6, Freq 3) (Number 8, Freq 2) (Number 9, Freq 1)
To solve this, we will follow these steps −
Define an array freq of size: 10 and initialize all elements with 0
Define an array freq of size: 10 and initialize all elements with 0
for initialize i := 0, when i < size of s, update (increase i by 1), do:if s[i] is numeric, then:increase freq[s[i] - ASCII of '0'] by 1
for initialize i := 0, when i < size of s, update (increase i by 1), do:
if s[i] is numeric, then:increase freq[s[i] - ASCII of '0'] by 1
if s[i] is numeric, then:
increase freq[s[i] - ASCII of '0'] by 1
increase freq[s[i] - ASCII of '0'] by 1
for initialize i := 0, when i < 10, update (increase i by 1), do:if freq[i] > 0, then:display (Number i , Freq freq[i])
for initialize i := 0, when i < 10, update (increase i by 1), do:
if freq[i] > 0, then:display (Number i , Freq freq[i])
if freq[i] > 0, then:
display (Number i , Freq freq[i])
display (Number i , Freq freq[i])
Let us see the following implementation to get better understanding −
#include <stdio.h>
#include <string.h>
void solve(char *s){
    int freq[10] = {0};
    for(int i = 0; i < strlen(s); i++){
        if(s[i] >= '0' && s[i] <= '9'){
            freq[s[i] - '0']++ ;    
        }
    }
    for(int i = 0; i<10; i++){
        if(freq[i] > 0)
            printf("(Number %d, Freq %d)\n", i, freq[i]);
    }
}
int main(){
    char *s = "we85abc586wow236h69";
    solve(s);
}

"we85abc586wow236h69"
(Number 2, Freq 1)
(Number 3, Freq 1)
(Number 5, Freq 2)
(Number 6, Freq 3)
(Number 8, Freq 2)
(Number 9, Freq 1)
Powershell - Delete File

Remove-Item cmdlet is used to delete a file by passing the path of the file to be deleted.
In this example, we'll delete a file D:\Temp\Test Folder\Test.txt
Type the following command in PowerShell ISE Console
Remove-Item 'D:\temp\Test Folder\test.txt'
You can see the Test Folder1 in Windows Explorer is deleted now.
In this example, we'll remove the folder D:\Temp\Test Folder recursively deleting its all files. In first example, PowerShell confirms if directory is not empty. In this case, it will simply delete the item.
Type the following command in PowerShell ISE Console
Remove-Item 'D:\temp\Test Folder' -Recurse
You can see the content of temp folder in Windows Explorer where its folder is now removed.

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Check if any alert exists using selenium with python.

We can check if any alert exists with Selenium webdriver. An alert is designed on a webpage to notify users or to perform some actions on the alert. It is designed with the help of Javascript.
An alert can be of three types – prompt, confirmation dialogue box or alert. Selenium has multiple APIs to handle alerts with an Alert interface. To check the presence of an alert we shall use the concept of explicit wait in synchronization.
As we know, explicit wait is developed based on Expected condition for a specific element. For the alerts, we shall verify if alert_is_present exists after a specific wait time. If present, we shall accept it. Entire verification shall be inside a try except block.
Let us see if the above alert is present in the page. WebDriverWait class along with ExpectedCondition is used for an explicit wait condition.
Code Implementation.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
# identify element and click()
l=driver.find_element_by_name("submit")
l.click()
// alert_is_present() expected condition wait for 5 seconds
try:
   WebDriverWait(driver, 5).until (EC.alert_is_present())
   // switch_to.alert for switching to alert and accept
   alert = driver.switch_to.alert
   alert.accept()
   print("alert Exists in page")
except TimeoutException:
   print("alert does not Exist in page")
driver.close()
Python Coding Style Guide

In this tutorial, we are going to learn about the standard style guide that should follow in a Python project. Following a standard style guide of any programming language will keep all team
members at the same pace. Moreover, it looks professional.
For Python, most of the users follow PEP 8 style guide. The code looks pretty and more
readable. You can find the full list of style guide here. We are presenting the curated list of a style guide in this article.
Using a tab for indentation in the code make code more readable instead of using random spaces for multiple functions and methods. You can set the number of spaces for a tab in any code editors' settings.
You can see some examples below.
# example
def sample(random):
   # statement 1
   # statement 2
   # ...
   return random
Using Pythons' default UTF-8 or ASCII encoding is the best practice for international environments.
Using a trailing comma in the tuples is one of the best practices. But, it's not mandatory.
# example
tup = (1, 2, 3,)
Use docstring in the functions and classes. We can use the triple quotes for the docstrings. See some examples below.
def sample():
   """This is a function"""
   """
   This
   is
   a function
   """
class Smaple:
   """This is a class"""
   """
   This
   is
   a class
   """
Writing more than 79 characters in a line is not recommended in PEP 8 style guide. Avoid this by breaking the line into multiple lines using the escape character (). See the example below.
# example
def evaluate(a, b, c, d):
   return (2 ** (a + b) / (c // d) ** d + a - d * b) \ - (3 ** (a + b) / (c // d) ** d + a - d * b)
It's one of the best practices to use a space before and after an operator. Use a space after the comma as well for more readability.
# example
import random
result = random.randint(1, 3) + random.randint(1, 2)
Follow the same case for variables, constants, classes and functions across the program. Most of the Python users will use snake_case for functions and variables naming and PascalCase for classes naming. For constants, use all uppercase letter separated with underscores (ex:- PI_TWO).
snake_case => this_is_function
PascalCase => ThisIsClass
CONSTANT => THIS_IS_CONSTANT
Don't try to import multiple modules in a single even though it is syntactically correct. See the example below.
# don't
import math, random
# do
import math
import random
Always keep your comments up to date. Don't forget to update the comments while updating
code. It's one of the most important things in coding. And most of the user will forget it. Keep this in mind.
We have some characters that shouldn't be used as variable names lonely. And they are I
(uppercase i), and l (lowercase L) as they look similar to the roman letters.
Using ASCII characters in identifiers is not at all a good practice. Avoid using them.
DateTime.ToShortDateString() Method in C#

The DateTime.ToShortDateString() method in C# is used to convert the value of the current DateTime object to its equivalent short date string representation.
Following is the syntax −
public string ToShortDateString ();
Let us now see an example to implement the DateTime.ToShortDateString() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 08, 11, 9, 10, 45);
      Console.WriteLine("Date = {0}", d);
      string str = d.ToShortDateString();
      Console.WriteLine("Short date string representation = {0}", str);
   }
}
This will produce the following output −
Date = 8/11/2019 9:10:45 AM
Short date string representation = 8/11/2019
Let us now see another example to implement the DateTime.ToShortDateString() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name);
      var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
      string str = d.ToShortDateString();
      Console.WriteLine("Short date string = {0}", pattern.ShortDatePattern);
      Console.WriteLine("Short date string representation = {0}", str);
   }
}
This will produce the following output −
Date = 10/16/2019 8:56:40 AM
Current culture = en-US
Short date string = M/d/yyyy
Short date string representation = 10/16/2019
How can I create a directory if it does not exist using Python?

To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using:
import os
if not os.path.exists('my_folder'):
    os.makedirs('my_folder')
You can also use the python idiom EAFP: Easier to ask for forgiveness than permission. For example,
import os
try:
    os.makedirs('my_folder')
except OSError as e:
    if e.errno != errno.EEXIST:
        raise
MySQL query to update all the values in a column with numeric incremental values like John1, John2, John3, etc.

To update all the values in a column to John1, John2, etc.; you need to set incremental values 1, 2, 3, etc. and concatenate them to the records. Let us first create a table −
mysql> create table DemoTable
(
   StudentId varchar(80)
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command. Here, for our example, we have set similar names −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
|      John |
|      John |
|      John |
|      John |
|      John |
+-----------+
5 rows in set (0.00 sec)
Following is the query to update/concatenate all names with numeric incremental values −
mysql> update DemoTable,(select @row := 0) r set StudentId =concat('John',@row := @row+ 1);
Query OK, 5 rows affected (0.11 sec)
Rows matched: 5 Changed: 5 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
|     John1 |
|     John2 |
|     John3 |
|     John4 |
|     John5 |
+-----------+
5 rows in set (0.00 sec)
Return query based on date in MongoDB?

To return query based on the date in MongoDB, let us take an example.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.returnQueryFromDate.insertOne({"PassengerName":"John","PassengerAge":23,"PassengerArrivalTime":new ISODate("2018-03-10 14:45:56")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a57be9064dcd4a68b70e4")
}
> db.returnQueryFromDate.insertOne({"PassengerName":"Larry","PassengerAge":21,"PassengerArrivalTime":new ISODate("2018-05-19 11:10:23")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e5")
}
> db.returnQueryFromDate.insertOne({"PassengerName":"Mike","PassengerAge":24,"PassengerArrivalTime":new ISODate("2018-08-25 16:40:12")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e6")
}
>db.returnQueryFromDate.insertOne({"PassengerName":"Carol","PassengerAge":26,"PassengerArrivalTime":new ISODate("2019-01-29 09:45:10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e7")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.returnQueryFromDate.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a57be9064dcd4a68b70e4"),
   "PassengerName" : "John",
   "PassengerAge" : 23,
   "PassengerArrivalTime" : ISODate("2018-03-10T14:45:56Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e5"),
   "PassengerName" : "Larry",
   "PassengerAge" : 21,
   "PassengerArrivalTime" : ISODate("2018-05-19T11:10:23Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e6"),
   "PassengerName" : "Mike",
   "PassengerAge" : 24,
   "PassengerArrivalTime" : ISODate("2018-08-25T16:40:12Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e7"),
   "PassengerName" : "Carol",
   "PassengerAge" : 26,
   "PassengerArrivalTime" : ISODate("2019-01-29T09:45:10Z")
}
Here is return query based on date. The records with a date greater than 2018-05-19T11:10:23Z will be displayed −
> db.returnQueryFromDate.find({"PassengerArrivalTime" : { $gte : new ISODate("2018-05-19T11:10:23Z") }}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e5"),
   "PassengerName" : "Larry",
   "PassengerAge" : 21,
   "PassengerArrivalTime" : ISODate("2018-05-19T11:10:23Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e6"),
   "PassengerName" : "Mike",
   "PassengerAge" : 24,
   "PassengerArrivalTime" : ISODate("2018-08-25T16:40:12Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e7"),
   "PassengerName" : "Carol",
   "PassengerAge" : 26,
   "PassengerArrivalTime" : ISODate("2019-01-29T09:45:10Z")
}
Find k-th smallest element in BST (Order Statistics in BST) in C++

Suppose we have a binary search tree and a value K as input, we have to find K-th smallest element in the tree.
So, if the input is like
k = 3, then the output will be 15.
To solve this, we will follow these steps −
Define a function find_kth_smallest(), this will take root, count, k,
Define a function find_kth_smallest(), this will take root, count, k,
if root is NULL, then −return NULL
if root is NULL, then −
return NULL
return NULL
left = find_kth_smallest(left of root, count, k)
left = find_kth_smallest(left of root, count, k)
if left is not NULL, then −return left
if left is not NULL, then −
return left
return left
(increase count by 1)
(increase count by 1)
if count is same as k, then −return root
if count is same as k, then −
return root
return root
return find_kth_smallest(right of root, count, k)
return find_kth_smallest(right of root, count, k)
From the main method, do the following −
From the main method, do the following −
count := 0
count := 0
res = find_kth_smallest(root, count, k)
res = find_kth_smallest(root, count, k)
if res is NULL, then −display not found
if res is NULL, then −
display not found
display not found
Otherwisedisplay val of res
Otherwise
display val of res
display val of res
Let us see the following implementation to get better understanding −
 Live Demo
#include <iostream>
using namespace std;
struct TreeNode {
   int val;
   TreeNode *left, *right;
   TreeNode(int x) {
      val = x;
      left = right = NULL;
   }
};
TreeNode* find_kth_smallest(TreeNode* root, int &count, int k) {
   if (root == NULL)
      return NULL;
   TreeNode* left = find_kth_smallest(root->left, count, k);
   if (left != NULL)
      return left;
   count++;
   if (count == k)
      return root;
   return find_kth_smallest(root->right, count, k);
}
void kth_smallest(TreeNode* root, int k) {
   int count = 0;
   TreeNode* res = find_kth_smallest(root, count, k);
   if (res == NULL)
      cout << "Not found";
   else
      cout << res->val;
}
int main() {
   TreeNode* root = new TreeNode(25);
   root->left = new TreeNode(13);
   root->right = new TreeNode(27);
   root->left->left = new TreeNode(9);
   root->left->right = new TreeNode(17);
   root->left->right->left = new TreeNode(15);
   root->left->right->right = new TreeNode(19);
   int k = 3;
   kth_smallest(root, k);
}
TreeNode* root = new TreeNode(25); root->left = new TreeNode(13);
root->right = new TreeNode(27); root->left->left = new
TreeNode(9); root->left->right = new TreeNode(17); root- >left->right->left = new TreeNode(15); root->left->right->right = new TreeNode(19); k = 3
15
What are public and private variables in Python class?

Python doesn’t restrict us from accessing any variable or calling any member method in a python program.
All python variables and methods are public by default in Python. So when we want to make any variable or method public, we just do nothing. Let us see the example below −
class Mug:
    def __init__(self):
        self.color = None
        self.content = None

    def fill(self, beverage):
        self.content = beverage

    def empty(self):
        self.content = None

brownMug = Mug()
brownMug.color = "brown"
print brownMug.empty()
print brownMug.fill('tea')
print brownMug.color
print brownMug.content
All the variables and the methods in the code are public by default.
When we declare our data member private we mean, that nobody should be able to access it from outside the class. Here Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName> . So to make our member private, let’s have a look at the example below −
class Cup:
    def __init__(self, color):
         self.__content = None  # private variable
    def fill(self, beverage):
        self.__content = beverage
    def empty(self):
        self.__content = None
Our cup now can be only filled and poured out by using fill() and empty() methods. Note, that if you try accessing __content from outside, you’ll get an error. But you can still stumble upon something like this −
redCup = Cup("red")
redCup._Cup__content = "tea"
How do I update NULL values in a field in MySQL?

Let us first create a table −
mysql> create table OrderDemo
   -> (
   -> OrderId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> OrderPrice int,
   -> OrderDatetime datetime
   -> );
Query OK, 0 rows affected (0.66 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(200,'2016-09-12');
Query OK, 1 row affected (0.24 sec)
mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(NULL,'2002-11-18');
Query OK, 1 row affected (0.26 sec)
mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(1000,'2017-12-28');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from OrderDemo;
+---------+------------+---------------------+
| OrderId | OrderPrice | OrderDatetime       |
+---------+------------+---------------------+
|       1 |        200 | 2016-09-12 00:00:00 |
|       2 |       NULL | 2002-11-18 00:00:00 |
|       3 |       1000 | 2017-12-28 00:00:00 |
+---------+------------+---------------------+
3 rows in set (0.00 sec)
Here is the query to add a row in OrderPrice column where OrderPrice is NULL i.e. updating the NULL −
mysql> update OrderDemo set OrderPrice = 6500 where OrderPrice IS NULL;
Query OK, 1 row affected (0.17 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now check the table record once again. The query is as follows −
mysql> select *from OrderDemo;
+---------+------------+---------------------+
| OrderId | OrderPrice | OrderDatetime       |
+---------+------------+---------------------+
|       1 |        200 | 2016-09-12 00:00:00 |
|       2 |       6500 | 2002-11-18 00:00:00 |
|       3 |       1000 | 2017-12-28 00:00:00 |
+---------+------------+---------------------+
3 rows in set (0.00 sec)
The NULL value has been replaced with 6500.
DateTime.Add() Method in C#

The DateTime.Add() method in C# is used to return a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
Following is the syntax −
public DateTime Add (TimeSpan val);
Above, Val is the positive or negative time interval.
Let us now see an example to implement the DateTime.Add() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 3, 7, 8, 0, 15);
      TimeSpan span = new TimeSpan(115, 0, 0, 0);
      DateTime d2 = d1.Add(span);
      System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1);
      System.Console.WriteLine("\nNew DateTime = {0:y} {0:dd}", d2);
   }
}
This will produce the following output −
Initial DateTime = March 2019 07
New DateTime = June 2019 30
Let us now see another example to implement the DateTime.Add() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 9, 7, 8, 0, 15);
      // subtracting days
      TimeSpan span = new TimeSpan(-75, 0, 0, 0);
      DateTime d2 = d1.Add(span);
      System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1);
      System.Console.WriteLine("\nNew DateTime = {0:y} {0:dd}", d2);
   }
}
This will produce the following output −
Initial DateTime = September 2019 07
New DateTime = June 2019 24
Get index of first true value of array in Julia | Array findfirst() Method - GeeksforGeeks

23 Mar, 2020
The findfirst() is an inbuilt function in julia which is used to return the index or key of the first true value in the specified array. Here values of index or key start from 1 i.e, for index of 1st element is 1, index of 2nd element is 2 and so on.
Syntax:findfirst(A)orfindfirst(predicate::Function, A)
Parameters:
A: Specified array
Predicate Function: Determines whether something is true or false based on the specified arguments
Returns: It returns the index or key of the first true value in the specified array.
Example 1:
# Julia program to illustrate # the use of Array findfirst() method   # Finding index of first true value from # the 1D array AA = [false, true, true, false]println(findfirst(A))   # Finding index of first true value from # the 2D array B of size 2 * 2B = [false false; true false]println(findfirst(B))   # Finding index of first true value from # the 3D array C of size 2 * 2*2C = cat([false false; true false],         [false true; true false],        [true false; true true], dims = 3)println(findfirst(C))
Output:
Example 2:
# Julia program to illustrate # the use of Array findfirst() method   # Finding index of first even value from # the 1D array AA = [1, 2, 5, 6]println(findfirst(iseven, A))   # Finding index of first even value from # the 2D array B of size 2 * 2B = [3 5; 6 7]println(findfirst(iseven, B))   # Finding index of first even value from # the 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8],         [9 10; 11 12], dims = 3)println(findfirst(iseven, C))
Output:
Julia Array-functions
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
while loop in Julia
Getting rounded value of a number in Julia - round() Method
Working with Date and Time in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Functions in Julia
Working with DataFrames in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Get array dimensions and size of a dimension in Julia - size() Method
Vectors in Julia
Ignore null values in MongoDB documents

To ignore null values in MongoDB, use "$ne" : null in aggregate(). Let us create a collection with documents −
> db.demo722.insertOne(
...    {
...       id:101,
...       details: [
...          { Name:""},
...          { Name: "David"},
...          {Name:null},
...          {Name:"Carol"}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab07d543417811278f5889")
}
Display all documents from a collection with the help of find() method −
> db.demo722.find();
This will produce the following output −
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : [ { "Name" : "" }, { "Name" : "David" }, { "Name" : null }, { "Name" : "Carol" } ] }
Following is the query to ignore null values in MongoDB using $ne −
> db.demo722.aggregate([
...    {"$unwind": "$details"},
...
...    {"$match": { "details.Name" :{ "$ne" : null } } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "" } }
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "David" } }
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "Carol" } }
Calculate Inverse tangent of a value in R Programming - atan() Function - GeeksforGeeks

01 Jun, 2020
atan() function in R Language is used to calculate the inverse tangent value of the numeric value passed to it as argument.
Syntax: atan(x)
Parameter:x: Numeric value
Example 1:
# R code to calculate inverse tangent of a value  # Assigning values to variablesx1 <- -1x2 <- 0.5  # Using atan() Functionatan(x1)atan(x2)
Output:
[1] -0.7853982
[1] 0.4636476
Example 2:
# R code to calculate inverse tangent of a value  # Assigning values to variables x1 <- 0.224587x2 <- 0.456732  # Using atan() Functionatan(x1)atan(x2)
Output:
[1] 0.2209213
[1] 0.4284381
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Python - Convert List of Lists to Tuple of Tuples - GeeksforGeeks

26 May, 2020
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[‘Best’], [‘Gfg’], [‘Gfg’]]Output : ((‘Best’, ), (‘Gfg’, ), (‘Gfg’, ))
Input : test_list = [[‘Gfg’, ‘is’, ‘Best’]]Output : ((‘Gfg’, ‘is’, ‘Best’), )
Method #1 : Using tuple() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the conversion using tuple() and list comprehension is used to extend logic to all the containers.
# Python3 code to demonstrate working of # Convert List of Lists to Tuple of Tuples# Using tuple + list comprehension  # initializing listtest_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],                            ['Gfg', 'is', 'for', 'Geeks']]  # printing original listprint("The original list is : " + str(test_list))  # Convert List of Lists to Tuple of Tuples# Using tuple + list comprehensionres = tuple(tuple(sub) for sub in test_list)  # printing result print("The converted data : " + str(res)) 
The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’))
 
Method #2 : Using map() + tuple()The combination of above functions can be used to solve this problem. In this, we perform the task performed using list comprehension using map(), to extend the conversion logic to each sublist.
# Python3 code to demonstrate working of # Convert List of Lists to Tuple of Tuples# Using map() + tuple()  # initializing listtest_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],                             ['Gfg', 'is', 'for', 'Geeks']]  # printing original listprint("The original list is : " + str(test_list))  # Convert List of Lists to Tuple of Tuples# Using map() + tuple()res = tuple(map(tuple, test_list))  # printing result print("The converted data : " + str(res)) 
The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’))
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.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python?
How do I create and use a sequence in MySQL?

To create a sequence in MySQL, auto_increment can be used on the column. It starts from the
value 1 and increments by 1 for each record when it is inserted.
First, a table is created with the help of CREATE table. The query for that is as follows −
mysql> CREATE table SequenceDemo
-> (
-> SequenceId int auto_increment,
-> primary key(SequenceId)
-> );
Query OK, 0 rows affected (1.22 sec)
After creating the table, the records can be inserted with the help of the insert command which
is given as follows −
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.19 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.14 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.10 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.09 sec)
After inserting the records, they can be displayed with the help of the select statement which is
given as follows −
mysql> SELECT * from SequenceDemo;

The following is the output obtained −
+------------+
| SequenceId |
+------------+
| 1          |
| 2          |
| 3          |
| 4          |
| 5          |
+------------+
5 rows in set (0.00 sec)
The sequence can be set with the help of the alter command.The syntax for this is given as
follows −
alter table yourTableName auto_increment=Somevalue;

Now, the above syntax is used in the following query to set the sequence value as follows −
mysql> alter table SequenceDemo auto_increment = 500;
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0
After that, the records are inserted from the value 500 in the table. This is given below −
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.15 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.15 sec)

mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.05 sec)
All the records can be displayed with the select statement as follows −
mysql> SELECT * from SequenceDemo;

The output is given below
+------------+
| SequenceId |
+------------+
| 1          |
| 2          |
| 3          |
| 4          |
| 5          |
| 500        |
| 501        |
| 502        |
+------------+
8 rows in set (0.00 sec)
As can be seen from the above output, after 5 records the sequence id starts from 500 and is
incremented by 1.
IDE | GeeksforGeeks | A computer science portal for geeks

Please enter your email address or userHandle.
12345678910111213141516171819202122232425import java.io.*;import java.lang.*;class GFG {        public static int fun(int a[],int n, int l)    {        if(n==l-1)        {            System.out.println(a[n]);        return a[n];        }        else         {            System.out.println(Math.max(a[n], fun(a,n+1,l)));            return a[n];                    }    }    public static void main (String[] args) {        int a[]={7,9,8,2,5,3};        fun(a,0,6);        //code    }}ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Find sum of frequency of given elements in the list in Python

A given list has many repeated items. We are interested in finding out the sum of the frequency of some such items which are repeated in the list. Below are the approaches how we can achieve this.
We have two lists. One has the list of values and other has the values whose frequency needs to be checked from the first list. So we create a for loop to count the number of occurrences of the elements from the second list in the first list and then apply the sum function to get the final sum of frequency.
 Live Demo
chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']

# Apply sum
res = sum(big_list.count(elem) for elem in chk_list)

# Printing output
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)
Running the above code gives us the following result −
Given list to be analysed:
['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
Given list to with values to be analysed:
['Mon', 'Tue']
Sum of the frequency: 5
The Counter function from collections module can get the desired result by applying it to the list whose values have to be analysed while looping through the smaller list which has only the elements whose frequency needs to be established.
 Live Demo
from collections import Counter

chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']

# Apply Counter

res = sum(Counter(big_list)[x] for x in chk_list)

# Printing output
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)
Running the above code gives us the following result −
Given list to be analysed:
['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
Given list to with values to be analysed:
['Mon', 'Tue']
Sum of the frequency: 5
Get the Maximum element of an Object in R Programming - max() Function - GeeksforGeeks

05 Jun, 2020
max() function in R Language is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc..
Syntax: max(object, na.rm)
Parameters:object: Vector, matrix, list, data frame, etc.na.rm: Boolean value to remove NA element.
Example 1:
# R program to illustrate # the use of max() function  # Creating vectorsx1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)x2 <- c(1, 4, 2, 8, NA, 11)  # Finding Maximum elementmax(x1)max(x2, na.rm = FALSE)max(x2, na.rm = TRUE)
Output:
[1] 9
[1] NA
[1] 11

Example 2:
# R program to illustrate # the use of max() function  # Creating a matrixarr = array(2:13, dim = c(2, 3, 2)) print(arr)  # Using max() functionmax(arr)
Output:
,, 1

     [, 1] [, 2] [, 3]
[1, ]    2    4    6
[2, ]    3    5    7,, 2

     [, 1] [, 2] [, 3]
[1, ]    8   10   12
[2, ]    9   11   13

[1] 13

R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Callbacks in C

The callback is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time. We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function.
In C we have to use a function pointer to call the callback function. The following code is showing how the callback function is doing its task.
#include<stdio.h>
void my_function() {
   printf("This is a normal function.");
}
void my_callback_function(void (*ptr)()) {
   printf("This is callback function.\n");
   (*ptr)();   //calling the callback function
}
main() {
   void (*ptr)() = &my_function;
   my_callback_function(ptr);
}
This is callback function.
This is a normal function.
Convert JS array into an object - JavaScript

Suppose, we have an array of objects like this −
const arr = [
   {id: 1, name: "Mohan"},
   {id: 2,name: "Sohan"},
   {id: 3,name: "Rohan"}
];
We are required to write a function that takes one such array and constructs an object from it with the id property as key and name as value
The output for the above array should be −
const output = {1:{name:"Mohan"},2:{name:"Sohan"},3:{name:"Rohan"}}
Following is the code −
const arr = [
   {id: 1, name: "Mohan"},
   {id: 2,name: "Sohan"},
   {id: 3,name: "Rohan"}
];
const arrayToObject = arr => {
   const res = {};
   for(let ind = 0; ind < arr.length; ind++){
      res[ind + 1] = {
         "name": arr[ind].name
      };
   };
   return res;
};
console.log(arrayToObject(arr));
This will produce the following output in console −
{
   '1': { name: 'Mohan' },
   '2': { name: 'Sohan' },
   '3': { name: 'Rohan' }
}
How to pop-up the first element from a Python tuple?

By definition, tuple object is immutable. Hence it is not possible to remove element from it. However, a workaround would be convert tuple to a list, remove desired element from list and convert it back to a tuple.
>>> T1=(1,2,3,4)
>>> L1=list(T1)
>>> L1.pop(0)
1
>>> L1
[2, 3, 4]
>>> T1=tuple(L1)
>>> T1
(2, 3, 4)
PL/SQL - WHILE LOOP Statement

A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true.
WHILE condition LOOP 
   sequence_of_statements 
END LOOP; 

DECLARE 
   a number(2) := 10; 
BEGIN 
   WHILE a < 20 LOOP 
      dbms_output.put_line('value of a: ' || a); 
      a := a + 1; 
   END LOOP; 
END; 
/ 
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10 
value of a: 11 
value of a: 12 
value of a: 13 
value of a: 14 
value of a: 15 
value of a: 16 
value of a: 17 
value of a: 18 
value of a: 19  

PL/SQL procedure successfully completed. 

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: JavaScript function
Tryit Editor v3.7

Tryit: Grey HSL color values
Go - Multidimensional Arrays in Go

Go programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −
var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
var threedim [5][10][4]int

A two-dimensional array is the simplest form of a multidimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x, y], you would write something as follows −
var arrayName [ x ][ y ] variable_type

Where variable_type can be any valid Go data type and arrayName will be a valid Go identifier. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below −
Thus, every element in the array a is identified  by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.
a = [3][4]int{  
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
}
An element in two dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −
int val = a[2][3]

The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array −
package main

import "fmt"

func main() {
   /* an array with 5 rows and 2 columns*/
   var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}
   var i, j int

   /* output each array element's value */
   for  i = 0; i < 5; i++ {
      for j = 0; j < 2; j++ {
         fmt.Printf("a[%d][%d] = %d\n", i,j, a[i][j] )
      }
   }
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page