code-rag-bench/online-tutorials huggingface dataset:
numpy.swapaxes() function | Python - GeeksforGeeks

22 Apr, 2020
numpy.swapaxes() function interchange two axes of an array.
Syntax : numpy.swapaxes(arr, axis1, axis2)Parameters :arr : [array_like] input array.axis1 : [int] First axis.axis2 : [int] Second axis.Return : [ndarray] In earlier NumPy versions, a view of arr is returned only if the order of the axes is changed, otherwise the input array is returned. For NumPy >= 1.10.0, if arr is an ndarray, then a view of arr is returned; otherwise a new array is created.
Code #1 :
# Python program explaining# numpy.swapaxes() function  # importing numpy as geek import numpy as geek  arr = geek.array([[2, 4, 6]])  gfg = geek.swapaxes(arr, 0, 1)  print (gfg)
Output :
[[2]
 [4]
 [6]]

 Code #2 :
# Python program explaining# numpy.swapaxes() function  # importing numpy as geek import numpy as geek  arr = geek.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])  gfg = geek.swapaxes(arr, 0, 2)  print (gfg)
Output :
[[[0 4]
  [2 6]]
 [[1 5]
  [3 7]]]

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
How to remove line breaks from the string in PHP? - GeeksforGeeks

01 Apr, 2021
The line break can be removed from string by using str_replace() function. The str_replace() function is an inbuilt function in PHP which is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.Syntax:  
str_replace ( $searchVal, $replaceVal, $subjectVal, $count )  
Return Type: This function returns a new string or array based on the $subjectVal parameter with replaced values.Example: After replacing the <br> tag, the new string is taken in the variable text.  
php
<?php // Declare a variable and initialize it// with strings containing <br> tag$text = "Geeks<br>For<br>Geeks"; // Display the stringecho $text;echo "\n"; // Use str_replace() function to// remove <br> tag$text = str_replace("<br>", "", $text); // Display the new stringecho $text; ?>
Geeks
For
Geeks
GeeksForGeeks
 
Using preg_replace() function: The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.Syntax:  
preg_replace( $pattern, $replacement, $subject, $limit, $count )
Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.Example: This example use preg_replace() function to remove line break.  
php
<?php // Declare a variable and initialize it// with strings containing <br> tag$text = "Geeks<br>For<br>Geeks"; // Display the stringecho $text;echo "\n"; // Use preg_replace() function to// remove <br> and \n$text = preg_replace( "/<br>|\n/", "", $text ); // Display the new stringecho $text; ?>
Geeks
For
Geeks
GeeksForGeeks
 
arorakashish0911
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Write a java program to tOGGLE each word in string?

You can change the cases of the letters of a word using toUpperCase() and toLowerCase() methods.
Split each word in the string using the split() method, change the first letter of each word to lower case and remaining letters to upper case.
Live Demo
public class Sample{
   public static void main(String args[]){
      String sample = "Hello How are you";
      String[] words = sample.split(" ");
      String result = "";
      for(String word:words){
         String firstSub = word.substring(0, 1);
         String secondSub = word.substring(1);
         result = result+firstSub.toLowerCase()+secondSub.toUpperCase()+" ";
      }
      System.out.println(result);
   }
}
hELLO hOW aRE yOU
How to connect a variable to the Tkinter Entry widget?

Tkinter Entry widget is an Input widget that supports and accepts single-line user input. It accepts all types of characters in UTF-8 module. In order to get the input from the Entry widget, we have to define a variable (based on Data Types it accepts) that accepts only string characters. Then, by using get() method, we can print the given input from the Entry widget.
# Import the Tkinter Library
from tkinter import *

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry of window
win.geometry("700x250")

# Define a String Variable
var = StringVar()

# Define a function to print the Entry widget Input
def printinput(*args):
   print(var.get())

# Create an Entry widget
entry = Entry(win, width=35, textvariable=var)
entry.pack()

