code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Timestamp.dayofweek - GeeksforGeeks

08 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.dayofweek attribute return the value of day of the week in the given Timestamp object. The days are numbered from 0 to 6 where 0 is Monday and 6 is Sunday.
Syntax : Timestamp.dayofweek
Parameters : None
Return : day of week
Example #1: Use Timestamp.dayofweek attribute to find the day of the week in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(2017, 1, 15, 12)  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.dayofweek attribute to find out the day of the week in the given Timestamp object.
# return day of the weekts.dayofweek
Output :
As we can see in the output, the Timestamp.dayofweek attribute has returned 6 indicating that it is the last day of the week in the given Timestamp object. Example #2: Use Timestamp.dayofweek attribute to find the day of the week in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 10,           day = 21, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.dayofweek attribute to find out the day of the week in the given Timestamp object.
# return day of the weekts.dayofweek
Output :
As we can see in the output, the Timestamp.dayofweek attribute has returned 2 indicating that the given date in the Timestamp object is Wednesday.
Python Pandas-Timestamp
Python-pandas
Python
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
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
C# Enum GetNames Method

The GetNames() returns the array of names of the constants in the Enumeration.
The following is the enum.
enum Stock { Watches, Books, Grocery };
To get the array of names, use the GetNames() and loop through as shown below −
foreach(string s in Enum.GetNames(typeof(Stock))) {
}
Let us see the complete example now.
 Live Demo
using System;
class Demo {
   enum Stock { Watches, Books, Grocery };
   static void Main() {
      Console.WriteLine("The value of first stock category = {0}",Enum.GetName(typeof(Stock), 0));
      Console.WriteLine("The value of second stock category = {0}",Enum.GetName(typeof(Stock), 1));
      Console.WriteLine("The value of third stock category = {0}",Enum.GetName(typeof(Stock), 2));
      Console.WriteLine("All the categories of stocks...");
      foreach(string s in Enum.GetNames(typeof(Stock))) {
         Console.WriteLine(s);
      }
   }
}
The value of first stock category = Watches
The value of second stock category = Books
The value of third stock category = Grocery
All the categories of stocks...
Watches
Books
Grocery
Structs in Arduino program

A struct is simply a collection of different types of variable. Structs in Arduino mimic the structs in C language. So, if you are familiar with C structs, Arduino structs shouldn’t be an issue. The struct declaration syntax is as follows −
Syntax
struct structName{
   item1_type item1_name;
   item2_type item2_name;
   .
   .
   .
   itemN_type itemN_name;
}
An example is given below −
Example
struct student{
   String name;
   int age;
   int roll_no;
}
The elements of a struct are accessed using the . (dot) notation. This notation can be used for both reading the elements of a struct, or changing them.
The following example illustrates this −
struct student{
   String name;
   int age;
   int roll_no;
};

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   student A = {"Yash", 25, 26};
   Serial.println(A.name);
   Serial.println(A.age);
   Serial.println(A.roll_no);

   A.age = 27;
   Serial.println(A.age);
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, we were able to both read the elements and change an element of the struct (age), using the dot notation.
Note that while the declaration of the struct contains a semi-colon between each variable, the creation of the struct contains a comma −
student A = {"Yash", 25, 26};
Once a struct has been created, you can treat it like any other data type. You can even have functions returning the struct.
For example −
student funcA(){
   student A = {"Yash", 25, 26};
   return A;
}
In some literature related to structs, you will come across the → notation. This is used in place of dot notation when you are dealing with a pointer to the struct.
The following example demonstrates that.
struct student{
   String name;
   int age;
   int roll_no;
};

student increaseAge(student *B){
   B→age = B→age + 1;
   return *B;
}

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   student A = {"Yash", 25, 26};
   Serial.println(A.age);
   student *C = &A;

   student D = increaseAge(C);
   Serial.println(A.age);
   Serial.println(D.age);

}
void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is −
As you can see, the struct pointer C was pointing to A. When the age was incremented in the increaseAge function, it reflected in the struct A as well.
ios manipulators fixed() function in C++ - GeeksforGeeks

02 Sep, 2019
The fixed() method of stream manipulators in C++ is used to set the floatfield format flag for the specified str stream. This flag sets the floatfield to fixed. It means that the floating-point values will be written in fixed point notations.
Syntax:
ios_base& fixed (ios_base& str)