# Trace the Input from Entry widget
var.trace("w", printinput)
win.mainloop()
Running the above code will display a window with an Entry widget.
When we write something in the Entry widget, it will just print out all the characters from the Entry widget on the console.
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World
Hello World!
Explain the removal of useless symbols

All grammars are not always optimized, which means the grammar may consist of some extra symbols (non-terminals) which increase the length of grammar.
So, we have to reduce the grammar by removing such useless symbols.
The properties to reduce grammar are explained below −
Each non-terminal and terminal of G appears in the derivation of some word in L
There should not be any production as X->Y where X and Y are non-terminals.
If epsilon is not in language L then, there need not be in the production X-> ε.
The use of reducing grammar is as follows −
A symbol X is useful if there is a derivation of the form
S=>* aXb =* w
Otherwise, the symbol X is useless. Note that in a derivation, finally, we should get a string of terminals and all these symbols must be reachable from the start symbol S.
Those symbols and productions which are not at all used in the derivation are useless.
Consider the following example for removing symbol
S->aAa|bBb| ε
A->C|a
B->C|b
C->CDE| ε
D->A|B|ab
The useless symbols from the given grammar is E. Because E is not a derivative on the
right hand side (RHS).
After removing the useless symbol, the production is as follows
S->aDa|bDb
D->a|b|ab
How to use Tickers in Golang?

There are often cases where we would want to perform a particular task after a specific interval of time repeatedly. In Golang, we achieve this with the help of tickers.
We can use them with goroutines as well so that we can run these tasks in the background of our application without breaking the flow of the application.
The function that we use in tickers is the NewTicker() function which takes time as an argument and we can supply seconds and even milliseconds in it.
The following example demonstrates how we can use a ticker in Golang. Consider the code shown below.
package main

import (
   "fmt"
   "time"
)

func main() {
   fmt.Println("Starting the ticker")

   ticker := time.NewTicker(1 * time.Second)

   for _ = range ticker.C {
      fmt.Println("Ticking..")
   }
}
If we run the above code with the command go run main.go then we will get the following output.
Starting the ticker
Ticking..
Ticking..
It should be noted that the above program will keep on executing unless we forcefully stop it. We can stop it with CTRL+C.
We can also run the ticker in the background with the help of goroutines. Consider the code shown below.
package main

import (
   "fmt"
   "time"
)

func inBackground() {
   ticker := time.NewTicker(1 * time.Second)

   for _ = range ticker.C {
      fmt.Println("Ticking..")
   }
}

func main() {
   fmt.Println("Starting the ticker")
   go inBackground()
   fmt.Println("After goroutine..")
   select {}
}


If we run the above code with the command go run main.go then we will get the following output.
Starting the ticker
After goroutine..
Ticking..
Ticking..
It should be noted that the above program will keep on executing unless we forcefully stop it. We can stop it with CTRL+C.
Now let's consider a more advanced use-case of the ticker, in which we will make use of a channel and a select statement and the ticker will run for a defined period of time as well.
Consider the code shown below.
package main

import (
   "fmt"
   "time"
)

func main() {
   ticker := time.NewTicker(400 * time.Millisecond)
   done := make(chan bool)
   fmt.Println("Started!")
   go func() {
      for {
         select {
         case <-done:
            return
         case t := <-ticker.C:
            fmt.Println("Tick at", t)
         }
      }
   }()
   time.Sleep(1600 * time.Millisecond)
   ticker.Stop()
   done <- true
   fmt.Println("Stopped!")
}


If we run the above code with the command go run main.go then we will get the following output.
Started!
Tick at 2009-11-10 23:00:00.4 +0000 UTC m=+0.400000001
Tick at 2009-11-10 23:00:00.8 +0000 UTC m=+0.800000001
Tick at 2009-11-10 23:00:01.2 +0000 UTC m=+1.200000001
Tick at 2009-11-10 23:00:01.6 +0000 UTC m=+1.600000001
Stopped!
How to set Echo Char for JPasswordField in Java?

With echo char, you can set a character that would appear whenever a user will type the password in the JPasswordField.
Let us first create a new JPassword field −
JPasswordField passwd = new JPasswordField();
Now, use the setEchoChar() to set the echo char for password field. Here, we have asterisk (*) as the field for password −
passwd.setEchoChar('*');
The following is an example to set echo char for password field −
package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Register!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label2 = new JLabel("Age", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField emailId = new JTextField(20);
      JTextField age = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(age);
      frame.add(passwd);
      frame.setSize(550,250);
      frame.setVisible(true);
   }
}
How to create the ArrayList in C# - GeeksforGeeks

18 Feb, 2019
ArrayList() constructor is used to initialize a new instance of the ArrayList class which will be empty and will have the default initial capacity. ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list.
Syntax:
public ArrayList ();
Important Points:
The number of elements that an ArrayList can hold is known as the Capacity of the ArrayList. If the elements will be added to the ArrayList then capacity will be automatically increased by reallocating the internal array.
Specifying the initial capacity will eliminate the requirement to perform a number of resizing operations while adding elements to the ArrayList if the size of the collection can be estimated.
This constructor is an O(1) operation.
Example 1:
// C# Program to illustrate how// to create a ArrayListusing System;using System.Collections;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // arrlist is the ArrayList object        // ArrayList() is the constructor        // used to initializes a new        // instance of the ArrayList class        ArrayList arrlist = new ArrayList();          // Count property is used to get the        // number of elements in ArrayList        // It will give 0 as no elements        // are present currently        Console.WriteLine(arrlist.Count);    }}
0

Example 2:
// C# Program to illustrate how// to create a ArrayListusing System;using System.Collections;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // arrlist is the ArrayList object        // ArrayList() is the constructor        // used to initializes a new        // instance of the ArrayList class        ArrayList arrlist = new ArrayList();          Console.Write("Before Add Method: ");          // Count property is used to get the        // number of elements in ArrayList        // It will give 0 as no elements        // are present currently        Console.WriteLine(arrlist.Count);          // Adding the elements        // to the ArrayList        arrlist.Add("This");        arrlist.Add("is");        arrlist.Add("C#");        arrlist.Add("ArrayList");          Console.Write("After Add Method: ");          // Count property is used to get the        // number of elements in arrlist        Console.WriteLine(arrlist.Count);    }}
Before Add Method: 0
After Add Method: 4

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.-ctor?view=netframework-4.7.2#System_Collections_ArrayList__ctor
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
What do you mean by timeOut in TestNG?