Parameters: This method accepts str as a parameter which is the stream for which the format flag is affected.
Return Value: This method returns the stream str with internal format flag set.
Example 1:
// C++ code to demonstrate// the working of fixed() function  #include <iostream>  using namespace std;  int main(){      // Initializing the float values    double x = 1.23;      cout.precision(5);      cout << "without fixed flag: "         << x << endl;      // Using fixed()    cout << "with fixed flag: "         << fixed << x << endl;      return 0;}
without fixed flag: 1.23
with fixed flag: 1.23000

Example 2:
// C++ code to demonstrate// the working of fixed() function  #include <iostream>  using namespace std;  int main(){      // Initializing the float values    double x = 1.0;      cout.precision(5);      cout << "without fixed flag: "         << x << endl;      // Using fixed()    cout << "with fixed flag: "         << fixed << x << endl;      return 0;}
without fixed flag: 1
with fixed flag: 1.00000

Example 3:
// C++ code to demonstrate// the working of fixed() function  #include <iostream>  using namespace std;  int main(){      // Initializing the float values    double x = 1.23e9;      cout.precision(5);      cout << "without fixed flag: "         << x << endl;      // Using fixed()    cout << "with fixed flag: "         << fixed << x << endl;      return 0;}
without fixed flag: 1.23e+09
with fixed flag: 1230000000.00000

Reference: http://www.cplusplus.com/reference/ios/fixed/
cpp-ios
cpp-manipulators
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
VBA - Switch Statement

When a user wants to execute a group of statements depending upon a value of an Expression, then Switch Case is used. Each value is called a Case, and the variable is being switched ON based on each case. Case Else statement is executed if the test expression doesn't match any of the Case specified by the user.
Case Else is an optional statement within Select Case, however, it is a good programming practice to always have a Case Else statement.
Following is the syntax of a Switch statement in VBScript.
Select Case expression
   Case expressionlist1
      statement1
      statement2
      ....
      ....
      statement1n
   Case expressionlist2
      statement1
      statement2
      ....
      ....
   Case expressionlistn
      statement1
      statement2
      ....
      ....   
   Case Else
      elsestatement1
      elsestatement2
      ....
      ....
End Select

For demo purpose, let us find the type of integer with the help of a function.
Private Sub switch_demo_Click()
   Dim MyVar As Integer
   MyVar = 1
  
   Select Case MyVar
      Case 1
         MsgBox "The Number is the Least Composite Number"
      Case 2
         MsgBox "The Number is the only Even Prime Number"
      Case 3
         MsgBox "The Number is the Least Odd Prime Number"
      Case Else
         MsgBox "Unknown Number"
   End Select
End Sub
When the above code is executed, it produces the following result.
The Number is the Least Composite Number 


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to plot two histograms side by side using Matplotlib?

To plot two histograms side by side using 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.
Make two dataframes, df1 and df2, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Make two dataframes, df1 and df2, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
Make a histogram of the DataFrame's, df1 and df2.
Make a histogram of the DataFrame's, df1 and df2.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import pandas as pd

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

df1 = pd.DataFrame(dict(a=[1, 1, 1, 1, 3]))
df2 = pd.DataFrame(dict(b=[1, 1, 2, 1, 3]))

fig, axes = plt.subplots(1, 2)

df1.hist('a', ax=axes[0])
df2.hist('b', ax=axes[1])

plt.show()
SAS : How to Display Current Date? - GeeksforGeeks

30 Jul, 2019
The today() function of SAS programming is basically used to generate current date. The format() function is used to display the format of the date in the specified format.
In DD-MMM-YYYY format:Example:data _null_;    dt=today();    format dt yymmdd10.;    put dt ;run;Output:In DDMMMYYYY format:Example:data _null_;    dt=today();    format dt date9.;    put dt ;run;Output:20JUL2019In MONTH DD, YYYY format:Example:data _null_;    dt=today();    format dt WORDDATE.;    put dt ;run;Output:JULY 20, 2019In WEEKDAY, MONTH DD, YYYY format:Example:data _null_;    dt=today();    format dt date9.;    put dt ;run;Output:Saturday, July 20, 2019
In DD-MMM-YYYY format:Example:data _null_;    dt=today();    format dt yymmdd10.;    put dt ;run;Output:
Example:
data _null_;    dt=today();    format dt yymmdd10.;    put dt ;run;
Output:
In DDMMMYYYY format:Example:data _null_;    dt=today();    format dt date9.;    put dt ;run;Output:20JUL2019
Example:
data _null_;    dt=today();    format dt date9.;    put dt ;run;
Output:
20JUL2019
In MONTH DD, YYYY format:Example:data _null_;    dt=today();    format dt WORDDATE.;    put dt ;run;Output:JULY 20, 2019
Example:
data _null_;    dt=today();    format dt WORDDATE.;    put dt ;run;
Output:
JULY 20, 2019
In WEEKDAY, MONTH DD, YYYY format:Example:data _null_;    dt=today();    format dt date9.;    put dt ;run;Output:Saturday, July 20, 2019
Example:
data _null_;    dt=today();    format dt date9.;    put dt ;run;
Output:
Saturday, July 20, 2019
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Advantages and Disadvantages of OOP
C# | Data Types
Shallow Copy and Deep Copy in C++
Difference between Shallow and Deep copy of a class
Decorators with parameters in Python
Use of FLAG in programming
Kotlin Array
Prolog | An Introduction
Java Swing | JComboBox with examples
Formik for form handling in React.js

Purpose of formic is to remove the complexity of form handling in react and make form submission simpler.
Formic uses yup to validate the form fields which is very simple to use
First install the formic library
npm install –save formic
import React, { Component} from 'react';
import { Formik, FormikProps, Form, Field, ErrorMessage } from 'formik';
export class FormExample extends Component {
   handleSubmit = (values, {
      props = this.props,
      setSubmitting
   }) => {
      setSubmitting(false);
      return;
   }  
   render() {
      return(
         <Formik
            initialValues={{
               first_name: '',
               last_name: ''
            }}
            validate={(values) => {
               let errors = {};  
               if(!values.first_name)
               errors.first_name = "first name Required";
               //check if my values have errors
               return errors;
            }
         }
         onSubmit={this.handleSubmit}
         render={formProps => {
            return(
               <Form>
                  <Field type="text" name="first_name" placeholder="First Name"/>
                  <ErrorMessage name="first_name" />
                  <Field type="text" name="last_name" placeholder="Last Name" />
                  <ErrorMessage name="last_name" />
                  <button type="submit" disabled={formProps.isSubmitting}>
                     Submit Form
                  </button>
               </Form>
            );
         }}
      />);
   }
}
The code is very self explanatory. We have two fields first_name and last_name. we are validating the first_name field and displaying error message if it's empty.
Note the imported components from formic → Formik, FormikProps, Form, Field, ErrorMessage
We can use yup which has good support with formik library
const validationSchema = Yup.object({
   first_name: Yup.string("Enter a First Name")
   .required("First Name is required"),
   last_name: Yup.string("Enter your Last Name")
   .last_name("Enter a valid Last Name")
   .required("Last Name is required")
})
We can validation like above using yup and add the validations Schema on formik component to make it work.
<Formik
   initialValues={values}
validationSchema={validationSchema}
/>
How to close the pop up window in selenium running?

We can close the pop up window with Selenium. The getWindowHandles and getWindowHandle methods are used for the pop up window. To store all the window handles opened in a Set data structure, the getWindowHandles method is used.
To store the window handle of the pop up in focus, the getWindowHandle method is used. To iterate over the window handles, the iterator method is used. By default, the Selenium driver has the control over the parent window.
To switch the focus of the driver to the child pop up window, we can take the help of the switchTo().window method. The window handle id of the pop up is passed as an argument to the method.
We have to incorporate import java.util.Set, import java.util.List, and import java.util.Iterator packages to work with the above methods.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
public class ClosePopup {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      //implicit wait
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.findElement(By.id("login−google−button")).click();
      // store window handles in Set
      Set<String> wnd = driver.getWindowHandles();
      // window handles iteration
      Iterator<String> i = wnd.iterator();
      String prntw = i.next();
      String popwnd = i.next();
      // switching pop up window handle id
      driver.switchTo().window(popwnd);
      System.out.println("Page title of popup: "+ driver.getTitle());
      // closes pop up window
      driver.close();
      // switching parent window handle id
      driver.switchTo().window(prntw);
      System.out.println("Page title of parent window: "+ driver.getTitle());
      driver.quit();
   }
}
HTML | datetime Attribute - GeeksforGeeks