The timeOut is a helper attribute in TestNG that can put an end to the
execution of a test method if that method takes time beyond the timeOut duration.
A timeOut time is set in milliseconds, after that the test method will be marked
Failed.
@Test
public void ContactVerify(){
   System.out.println("Contact validation is successful”);
}
@Test(timeOut = 1000)
public void LandingPage(){
   System.out.println("Landing page verification is successful”);
}
@Test
public void LoanContact(){
   System.out.println("Loan contact details verification is successful”);
}
After 1000ms, if LandingPage() execution continues , that test method will be
considered as failed. The rest of the test methods will have no impact.
Rectangle Overlap in Python

Suppose there is a rectangle that is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinates of its bottom-left corner, and (x2, y2) is the coordinates of its top-right corner. Now
two rectangles overlap if the area of their intersection is positive. So, we can understand that two rectangles that only touch at the corner or edges do not overlap.
If we have two (axis-aligned) rectangles, we have to check whether they overlap or not.
So, if the input is like R1 = [0,0,2,2], R2 = [1,1,3,3], then the output will be True.
To solve this, we will follow these steps −
if R1[0]>=R2[2] or R1[2]<=R2[0] or R1[3]<=R2[1] or R1[1]>=R2[3], thenreturn False
return False
otherwise,return True
return True
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def isRectangleOverlap(self, R1, R2):
      if (R1[0]>=R2[2]) or (R1[2]<=R2[0]) or (R1[3]<=R2[1]) or
         (R1[1]>=R2[3]):
         return False
      else:
   return True
ob = Solution()
print(ob.isRectangleOverlap([0,0,2,2],[1,1,3,3]))
[0,0,2,2],[1,1,3,3]
True
How to create a text area in JavaFX?

A text area is a multi-line editor where you can enter text. Unlike previous versions, in the latest versions of JavaFX, a TextArea does not allow single lines in it. You can create a text area by instantiating the javafx.scene.control.TextArea class.
The following Example demonstrates the creation of a TextArea.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class TextAreaExample extends Application {
   public void start(Stage stage) {
      //Setting the label
      Label label = new Label("Address");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a pagination
      TextArea area = new TextArea();
      //Setting number of pages
      area.setText("Enter your address here");
      area.setPrefColumnCount(15);
      area.setPrefHeight(120);
      area.setPrefWidth(300);
      //Creating a hbox to hold the pagination
      HBox hbox = new HBox();
      hbox.setSpacing(20);
      hbox.setPadding(new Insets(20, 50, 50, 60));
      hbox.getChildren().addAll(label, area);
      //Setting the stage
      Group root = new Group(hbox);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Text Area");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
How to detect integer overflow in C++?

The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either value-added. So for example,
unsigned int x, y;
unsigned int value = x + y;
bool overflow = value < x; // Alternatively "value < y" should also work
This is because if x and y are both unsigned ints if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values.
Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard.
There are other ways to achieve this but they provide estimates only. You can check them out here − https://stackoverflow.com/a/199455/3719089
GATE | GATE CS 2021 | Set 2 | Question 50 - GeeksforGeeks

23 May, 2021
Suppose the following functional dependencies hold on a relation U with attributes P,Q,R,S, and T:
P → QR
RS → T 
Which of the following functional dependencies can be inferred from the above functional dependencies?(A) PS → T(B) R → T(C) P → R(D) PS → QAnswer: (A) (C) (D)Explanation:
P-> QR
RS-> T
From P->QR we derived P->Q and P->R. After getting R from P we derive PS->T . We directly derive Q from P so PS->Q also holds true. Correct Option A , C, D
Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
IDE | GeeksforGeeks | A computer science portal for geeks

Edit the code and Run to see changes
MySQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.
The following SQL statement creates a database called "testDB":
Tip: Make sure you have admin privilege before creating any database. Once a 
database is created, you can check it in the list of databases with the 
following SQL command: SHOW DATABASES;
Write the correct SQL statement to create a new database called testDB.
;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Populate Inorder Successor for all nodes | Practice | GeeksforGeeks

Given a Binary Tree, write a function to populate next pointer for all nodes. The next pointer for every node should be set to point to inorder successor.
Example 1:
Input:
           10
       /  \
      8    12
     /
    3
  

Output: 3->8 8->10 10->12 12->-1
Explanation: The inorder of the above tree is :
3 8 10 12. So the next pointer of node 3 is 
pointing to 8 , next pointer of 8 is pointing
to 10 and so on.And next pointer of 12 is
pointing to -1 as there is no inorder successor 
of 12.
Example 2:
Input:
           1
      /   \
     2     3
Output: 2->1 1->3 3->-1 
Your Task:
You do not need to read input or print anything. Your task is to complete the function populateNext() that takes the root node of the binary tree as input parameter.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1<=n<=10^5
1<=data of the node<=10^5
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to Export a certificate from a certificate store using PowerShell?

To export or download a certificate from the certificate store using PowerShell, we need to use the command Export-Certificate.
First, you need to get the certificate details from the store. If you know the thumbprint, you can directly get the certificate details using the thumbprint and then use that details to export the certificate.
$cert = (Get-ChildItem  Cert:\LocalMachine\My\43E6035D120EBE9ECE8100E8F38B85A9F)
Export-Certificate -Cert $cert -Type CERT -FilePath C:\Temp\Mycert.cer
In the above example, we are exporting the certificate from the LocalMachine -> Personal Store. You can choose a different path. Here, the certificate would be exported to the C:\temp\MyCert.cer.
 You can use the different types like P7B, SST to export the certificate. Alternatively, you can use the below command.
Get-ChildItem Cert:\LocalMachine\My\43E6035D120EBE9ECE8100E8F38B85A9F1C1140F `
   | Export-Certificate -Type cer -FilePath C:\Temp\newcert.cer -Force
If you don't know the certificate thumbprint then you can use any of the certificate's unique properties like Subject, FriendlyName, etc to retrieve the details.  For example,
Get-ChildItem Cert:\LocalMachine\My\  `
   | where{$_.FriendlyName -eq "mysitecert"}  `
   | Export-Certificate -Type cer -FilePath C:\Temp\newcert.cer -Force
Tryit Editor v3.7

HTML Form elements
Tryit: HTML selected option
Format Year in yy format in Java

To format year in yy format is like displaying year as 01, 02, 03, 04, etc. For example, 18 for 2018.
Use the yy format like this.
SimpleDateFormat("yy");
Let us see an example −
// year in yy format
SimpleDateFormat simpleformat = new SimpleDateFormat("yy");
String strYear = simpleformat.format(new Date());
System.out.println("Current Year = "+strYear);
Above, we have used the SimpleDateFormat class, therefore the following package is imported −
import java.text.SimpleDateFormat;
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss");
      System.out.println("Date and time = "+simpleformat.format(cal.getTime()));
      // displaying date
      simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
      String str = simpleformat.format(new Date());
      System.out.println("Current Date = "+str);
      // year in yy format
      simpleformat = new SimpleDateFormat("yy");
      String strYear = simpleformat.format(new Date());
      System.out.println("Current Year = "+strYear);
   }
}
Date and time = Mon, 26 Nov 2018 11:05:15
Current Date = 26/November/2018
Current Year = 18
How to convert ISO 8601 String to Date/Time object in Android using Kotlin?

This example demonstrates how to convert an ISO 8601 String to Date/Time object in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="50dp"
   android:text="Tutorials Point"
   android:textAlignment="center"
   android:textColor="@android:color/holo_green_dark"
   android:textSize="32sp"
   android:textStyle="bold" />
<TextView
   android:id="@+id/textView"
   android:textAlignment="center"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:textColor="@android:color/holo_red_dark"
   android:textSize="24sp"
   android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
   lateinit var textView: TextView
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      textView = findViewById(R.id.textView)
      val dtStart = "2020-07-05T09:27:37Z"
      val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
      val date: Date = format.parse(dtStart)
      textView.text = "ISO 1801 date/time: $date"
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
How to create a Dictionary in Python - GeeksforGeeks

31 Dec, 2019
Dictionaries are the fundamental data structure in Python and are very important for Python programmers. They are an unordered collection of data values, used to store data values like a map. Dictionaries are mutable, which means they can be changed. They offer a time complexity of O(1) and have been heavily optimized for memory overhead and lookup speed efficiency.
Example 1: The first element of each of the sublists is the key and the second element is the value. We want to store the key-value pair dynamically.
# Python program to demonstrate# dynamic dictionary creation    # Initialize an empty dictionaryD = {}   L = [['a', 1], ['b', 2], ['a', 3], ['c', 4]]  # Loop to add key-value pair# to dictionaryfor i in range(len(L)):    # If the key is already     # present in dictionary    # then append the value     # to the list of values    if L[i][0] in D:        D[L[i][0]].append(L[i][1])          # If the key is not present    # in the dictionary then add    # the key-value pair    else:        D[L[i][0]]= []        D[L[i][0]].append(L[i][1])          print(D) 
Output:
{'a': [1, 3], 'b': [2], 'c': [4]}

Example 2:
# Python program to demonstrate# dynamic dictionary creation    # Key to be addedkey_ref = 'More Nested Things'my_dict = {    'Nested Things': [{'name', 'thing one'}, {'name', 'thing two'}]}  # Value to be addedmy_list_of_things = [{'name', 'thing three'}, {'name', 'thing four'}]  # try-except to take care of errors# while adding key-value pairtry:    my_dict[key_ref].append(my_list_of_things)      except KeyError:    my_dict = {**my_dict, **{key_ref: my_list_of_things}}      print(my_dict)
Output:
{
 'Nested Things': [{'name', 'thing one'}, {'thing two', 'name'}], 
 'More Nested Things': [{'name', 'thing three'}, {'thing four', 'name'}]
}

Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Add hours to current time using Calendar.add() method in Java

Import the following package for Calendar class in Java.
import java.util.Calendar;
Firstly, create a Calendar object and display the current date and time.
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us increment the hours using the calendar.add() method and Calendar.HOUR_OF_DAY constant.
calendar.add(Calendar.HOUR_OF_DAY, +5);
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.println("Current Date = " + calendar.getTime());
      // Incrementing hours by 5
      calendar.add(Calendar.HOUR_OF_DAY, +5);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}
Current Date = Thu Nov 22 16:13:04 UTC 2018
Updated Date = Thu Nov 22 21:13:04 UTC 2018
Python Sequence Types

Some basic sequence type classes in python are, list, tuple, range. There are some additional sequence type objects, these are binary data and text string.
Some common operations for the sequence type object can work on both mutable and immutable sequences. Some of the operations are as follows −
x in seq
True, when x is found in the sequence seq, otherwise False
x not in seq
False, when x is found in the sequence seq, otherwise True
x + y
Concatenate two sequences x and y 
x * n or n * x
Add sequence x with itself n times
seq[i]
ith item of the sequence.
seq[i:j]
Slice sequence from index i to j
seq[i:j:k]
Slice sequence from index i to j with step k
len(seq)
Length or number of elements in the sequence 
min(seq)
Minimum element in the sequence
max(seq)
Maximum element in the sequence
seq.index(x[, i[, j]])
Index of the first occurrence of x (in the index range i and j)
seq.count(x)
Count total number of elements in the sequence
seq.append(x)
Add x at the end of the sequence
seq.clear()
Clear the contents of the sequence
seq.insert(i, x)
Insert x at the position i
seq.pop([i])
Return the item at position i, and also remove it from sequence. Default is last element.
seq.remove(x)
Remove first occurrence of item x
seq.reverse()
Reverse the list
 Live Demo
myList1 = [10, 20, 30, 40, 50]
myList2 = [56, 42, 79, 42, 85, 96, 23]

if 30 in myList1:
   print('30 is present')
    
if 120 not in myList1:
   print('120 is not present')
    
print(myList1 + myList2) #Concatinate lists
print(myList1 * 3) #Add myList1 three times with itself
print(max(myList2))
print(myList2.count(42)) #42 has two times in the list

print(myList2[2:7])
print(myList2[2:7:2])

myList1.append(60)
print(myList1)

myList2.insert(5, 17)
print(myList2)

myList2.pop(3)
print(myList2)
myList1.reverse()
print(myList1)

myList1.clear()
print(myList1)
30 is present
120 is not present
[10, 20, 30, 40, 50, 56, 42, 79, 42, 85, 96, 23]
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
96
2
[79, 42, 85, 96, 23]
[79, 85, 23]
[10, 20, 30, 40, 50, 60]
[56, 42, 79, 42, 85, 17, 96, 23]
[56, 42, 79, 85, 17, 96, 23]
[60, 50, 40, 30, 20, 10]
[]
How to get root directory information in android?

This example demonstrate about How to get root directory information in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show root directory.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.KeyguardManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setText(Environment.getRootDirectory().getAbsolutePath().toString());
   }
   @Override
   protected void onStop() {
      super.onStop();
   }
   @Override
   protected void onResume() {
      super.onResume();
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
numpy.array_str() in Python - GeeksforGeeks

29 Nov, 2018
numpy.array_str()function is used to represent the data of an array as a string.
The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type.
Syntax : numpy.array_str(arr, max_line_width=None, precision=None, suppress_small=None)
Parameters :arr : [array_like] Input array.max_line_width : [int, optional] Inserts newlines if text is longer than max_line_width. The default is, indirectly, 75.precision : [int, optional] Floating point precision. Default is the current printing precision(generally 8).suppress_small : [bool, optional] It represent very small numbers as zero, default is False. Very small number is defined by precision, if the precision is 8 then numbers smaller than 5e-9 are represented as zero.
Return : [str] The string representation of an array.
Code #1 : Working
# Python program explaining# array_str() function  import numpy as geekarr = geek.array([4, -8, 7 ])  print ("Input  array : ", arr)print(type(arr))    out_arr = geek.array_str(arr)print ("The string representation of input array : ", out_arr) print(type(out_arr))
Output :
Input  array :  [ 4 -8  7]
class 'numpy.ndarray'
The string representation of input array :  array([ 4, -8,  7])
class 'str'

 Code #2 : Working
# Python program explaining# array_str() function  import numpy as geekin_arr = geek.array([5e-8, 4e-7, 8, -4])  print ("Input  array : ", in_arr)print(type(in_arr))    out_arr = geek.array_str(in_arr, precision = 6, suppress_small = True)print ("The string representation of input array : ", out_arr) print(type(out_arr))
Output :
Input  array :  [  5.00000000e-08   4.00000000e-07   8.00000000e+00  -4.00000000e+00]
class 'numpy.ndarray'
The string representation of input array :  array([ 0.,  0.,  8., -4.])
class 'str'

 
Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Change figure window title in pylab(Python)

Using pylab.gcf(), we can create a fig variable and can set the fig.canvas.set_window_title('Setting up window title.') window title.
Using gcf() method, get the current figure. If no current figure exists, a new one is created using `~.pyplot.figure()`.
Using gcf() method, get the current figure. If no current figure exists, a new one is created using `~.pyplot.figure()`.
Set the title text of the window containing the figure, using set_window_title() method.. Note that this has no effect if there is no window (e.g., a PS backend).
Set the title text of the window containing the figure, using set_window_title() method.. Note that this has no effect if there is no window (e.g., a PS backend).
Please use Ipython and follow the steps given below -
In [1]: from matplotlib import pylab

In [2]: fig = pylab.gcf()

In [3]: fig.canvas.set_window_title('Setting up window title.')
Matplotlib animation not working in IPython Notebook?

To animate a plot in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a random data of shape 10X10 dimension.
Create a random data of shape 10X10 dimension.
Create a figure and a set of subplots, using subplots() method.
Create a figure and a set of subplots, using subplots() method.
Makes an animation by repeatedly calling a function *func*, using FuncAnimation() class.
Makes an animation by repeatedly calling a function *func*, using FuncAnimation() class.
To update the contour value in a function, we can define a method animate that can be used in FuncAnimation() class.
To update the contour value in a function, we can define a method animate that can be used in FuncAnimation() class.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()

def animate(i):
   ax.clear()
   ax.contourf(data[:, :, i])

ani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)
plt.show()
MySQL GROUP BY date when using datetime?

To GROUP BY date while using datetime, the following is the syntax −
select *from yourTableName GROUP BY date(yourColumnName);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table groupByDateDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20),
   -> UserPostDatetime datetime
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Larry','2018-01-02 13:45:40');
Query OK, 1 row affected (0.18 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Mike','2018-01-02 13:45:40');
Query OK, 1 row affected (0.14 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Sam','2019-01-28 12:30:34');
Query OK, 1 row affected (0.33 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('David','2019-02-10 11:35:54');
Query OK, 1 row affected (0.18 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Maxwell','2019-02-10 11:35:54');
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from groupByDateDemo;
Here is the output −
+----+----------+---------------------+
| Id | UserName | UserPostDatetime    |
+----+----------+---------------------+
| 1  | Larry    | 2018-01-02 13:45:40 |
| 2  | Mike     | 2018-01-02 13:45:40 |
| 3  | Sam      | 2019-01-28 12:30:34 |
| 4  | David    | 2019-02-10 11:35:54 |
| 5  | Maxwell  | 2019-02-10 11:35:54 |
+----+----------+---------------------+
5 rows in set (0.00 sec)
Let us now GROUP BY date while using datetime. The query is as follows −
mysql> select *from groupByDateDemo GROUP BY date(UserPostDatetime);
The following is the output −
+----+----------+---------------------+
| Id | UserName | UserPostDatetime    |
+----+----------+---------------------+
| 1  | Larry    | 2018-01-02 13:45:40 |
| 3  | Sam      | 2019-01-28 12:30:34 |
| 4  | David    | 2019-02-10 11:35:54 |
+----+----------+---------------------+
3 rows in set (0.00 sec)
Different Ways to Check Which Shell You are Using on Linux - GeeksforGeeks

28 Mar, 2021
A shell is a program through which users can interact with the Operating System. Linux provides commonly 4 types of Shell The Bourne Shell ( /bin/sh or /sbin/sh ), The C shell ( /bin/csh ), The Korn Shell ( /bin/ksh ), The GNU Bourne-Again Shell ( /bin/bash ). This article is about to Check that which shell we are using. Here, we discuss five ways by which we can check which shell we are using.
1) Using echo command: Basically, the echo command is used to print the input string, but it is also used to print the name of the shell which we are using with the help of the command.
$ echo "My Shell name is: $SHELL"
2) Using ps command: ps command stands for “Process Status”. It is used to check the currently running status and their PIDs. If the ps command is run generally in the shell then it simply tells the name of the shell.
$ ps
2. Shell name using ps
The first column tells the PID and the last column tells the type of shell i.e. bash.
3) By viewing /etc/passwd file: This tells the feature of the user just like it’s name, shell, and ID. This command is used with the grep command.
$ grep "^$USER" /etc/passwd
4) Using lsof command: lsof stands for LIST OF OPEN FILES. This command used when we want the list of open files in our system. By using the specific flag it gives a pointer to the shell and tells us about that which shell are we using and that specific flag is -p $$. The command looks like.
$ lsof -p $$
As you can see clearly in the 3rd line it tells us about the shell we are using.
5) Using readlink /proc/$$/exe: The readlink is used to print the file name. So with the help of this, we print the location of the current shell using the /proc/$$/exe. Command can be written as
$ readlink /proc/$$/exe
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
mv command in Linux with examples
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program
How to check if a text field is empty or not in swift?

It’s very easy to check whether text field is empty or not in Swift.
You will first need to check whether text is available or not in text field i.e. it’s not nil, then you will need to check if its present then its empty or not. Assuming myTextField is your text field variable name, you can do the following
if let text = myTextField.text, text.isEmpty {
   // myTextField is not empty here
} else {
   // myTextField is Empty
}
Above code will check if textField is empty or not.
If you want to look at how the text field can be added and checked in details . Follow the below steps.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “CheckEmptyTextField”
Step 2 − Open Main.storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label.
Step 3 − Add IBOutlet for text field in ViewController, name it textField
@IBOutlet weak var textField: UITextField!
Step 4 − Add IBoutlet for label, it resultLabel
@IBOutlet weak var resultLabel: UILabel!
Step 5 − Add @IBAction for touchUpInside ‘Check’ button as follows
@IBAction func checkTextFeild(_ sender: Any) {
}
Step 6 − In checkTextFeild function we will test whether the textField is empty or not, and show the result in label. Add below code to do so
@IBAction func checkTextFeild(_ sender: Any) {
   if let text = textField.text, text.isEmpty {
      resultLabel.text = "Text field is empty"
   } else {
      resultLabel.text = "Text Field is not empty"
   }
}
Step 7 − Run the project. Click on ‘Check’ button, you should see that the label gets updated saying ‘Text field is empty"’
Step 8 − Type something in textField, now click on ‘Check’ button, you should see that the label gets updated saying ‘Text Field is not empty"’
Tryit Editor v3.7

Tryit: The flex shorthand property