15 Jul, 2021
The HTML datetime Attribute is used to specify the date and time of the inserted and the deleted text. It also represents the date and time of the <time> element. Syntax:  
<element datetime="YYYY-MM-DDThh:mm:ssTZD"> 
Attribute Values: This attribute contains single value YYYY-MM-DDThh:mm:ssTZD which is used to specify the date and time when the text was deleted.
The explanation of datetime components are listed below:
YYYY: It sets the year of datetime object (e.g. 2009).
MM: It sets the month of datetime object (e.g. 05 for March).
DD: It sets the day of the month of datetime object (e.g. 04).
T: It is a required separator.
hh: It sets the hour of datetime object (e.g. 18 for 06.00pm).
mm: It sets the minutes of datetime object (e.g. 34).
ss: It sets the seconds of date
time object (e.g. 40).
ZD: Time Zone Designator (Z denotes Zulu, also known as Greenwich Mean Time)
Applicable: datetime attribute is applicable for:  
HTML | <del> Tag
HTML | <ins> Tag
HTML | <time> Tag
Example: This Example illustrates the use of datetime attribute.  
html
<!DOCTYPE html><html> <head>    <title>        HTML datetime Attribute    </title>     <style>        del {            color: red;        }                 ins {            color: green;        }                 h1 {            color: green;        }                 body {            text-align: center;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>     <h2>        HTML datetime Attribute    </h2>      <p>GeeksforGeeks is a        <del>mathematical</del>         <!-- Assigning id to            'ins' tag -->        <ins id="GFG" datetime="2018-11-21T15:55:03Z">            computer        </ins>         <time datetime="2017-02-14 20:00">            scienceportal        </time>     </p> </body> </html>
Output:  
Supported Browsers: The browsers supported by datetime Attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
HTML | rows Attribute - GeeksforGeeks

06 Dec, 2021
The rows attribute in HTML is used to specify the number of visible text lines for the control i.e the number of rows to display.Note: This attribute is only applicable on <textarea>.Syntax:  
<textarea rows = "value">Text content...</textarea>
Attribute Values: It’s default value is 2. It contains a numeric value which specify the height of the textarea element. 
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML rows Attribute</title>    <style>        h1,        h2 {            text-align: center;        }    </style></head> <body>    <center>        <h1 style="color: green;">            GeeksforGeeks        </h1>         <h2>            HTML rows Attribute        </h2>         <!-- Below Textarea element has rows            attribute assigned to 5 -->        <textarea rows="5" cols="23">            This paragraph has a number of rows equal to 5.        </textarea>    </center></body> </html> 
Output:  
Supported Browsers: The browser supported by rows attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
ManasChhabra2
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
An Insertion Sort time complexity question in C++

Time complexity is the amount of time taken by a set of codes or algorithms to process or run as a function of the amount of input.
For insertion sort, the time complexity is of the order O(n) i.e. big O of n in best case scenario. And in the average or worst case scenario the complexity is of the order O(n2).
The time complexity of form sorting the above array is O(n). Let’s see this algorithm carefully, here all pairs are swapped from their original position i.e. positions of element 1 and element 2 are interchanged, 3 and 4 are interchanged and so on. So, while sorting the algorithm will take only one operation n times to sort this algorithm.
Insertion sort is a sorting algorithm that sorts the data structure by placing the element at its position in a sorted array.
The below code shows the function for insertion sort −
void insertionSort(int arr[], int n) {
   for (int i = 1; i < n; i++){
      int element = arr[i];
      int j = i-1;
      while (j >= 0 && arr[j] > element){
         arr[j+1] = arr[j];
         j = j-1;
      }
      arr[j+1] = element;
   }
}
Flask â Sessions

Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser.
A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY.
Session object is also a dictionary object containing key-value pairs of session variables and associated values.
For example, to set a ‘username’ session variable use the statement −
Session[‘username’] = ’admin’

To release a session variable use pop() method.
session.pop('username', None)

The following code is a simple demonstration of session works in Flask. URL ‘/’ simply prompts user to log in, as session variable ‘username’ is not set.
@app.route('/')
def index():
   if 'username' in session:
      username = session['username']
         return 'Logged in as ' + username + '<br>' + \
         "<b><a href = '/logout'>click here to log out</a></b>"
   return "You are not logged in <br><a href = '/login'></b>" + \
      "click here to log in</b></a>"
As user browses to ‘/login’ the login() view function, because it is called through GET method, opens up a login form.
A Form is posted back to ‘/login’ and now session variable is set. Application is redirected to ‘/’. This time session variable ‘username’ is found.
@app.route('/login', methods = ['GET', 'POST'])
def login():
   if request.method == 'POST':
      session['username'] = request.form['username']
      return redirect(url_for('index'))
   return '''
	
   <form action = "" method = "post">
      <p><input type = text name = username/></p>
      <p<<input type = submit value = Login/></p>
   </form>
	
   '''
The application also contains a logout() view function, which pops out ‘username’ session variable. Hence, ‘/’ URL again shows the opening page.
@app.route('/logout')
def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('index'))
Run the application and visit the homepage. (Ensure to set secret_key of the application)
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'any random string’
The output will be displayed as shown below. Click the link “click here to log in”.
The link will be directed to another screen. Type ‘admin’.
The screen will show you the message, ‘Logged in as admin’.

    22 Lectures 
     6 hours 

 Malhar Lathkar

    21 Lectures 
     1.5 hours 

 Jack Chan

    16 Lectures 
     4 hours 

 Malhar Lathkar

    54 Lectures 
     6 hours 

 Srikanth Guskra

    88 Lectures 
     3.5 hours 

 Jorge Escobar

    80 Lectures 
     12 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python - Combine two dictionary adding values for common keys

When analyzing data with python we come across situations when we have to merge two dictionaries in such a way that we add the values of those elements whose keys have equal values. In this article we will see such two dictionaries getting added.
In this approach we design a for loop to check for the presence of the value of the key in both the dictionaries and then add them. Finally we merge the two dictionaries using the | operator available for the dictionaries.
dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6}
dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4}

# Add with common key
for key in dictB:
   if key in dictA:
      dictB[key] = dictB[key] + dictA[key]
   else:
      pass
res = dictA | dictB
print(res)
Running the above code gives us the following result −
{'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10}

The Counter function from the Collections module can be directly applied to merge the two dictionaries which preserves the keys. And in turn adds the values at the matching keys.
from collections import Counter
dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6}
dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4}

res = Counter(dictA) + Counter(dictB)
print(res)
Running the above code gives us the following result −
Counter({'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10})
MySQL - TRUNCATE TABLE Statement

The TRUNCATE TABLE statement deletes all the records of a specified table. Unlike DROP TABLE statement this statement retains the structure of the table, it just removes all the records from the table.
Following is the basic syntax of the TRUNCATE TABLE statement −
TRUNCATE TABLE table_name

Where, table_name is the name of the table you need to delete all the records from.
Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −
CREATE TABLE MyPlayers(
   ID INT,
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Date_Of_Birth date,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255),
   PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); 
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
Now, if verify the contents of the MyPlayers table, you can observe the created records as −
mysql> select * from MyPlayers;
+----+------------+------------+---------------+----------------+-------------+
| ID | First_Name | Last_Name  | Date_Of_Birth | Place_Of_Birth | Country     |
+----+------------+------------+---------------+----------------+-------------+
| 1  | Shikhar    | Dhawan     | 1981-12-05    | Delhi          | India       |
| 2  | Jonathan   | Trott      | 1981-04-22    | CapeTown       | SouthAfrica |
| 3  | Kumara     | Sangakkara | 1977-10-27    | Matale         | Srilanka    |
| 4  | Virat      | Kohli      | 1988-11-05    | Delhi          | India       |
| 5  | Rohit      | Sharma     | 1987-04-30    | Nagpur         | India       |
| 6  | Ravindra   | Jadeja     | 1988-12-06    | Nagpur         | India       |
| 7  | James      | Anderson   | 1982-06-30    | Burnley        | England     |
+----+------------+------------+---------------+----------------+-------------+
7 rows in set (0.07 sec)
Following query truncates the above created table −
mysql> TRUNCATE TABLE MyPlayers;
Query OK, 0 rows affected (1.96 sec)

If you verify the contents of the table using the SELECT statement you will get an empty set as −
mysql> select * from MyPlayers;
Empty set (0.19 sec)


    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Python - Sort Nested keys by Value - GeeksforGeeks

11 May, 2020
Sometimes, while working with data records, we can have a problem in which we need to perform the sorting of nested keys of dictionary by the value of occurrence. This can have applications in arranging scores, prices etc. Lets discuss a way in which this task can be performed.
Method #1 : Using sorted() + lambda + generator expressionThe combination of above methods can be used to perform this task. In this, we perform the task of sorting using sorted() and lambda and generator expression are used to bind and extracting values of dictionaries.
# Python3 code to demonstrate working of # Sort Nested keys by Value# Using sorted() + generator expression + lamda  # initializing dictionarytest_dict = {'Nikhil' : {'English' : 5, 'Maths' :  2, 'Science' : 14},             'Akash' : {'English' : 15, 'Maths' :  7, 'Science' : 2},             'Akshat' : {'English' : 5, 'Maths' :  50, 'Science' : 20}}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Sort Nested keys by Value# Using sorted() + generator expression + lamdares = {key : dict(sorted(val.items(), key = lambda ele: ele[1]))       for key, val in test_dict.items()}      # printing result print("The sorted dictionary : " + str(res)) 
The original dictionary : {‘Nikhil’: {‘English’: 5, ‘Maths’: 2, ‘Science’: 14}, ‘Akash’: {‘English’: 15, ‘Maths’: 7, ‘Science’: 2}, ‘Akshat’: {‘English’: 5, ‘Maths’: 50, ‘Science’: 20}}The sorted dictionary : {‘Nikhil’: {‘Maths’: 2, ‘English’: 5, ‘Science’: 14}, ‘Akash’: {‘Science’: 2, ‘Maths’: 7, ‘English’: 15}, ‘Akshat’: {‘English’: 5, ‘Science’: 20, ‘Maths’: 50}}
Python dictionary-programs
Python-sort
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
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 program to check whether a number is Prime or not
File isFile() method in Java with Examples - GeeksforGeeks

28 Jan, 2019
The isFile() function is a part of File class in Java. This function determines whether the is a file or Directory denoted by the abstract filename is File or not. The function returns true if the abstract file path is File else returns false.
Function signature:
public boolean isFile()
Syntax:
file.isFile()
Parameters: This method does not accept any parameter.
Return Type The function returns boolean data type representing whether the abstract file path is file or not
Exception: This method throws Security Exception if the write access to the file is denied
Below programs illustrates the use of isFile() function:
Example 1: The file “F:\\program.txt” is a existing file in F: directory.
// Java program to demonstrate// isFile() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          // Get the file        File f = new File("F:\\program.txt");          // Check if the specified file        // is File or not        if (f.isFile())            System.out.println("File");        else            System.out.println("Not a File");    }}
Output:
File
Example 2: The file “F:\\program” is a directory
// Java program to demonstrate// isFile() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          // Get the file        File f = new File("F:\\program");          // Check if the specified file        // is File or not        if (f.isFile())            System.out.println("File");        else            System.out.println("Not a File");    }}
Output:
Not a File
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
java-file-handling
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Modulo or Remainder Operator in Java
Java Program to Convert String to String Array
Java Program to Find Sum of Array Elements
How to Replace a Element in Java ArrayList?
How to Iterate LinkedList in Java?
How to convert Date to String in Java
How to do twos complement on a 16-bit signal using Python?

If you want to get an inversion of only first 16 bits of a number, you can take a xor of that number with 65535(16 1s in binary). Forgetting a 2s complement, just add one to the result. For example,
a = 3 # 11 in binary
b = (a ^ 65535) + 1
print(bin(b))
This will give the output:
0b1111111111111101
Wrapping long Y labels in Matplotlib tight layout using setp

To wrap long Y label in matplotlib tight layput using setp, we can take the following steps−
Create a list of a long strings.
Create a tuple of 3 values.
Create a figure and add a set of subplots.
Limit the Y-axis ticks using ylim() method.
Make a horizontal bar plot, using barh() method.
Use yticks() method to ticks the yticks.
Use setp() method to set a property on an artist object.
Use tight_layout() method to adjust the padding between and around subplots.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
labels = (
   'label1 label1 label1 label1 label1 label1 label 1',
   'label2 label2 label2 label2 label2 label2 label 2',
   'label3 label3 label3 label3 label3 label3 label 3')
values = (10, 15, 12)
fig, ax = plt.subplots()
plt.ylim((0, 20))
for i in np.arange(3):
plt.barh(10 * i, values[i])
plt.yticks(10 * np.arange(3))
plt.setp(ax.set_yticklabels(labels))
plt.show()
How to change date format with DATE_FORMAT() in MySQL?

You can change the MySQL date format with a specific format using DATE_FORMAT(). Following is the syntax −
select date_format(yourColumnName,yourFormatSpecifier) from yourTableName;
Let us first create a table −
mysql> create table DemoTable
   (
   ShippingDate date
   );
Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2016-01-21');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('2018-05-24');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('2019-12-31');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| ShippingDate |
+--------------+
| 2016-01-21   |
| 2018-05-24   |
| 2019-12-31   |
+--------------+
3 rows in set (0.00 sec)
Following is the query to implement DATE_FORMAT() in MySQL query and set date format −
mysql> select date_format(ShippingDate,'%d/%m/%Y') from DemoTable;
This will produce the following output −
+--------------------------------------+
| date_format(ShippingDate,'%d/%m/%Y') |
+--------------------------------------+
| 21/01/2016                           |
| 24/05/2018                           |
| 31/12/2019                           |
+--------------------------------------+
3 rows in set (0.00 sec)
PHP date_timestamp_get() Function

The date_timestamp_get function is an alias of DateTime::getTimestamp(). This function accepts a DateTime object as a parameter and returns Unix timestamp for the given object.
date_timestamp_get(object)

object(Mandatory)
This is a DateTime object for which you need the time stamp for.
PHP date_timestamp_get() function returns an Unix timestamp representing the given date.
This function was first introduced in PHP Version 5.3 and, works with all the later versions.
Following example demonstrates the usage of the date_timestamp_get() function −
<?php
   $date = date_create("25-09-1989, 07:32:41 GMT");
   $timestamp = date_timestamp_get($date);
   print("Timestamp: ".$timestamp);
?>
This will produce following result −
Timestamp: 622711961

Following example retrieves the time stamp of current time −
<?php
   $date = date_create();
   $timestamp = date_timestamp_get($date);
   print("Timestamp: ".$timestamp);
?>
This will produce following result −
Timestamp: 1589179558

Following example creates a date adds an interval to it and retrieves the timestamp of the resultant date −
<?php
   //Creating a DateTime object
   $date = date_create("25-09-1989");
   //Adding interval to the date
   $new_date = date_add($date, new DateInterval('PT10H30S'));     
   $timestamp = date_timestamp_get($new_date);      
   print("Timestamp: $timestamp");
?>
This will produce following result −
Timestamp: 622720830

If you try to get the timestamp of the date before unix epoch date (1 January 1970) the  date_create() function returns a negative value −
<?php
   $date = date_create("1952-04-27");
   $timestamp = date_timestamp_get($date);  
   print($timestamp);   
?>
This produces the following result −
-557971200


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Insert data in a table in MySQL stored procedure?

To insert in a table in stored procedure, the syntax is as follows −
create procedure yourProcedureName(OptionalParameter)
   begin
   insert into yourTableName() values(yourValue1,yourValue2,...N);
end
To understand the above syntax, let us first create a table −
mysql> create table DemoTable1928
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Age int
   );
Query OK, 0 rows affected (0.00 sec)
Here is the query to create a stored procedure −
mysql> delimiter //
mysql> create procedure insert_demo(IN Name varchar(40),IN Age int)
   begin
   insert into DemoTable1928(Name,Age) values(Name,Age);
   end
   //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
Now you can call a stored procedure using CALL command −
mysql> call insert_demo('Chris',24);
Query OK, 1 row affected, 1 warning (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1928;
This will produce the following output −
+----+-------+------+
| Id | Name  |  Age |
+----+-------+------+
|  1 | Chris |   24 |
+----+-------+------+
1 row in set (0.00 sec)
Redis - Keys Expireat Command

Redis Expireat command is used to set the expiry of key in Unix timestamp format. After the expiry time, the key will not be available in Redis.
Integer value 1 or 0
1, if timeout is set for key.
0, if key does not exists or timeout could not set.
Following is the basic syntax of Redis Expireat command.
redis 127.0.0.1:6379> Expireat KEY_NAME TIME_IN_UNIX_TIMESTAMP 

First, create a key in Redis and set some value in it.
redis 127.0.0.1:6379> SET tutorialspoint redis 
OK

Now, set timeout of the previously created key.
redis 127.0.0.1:6379> EXPIREAT tutorialspoint 1293840000 
(integer) 1 
EXISTS tutorialspoint 
(integer) 0


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
MySQL query to copy records from one table to another with different columns

For this you can use INSERT INTO SELECT statement. Let us first create a table −
mysql> create table DemoTable1900
   (
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(20),
   ClientAge int default 29
   ) auto_increment=1000;
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1900(ClientName,ClientAge) values('Chris',45);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1900(ClientName,ClientAge) values('David',29);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1900(ClientName,ClientAge) values('Mike',37);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1900(ClientName) values('Sam');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1900;
This will produce the following output −
+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
|     1000 | Chris      |        45 |
|     1001 | David      |        29 |
|     1002 | Mike       |        37 |
|     1003 | Sam        |        29 |
+----------+------------+-----------+
4 rows in set (0.00 sec)
Here is the query to create second table −
mysql> create table DemoTable1901
   (
   EmployeeId int,
   EmployeeName varchar(20),
   EmployeeAge int
   );
Query OK, 0 rows affected (0.00 sec)
Here is the query to copy records from one table to another with different columns −
mysql> insert into DemoTable1901(EmployeeId,EmployeeName,EmployeeAge)
   select ClientId,ClientName,
   ClientAge from DemoTable1900;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1901;
This will produce the following output −
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|       1000 | Chris        |          45 |
|       1001 | David        |          29 |
|       1002 | Mike         |          37 |
|       1003 | Sam          |          29 |
+------------+--------------+-------------+
4 rows in set (0.00 sec)
How to use the GetUpperBound method of array class in C#?

The GetUpperBound() method of array class in C# gets the upper bound of the specified dimension in the Array.
Firstly, set the array and get the upperbound as shown below −
arr.GetUpperBound(0).ToString()
The following is an example stating the usage of GetUpperBound() method in C#.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Array arr = Array.CreateInstance(typeof(String), 6);
         arr.SetValue("One", 0);
         arr.SetValue("Two", 1);
         arr.SetValue("Three", 3);
         arr.SetValue("Four", 4);
         arr.SetValue("Five", 5);
         Console.WriteLine("Upper Bound: {0}",arr.GetUpperBound(0).ToString());
         Console.ReadLine();
      }
   }
}
Upper Bound: 5
Conversion Operators in C++

In this article we will see what is the conversion operator in C++. C++ supports object oriented design. So we can create classes of some real world objects as concrete types.
Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator. This is created like operator overloading function in class.
In this example we are taking a class for complex numbers. It has two arguments real and imaginary. When we assign the object of this class into some double type data, it will convert into its magnitude using conversion operator.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
class My_Complex {
   private:
      double real, imag;
   public:
      My_Complex(double re = 0.0, double img = 0.0) : real(re), imag(img) //default constructor{}
      double mag() {    //normal function to get magnitude
         return getMagnitude();
      }
      operator double () { //Conversion operator to gen magnitude
         return getMagnitude();
      }
   private:
      double getMagnitude() { //Find magnitude of complex object
         return sqrt(real * real + imag * imag);
      }
};
int main() {
   My_Complex complex(10.0, 6.0);
   cout << "Magnitude using normal function: " << complex.mag() << endl;
   cout << "Magnitude using conversion operator: " << complex << endl;
}
Magnitude using normal function: 11.6619
Magnitude using conversion operator: 11.6619
How to get all the directories and sub directories inside a path in C#?

To get the directories C# provides a method Directory.GetDirectories. The Directory.GetDirectories method returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.
In the below example * is matches Zero or more characters in that position. SearchOption TopDirectoryOnly .Gets only the top directories and SearchOption AllDirectories .Gets all the top directories and sub directories.
Note: The rootPath will be your systems rootPath so create a testfolder and use the rootPath accoridingly.
static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly);

   foreach (string dir in dirs) {
      Console.WriteLine (dir);
   }
   Console.ReadLine ();
}
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2
static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories);

   foreach (string dir in dirs) {
      Console.WriteLine (dir);
   }
   Console.ReadLine ();
}
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMainSubDirectory