code-rag-bench/online-tutorials huggingface dataset:
Visualizing the composition two of graph using networkx - GeeksforGeeks

24 Jan, 2021
In this article, we are going to see how to visualize the composition two of the graph using networkx. If we are given two graphs A and B then their composition can be found by performing union operation on node-set and edge-set of A and B.
Simply if an edge is contained between any two vertices in any of the initial graphs it will be contained in the composition of those graphs.
Example:
Initial Graph G:
G
Initial Graph H:
H
Result of Composition of G and H:
Composition(G,H)
Explanation: If we name nodes in both graphs G and H using integers then we will clearly observe that node and edge set of G will be superset of H and hence their union gives G in return.
Example 2:
Initial Graph G:
G
Initial Graph H:
H
Result of Composition of G and H:
R
Explanation: We can see that all the edges which are in graph G are present in graph H except the node between first and third node from right therefore doing composition of G and H adds all edges from G and H into the result.
Important points about Compose function:
H attributes take precedent over G attributes.
The graph returned is of the same type as G.
G and H should either be both directed or both undirected.
G and H must both be graphs or multigraphs
Realizing Composition using Python :
We will use networkx.compose() function for our task to do composition of 2 graphs.
Syntax: compose(G, H)
G: It is a networkx Graph object which is passed as an argument to compose function.
H: It is also an networkx Graph object which is passed as an argument to compose function.
Result of compose function will be union of edge and vertices set of G and H.
Approach:
We will import networkx with an alias nx.
Create a sample graph object G using path_graph() function.
Create second sample graph object H using path_graph() function.
We will then call compose function passing G as an argument.
We will capture the object returned by compose function in another object R.
We will then call draw() function passing R as an argument which will display the complement graph.
Code:
Python3
# importing networkx module import networkx as nx   # creating sample graph object G = nx.path_graph(7)   # creating sample graph object H = nx.path_graph(3)  # compose of G and H saving in RR = nx.compose(G,H)   # calling draw() to visualize the complement graph nx.draw(R) 
Output:
OUTPUT
Python Networx-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Difference between app.use() and app.get() in Express.js - GeeksforGeeks

26 May, 2021
Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features
Perquisites: Follow these steps for project setup and module installation.
Step 1: Create a directory using the below-given command. After creating a directory add the location of the created directory in a terminal.
 mkdir <folder_name>
Step 2: Now initialize the npm (node package manager) using the below given command.
 
npm init
Step 3: Now Install Express in the present directory and save it in the dependencies list.
npm install express --save 
1. app.use(): The app.use() function is used to mount the specified middleware function (are the functions that have access to the request object and response object, or we can call it a response-request cycle) at the path which is being specified. The middleware function is executed when the base of the requested path matches the path.
Syntax:
app.use([path,],callback[,callback...])
index.js
// Requiring moduleconst express = require('express')const app = express()  app.use(function(req, res, next) {  console.log('hello world')  next()})  app.use(function(req, res, next) {  console.log('happy holidays')  next()})  // Server setupvar server = app.listen(8080, function () {    var port = server.address().port    console.log("Listening at", port) })
Run the index.js file using the following command:
node index.js
Output: 
2. app.get(): This function tells the server what to do when get requests at a given route.
index.js
// Requiring modulevar express = require('express');var app = express();  app.get('/', function (req, res) {   res.send('Hello Geek');})  // Server setupvar server = app.listen(8080, function () {   var host = server.address().address   var port = server.address().port   console.log(" Listening : ", port)})
Run the index.js file using the following command:
node index.js
Output: 
Difference between app.use() and app.get() methods:
app.use() method
app.get() method
Reference: 
https://www.geeksforgeeks.org/express-js-app-use-function/
https://www.geeksforgeeks.org/express-js-app-get-function/
Express.js
Node.js-Methods
NodeJS-Questions
Picked
Difference Between
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
What is a string? Declare and initialize the strings in C language

An array of characters (or) collection of characters is called a string.
Refer to the declaration given below −
char stringname [size];
For example - char a[50]; a string of length 50 characters.
The initialization is as follows −
Using single character constant −
Using single character constant −
char string[20] = { ‘H’, ‘i’, ‘l’, ‘l’, ‘s’ ,‘\0’}
Using string constants −
Using string constants −
char string[20] = "Hello":;
‘\0’ is called a null character. It marks the end of the string.
‘\0’ is called a null character. It marks the end of the string.
‘\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\0’ at the end if a single character is given.
‘\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\0’ at the end if a single character is given.
Accessing − There is a control string "%s" used for accessing the string, till it encounters ‘\0’.
Following is the C program for a string −
#include<stdio.h>
main ( ){
   char a[10] = "Hello";
   clrscr ( );
   printf ( " given string is %s",a)
   getch ( );
}
When the above program is executed, it produces the following result −
Given string is Hello
How to make the Tkinter text widget read only?

In Tkinter, sometimes, we may want to make a text widget disabled. To achieve
this, we can set the text configuration as DISABLED. This will freeze the text widget
and will make it read-only.
In this example, we will create a text widget and a button which will allow users to
disable or freeze the text widget instantly.
#Import the library
from tkinter import *

#Create an instance of window
win= Tk()

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

def disable_button():
   text.config(state= DISABLED)

#Label
Label(win,text="Type Something",font=('Helvetica bold', 25),
fg="green").pack(pady=20)

#Create a Text widget
text= Text(win, height= 10,width= 40)
text.pack()

#Create a Disable Button
Button(win, text= "Disable", command= disable_button,fg= "white",
bg="black", width= 20).pack(pady=20)

win.mainloop()
Running the above code will create a text widget and a button which can be used
to disable or freeze the widget.
After you click the “Disable” button, the text widget will be disabled and you won’t
be able to type anything else inside it.
Setup the format of DATETIME to 'DDMM- YYYY HH:MM:SS' with MySQL SELECT?

Whenever you retrieve datetime from a table, the datetime gives ‘YYYY-MM-DD’ format. If you want to change the output, then you need to use in-built date_format() from MySQL.
The syntax is as follows −
SELECT DATE_FORMAT(yourDatetimeColumnName,yourFormat) as anyVariableName from
yourTableName;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table UserDateFormat
   -> (
   -> ProductId int,
   -> ProductDeliverDate datetime
   -> );
Query OK, 0 rows affected (0.93 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into UserDateFormat values(100,date_add(now(),interval 1 year));
Query OK, 1 row affected (0.10 sec)

mysql> insert into UserDateFormat values(101,date_add(now(),interval -1 year));
Query OK, 1 row affected (0.48 sec)

mysql> insert into UserDateFormat values(102,date_add(now(),interval -3 year));
Query OK, 1 row affected (0.17 sec)

mysql> insert into UserDateFormat values(103,date_add(now(),interval -2 year));
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select command. The query is as follows −
mysql> select *from UserDateFormat;
+-----------+---------------------+
| ProductId | ProductDeliverDate  |
+-----------+---------------------+
|       100 | 2019-12-24 13:32:47 |
|       101 | 2017-12-24 13:32:58 |
|       102 | 2015-12-24 13:33:08 |
|       103 | 2016-12-24 13:33:17 |
+-----------+---------------------+
4 rows in set (0.00 sec)
The above datetime format is from MySQL datetime. Now you can format datetime accordingly, which includes the ‘DD-MM-YYYY’ format as well.
The query is as follows −
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %h:%i:%s') as UserFormat from
UserDateFormat;
The following is the output displaying date in the DD-MM-YYYY format −
+----------------------+
| UserFormat           |
+----------------------+
| 24-12-2019 01:32:47  |
| 24-12-2017 01:32:58  |
| 24-12-2015 01:33:08  |
| 24-12-2016 01:33:17  |
+----------------------+
4 rows in set (0.00 sec)
You can get the above time format in 24 hours. The query is as follows −
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %H:%i:%S') as UserFormat
from UserDateFormat;
+----------------------+
| UserFormat           |
+----------------------+
| 24-12-2019 13:32:47  |
| 24-12-2017 13:32:58  |
| 24-12-2015 13:33:08  |
| 24-12-2016 13:33:17  |
+----------------------+
4 rows in set (0.00 sec)
MongoDB query to get date records in a range

To get date records in a range, use gtalongwithlt. Let us create a collection with documents −
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-11 12:30:10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2863fecfb11e5c34d89927")
}
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-10-12 03:10:00")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28641acfb11e5c34d89928")
}
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-14 05:11:20")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28642acfb11e5c34d89929")
}
Display all documents from a collection with the help of find() method −
> db.demo60.find();
This will produce the following output −
{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") }
{ "_id" : ObjectId("5e28641acfb11e5c34d89928"), "ArrivalDate" : ISODate("2019-10-12T03:10:00Z") }
{ "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
Following is the query to get date records in a range −
> db.demo60.find({"ArrivalDate": {"$gt":ISODate("2019-01-09T12:30:10Z"), "$lt": ISODate("2019-01-16T12:30:10Z")}});
This will produce the following output −
{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") }
{ "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
How to find leap year or not in android using year API class?

This example demonstrate about How to find leap year or not in android using year API class.
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"?>
<android.support.constraint.ConstraintLayout
   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:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/date"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Local Date"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show current year is leap year or not.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.time.Year;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView = findViewById(R.id.date);
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
         Year year = Year.now();
         String leap;
         if(year.isLeap()) {
            leap = " is leap year";
         } else {
            leap = " is not leap year";
         }
         textView.setText(String.valueOf(year+leap));
      }
   }
}
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 −
In the above result, it is showing current local year is not a leap year.
Click here to download the project code
HTTP headers | Strict-Transport-Security

05 Nov, 2019
HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps protect websites from malicious activities and informs user agents and web browsers how to handle its connection through a response header. Whenever a website connects through HTTP and then redirects to HTTPS, an opportunity for a man-in-the-middle attack is created and the redirect can lead the users to a malicious website because users first have to communicate with the non-encrypted version of the website. A server implements the HSTS policy by supplying a header over an HTTPS connection which informs the browser to load a site using HTTPS rather than HTTP.
Syntax:
Strict-Transport-Security: max-age=<expire-time>
Strict-Transport-Security: max-age=<expire-time>; includeSubDomains
Strict-Transport-Security: max-age=<expire-time>; preload
Directives:
<expire-time>: This mentions the time in seconds for which the user agent or browser should only access the server in a secure fashion by using HTTP.
includeSubDomains: This directs the browser to apply the rule to all pages and sub-domains of the site as well.
preload: This is necessary for inclusion in most major web browsers’ HSTS preload lists.
Explanation: If a user type in an address bar http://www.geeksforgeeks.com/ or geeksforgeeks.com this will create a chance for a man-in-the-middle attack. The redirect could be exploited to direct visitors to a malicious site instead of the secure version of the original site.
Examples:
Strict-Transport-Security: max-age=3600; includeSubDomains
All pages and subdomains will be HTTPS for a max-age of 1 hour. This blocks access to pages or sub domains that cannot be served over HTTPS.
Strict-Transport-Security: max-age=7200; includeSubDomains; preload

All present and future sub-domains will be HTTPS for a max-age of 2 hour. It also has preload as the suffix which is necessary in most major web browsers’ HSTS pre-load lists.
To check this Strict-Transport-Security in action go to Inspect Element -> Network check the response header for Strict-Transport-Security like below, Strict-Transport-Security is highlighted you can see.Supported Browsers: The following browsers are compatible with HTTP Strict-Transport-Security.
Google Chrome 4.0
Internet Explorer 11.0
Firefox 4.0
Safari 7.0
Opera 12.0
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How do I copy items from list to list without foreach in C#?

The List<T> is a collection of strongly typed objects that can be accessed by index
and having methods for sorting, searching, and modifying list.
It is the generic version of the ArrayList that comes under System.Collection.Generic
namespace.
List<T> equivalent of the ArrayList, which implements IList<T>.
It comes under System.Collection.Generic namespace.
List<T>can contain elements of the specified type. It provides compile-time type
checking and doesn't perform boxing-unboxing because it is generic.
Elements can be added using the Add(), AddRange() methods or collection-initializer
syntax.
Elements can be accessed by passing an index e.g. myList[0]. Indexes start from zero.
List<T> performs faster and less error-prone than the ArrayList.
A list can be accessed by an index, a for/foreach loop, and using LINQ queries.
Indexes of a list start from zero.
Pass an index in the square brackets to access individual list items, same as array. Use
a foreach or for loop to iterate a List<T> collection.
class Program{
   public static void Main(){
      List<int>originalList=new List<int>(){1,2,3,4,5,7,8,9};
      List<Int32>copy = new List<Int32>(originalList);
      foreach (var item in copy){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}
1
2
3
4
5
7
8
9
class Program{
   public static void Main(){
      List<int>originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 };
      List<Int32> copy = originalList.ToList();
      foreach (var item in copy){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}
1
2
3
4
5
7
8
9
class Program{
   public static void Main(){
      List<int> originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 };
      List<Int32> copy = originalList.GetRange(0, 3);
      foreach (var item in copy){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}
1
2
3
Bash shell script to find out the largest value from given command line arguments

05 Sep, 2019
Write a shell script to find out the largest value from the given number of command-line arguments.
Example:
Special variables in bash:
$@- All arguments.
$#- Number of arguments.
$0- Filename.
$1, $2, $3, $4 ... - Specific arguments.

Approach
If the number of arguments is 0, end the program.
If not zero, thenInitialize a variable maxEle with first argument.Loop over all the arguments. Compare each argument with maxEle and update it if the argument is greater.
Initialize a variable maxEle with first argument.
Loop over all the arguments. Compare each argument with maxEle and update it if the argument is greater.
#Check if the number of arguments passed is zeroif [ "$#" = 0 ]then    #Script exits if no    #arguments passed    echo "No arguments passed."    exit 1fi  #Initialize maxEle with #the first argumentmaxEle=$1  #Loop that compares maxEle with the #passed arguments and updates itfor arg in "$@"do    if [ "$arg" -gt "$maxEle" ]    then        maxEle=$arg    fidoneecho "Largest value among the arguments passed is: $maxEle"
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – DROP COLUMN

28 Aug, 2020
PostgreSQL also supports the DROP COLUMN clause in the ALTER TABLE statement to remove one or more columns of a table. When you remove a column from a table, PostgreSQL will automatically remove all of its indexes and constraints involving the column.
Syntax:
ALTER TABLE table_name 
DROP COLUMN column_name;
Now let’s look into an example.
Example:First, we create a few tables (say, books, categories, and publishers ) for demonstration having the below depicted relationships:
We create the above tables using the below statements:
CREATE TABLE publishers (
    publisher_id serial PRIMARY KEY,
    name VARCHAR NOT NULL
);

CREATE TABLE categories (
    category_id serial PRIMARY KEY,
    name VARCHAR NOT NULL
);

CREATE TABLE books (
    book_id serial PRIMARY KEY,
    title VARCHAR NOT NULL,
    isbn VARCHAR NOT NULL,
    published_date DATE NOT NULL,
    description VARCHAR,
    category_id INT NOT NULL,
    publisher_id INT NOT NULL,
    FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id),
    FOREIGN KEY (category_id) REFERENCES categories (category_id)
);
In addition, we create a view based on the books and publishers tables as follows:
CREATE VIEW book_info AS SELECT
    book_id,
    title,
    isbn,
    published_date,
    name
FROM
    books b
INNER JOIN publishers P ON P .publisher_id = b.publisher_id
ORDER BY
    title;
If we want to remove the category_id column of the books table, we use the following statement:
ALTER TABLE books DROP COLUMN category_id;
Now we check the books table using the below statement:
SELECT * FROM books;
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
java.time.Duration Class in Java

24 Jan, 2022
Duration is the value-based Class present in the Java time library. It’s used to get time-based amount of time. This class is immutable and thread-safe. This article describes all the methods present in this class and some basic examples using class methods. 
This class implements Serializable, Comparable<Duration>, TemporalAmount interfaces.
Field present in Class:
Methods present in Class:
Example 1: This example illustrates simple use of Duration class.
Java
// Importing required classesimport java.time.Duration;import java.time.LocalTime;import java.time.temporal.ChronoUnit; public class GFG {   public static void main(String[] args) {             // Initializing Duration variable      Duration duration = Duration.between(LocalTime.NOON,LocalTime.MIDNIGHT);              // Printing difference between time in seconds      System.out.println(duration.get(ChronoUnit.SECONDS));                // Finding absolute difference      Duration absDuration = duration.abs();             // Printing absolute time difference in seconds      System.out.println(absDuration.get(ChronoUnit.SECONDS));      }}
-43200
43200
Example 2: 
Java
// Importing required classesimport java.time.Duration;import java.time.temporal.ChronoUnit; public class GFG {   public static void main(String[] args) {             // Getting duration in an hour      Duration duration = Duration.from(ChronoUnit.HOURS.getDuration());             // Printing duration in minutes      System.out.println(duration.toMinutes());   }}
Output: 
60
 
simmytarika5
varshagumber28
Java-Duration
Java-time package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Java Program to locate a character in a string

To locate a character in a string, use the indexOf() method.
Let’s say the following is our string.
String str = "testdemo";
Find a character ‘d’ in a string and get the index.
int index = str.indexOf( 'd');
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      int index = str.indexOf( 'd' );
      System.out.printf("'d' is at index %d\n", index);
   }
}
String: testdemo
'd' is at index 4
Let us see another example. The method returns -1, if the character isn’t found −
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      int index = str.indexOf( 'h' );
      System.out.printf("'h' is at index %d\n", index);
   }
}
String: testdemo
'h' is at index -1
JavaScript - Array concat() Method

Javascript array concat() method returns a new array comprised of this array joined with two or more arrays.
The syntax of concat() method is as follows −
array.concat(value1, value2, ..., valueN);

valueN − Arrays and/or values to concatenate to the resulting array.
This method returns an array object representing the resultant array, a concatenation of the current and given array(s).
Try the following example.
<html>
   <head>
      <title>JavaScript Array concat Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var alpha = ["a", "b", "c"];
         var numeric = [1, 2, 3];
         var alphaNumeric = alpha.concat(numeric);
         document.write("alphaNumeric : " + alphaNumeric ); 
      </script>      
   </body>
</html>
alphaNumeric : a,b,c,1,2,3 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Python | Pandas Timestamp.fromtimestamp - GeeksforGeeks

14 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.fromtimestamp() function return a Timestamp object when passed an integer which represents the timestamp value.
Syntax :Timestamp.fromtimestamp()
Parameters : integer
Return : Timestamp
Example #1: Use Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                  hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# convert to a Timestamp objectts.fromtimestamp(992345678)
Output :
As we can see in the output, the Timestamp.fromtimestamp() function has returned a new Timestamp object constructed from the passed value.
Example #2: Use Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                  hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# convert to a Timestamp objectts.fromtimestamp(634816)
Output :
As we can see in the output, the Timestamp.fromtimestamp() function has returned a new Timestamp object constructed from the passed value.
Python Pandas-Timestamp
Python-pandas
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
jQuery | serializeArray() with Examples - GeeksforGeeks

13 Feb, 2019
The serializeArray() is an inbuilt method in jQuery which is used to create a JavaScript array of objects that is ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types. JSON string is a text and can convert any JavaScript object into JSON, and send JSON to the server.Syntax:
$(selector).serializeArray()

Parameter: It does not accept any parameter.
Return Value: It return a string of objects.
jQuery code to show the working of serializeArray() method:
<html>   <head>    <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <!-- jQuery code to show the working of this method -->    <script>        $(document).ready(function() {            $("button").click(function() {                var x = $("form").serializeArray();                $.each(x, function(i, field) {                    $("#d").append(field.name + ":" + field.value + ":::");                });            });        });    </script>    <style>        #d1 {            width: 300px;            height: 100px;            padding: 20px;            border: 2px solid green;            margin-bottom: 10px;        }    </style></head>   <body>    <div id="d1">        <form action="">            Site name:            <input type="text" name="SiteName" value="GeeksforGeeks">            <br>            <br> Contributor name:            <input type="text" name="ContributorName" value="KundanJha">            <br>        </form>        <!-- click on this button -->        <button>Click here!</button>    </div>    <div id="d"></div>   </body>   </html>
Output:Before clicking on the “Click here!” button-
After clicking on the “Click here!” button-
jQuery-AJAX
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
C | Data Types | Question 2 - GeeksforGeeks

28 Jun, 2021
Which of the following is not a valid declaration in C?
1. short int x;
2. signed short x;
3. short x;
4. unsigned short x;
(A) 3 and 4(B) 2(C) 1(D) All are validAnswer: (D)Explanation: All are valid. First 3 mean the same thing. 4th means unsigned.Quiz of this Question
C-Data Types
Data Types
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
Core Dump (Segmentation fault) in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
MAN Full Form - GeeksforGeeks

19 Aug, 2021
MAN stands for metropolitan area network and it is basically a computer network that is made by connecting multiple LAN’S. MAN covers a geographical area which is known as the metropolitan area. It serves as a connection which is larger than LAN(Local Area Network) but smaller than WAN(Wide Area Network). It generally covers the area of a city. It connects different LAN’s in an area by point to point connection. MAN also provides sharing of regional resources. MAN is very effective to use in large area like a city or a large campus. 
 
Examples:
Cable TV network and telephone networks
Characteristics :  
Area Covered – It covers an area from 5 km to 50 km which can cover a city.
Ownership – MAN is owned by a group of users rather than a single company.
High speed – MAN provides high speed network which uses shared regional resources.
Size – Size of MAN is in between WAN and LAN.
Advantages : 
MAN covers a larger area than LAN.
It has less implementation cost and it uses less resources.
It provides higher security than WAN.
It can cover area as large as a city.
MAN is a faster way to connect two fast LANs together. This is due to the fast configuration of links.
In some installation of MANs, users can share their internet connection. So multiple users can get the same high-speed internet.
   Disadvantages : 
MAN is not easily manageable as it becomes very complex.
It requires highly skilled people to look after it.
It requires more cables for connecting the LAN’s.
It has high management cost
It covers smaller area than WAN.
It is only used in metropolitan areas.
Examples of metropolitan area network (MAN) :
 Some of the examples of MAN are:-
Digital cable television
Used in government agencies
Used to connect several branches of the local school
A network of fire stations
University campuses
Networking between community colleges within the country
Cable broadband
pp_pankaj
jyoti369
naveenkumarkharwal
Computer Networks
Full Form
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
DBA Full Form
RDBMS Full Form
HTTP Full Form
CDMA Full Form
SCTP Full Form
Python - Group Elements in Matrix - GeeksforGeeks

30 Dec, 2020
Given a Matrix with two columns, group 2nd column elements on basis of 1st column.
Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]]Output : {5: [8, 4], 2: [0, 3, 9]}Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2.
Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2, 9]]Output : {2: [8, 4, 0, 3, 9]}Explanation : All mapped to 2.
Method #1 : Using dictionary comprehension + loop
This is one of the ways in which this task can be performed. In this, we construct the dictionary with empty list values from row 1 and then run a loop to assign values into it.
Python3
# Python3 code to demonstrate working of # Group Elements in Matrix# Using dictionary comprehension + loop  # initializing listtest_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]  # printing original listprint("The original list : " + str(test_list))  # initializing empty dictionary with default empty list res = {idx[0]: [] for idx in test_list}  # using loop for groupingfor idx in test_list:    res[idx[0]].append(idx[1])  # printing result print("The Grouped Matrix : " + str(res))
The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}

Method #2 : Using loop + defaultdict()
This is similar to above method. The difference being that initial empty mesh is created using defaultdict().
Python3
# Python3 code to demonstrate working of # Group Elements in Matrix# Using loop + defaultdict()from collections import defaultdict  # initializing listtest_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]  # printing original listprint("The original list : " + str(test_list))  # initializing empty dictionary using defaultdictres = defaultdict(list)  # using loop for groupingfor idx in test_list:    res[idx[0]].append(idx[1])  # printing result print("The Grouped Matrix : " + str(dict(res)))
The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}

Python dictionary-programs
Python matrix-program
Python
Python Programs
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
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Find closest number to k in given list - GeeksforGeeks

17 Oct, 2019
Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K.
Examples:
Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1
Output : 9.35

Input : lst = [9, 11, 5, 3, 25, 18], K = 6
Output : 5

 Method #1 : Using min() method
In this approach, we use min method from Python and apply a key that finds the absolute difference of each element with K, and returns the element having minimum difference.
# Python3 program to find Closest number in a list  def closest(lst, K):          return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]      # Driver codelst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]K = 9.1print(closest(lst, K))
9.35

 Method #2 : Using numpy module
This approach applies the same method but using numpy module. First we convert the given list to an array. Find absolute difference with K of each element, and return the minimum from it.
# Python3 program to find Closest number in a listimport numpy as npdef closest(lst, K):           lst = np.asarray(lst)     idx = (np.abs(lst - K)).argmin()     return lst[idx]      # Driver codelst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]K = 9.1print(closest(lst, K))
9.35

nidhi_biet
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python Program to Find the Number Occurring Odd Number of Times - GeeksforGeeks

28 Oct, 2019
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3

Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5

Python3
# Python program to find the element occurring# odd number of times      # function to find the element occurring odd# number of timesdef getOddOccurrence(arr, arr_size):          for i in range(0, arr_size):        count = 0        for j in range(0, arr_size):            if arr[i] == arr[j]:                count+= 1                      if (count % 2 != 0):            return arr[i]              return -1            # driver code arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]n = len(arr)print(getOddOccurrence(arr, n))  # This code has been contributed by # Smitha Dinesh Semwal
5

A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
Python
      # Python program to find the element occurring odd number of times  def getOddOccurrence(arr):      # Initialize result    res = 0          # Traverse the array    for element in arr:        # XOR with the result        res = res ^ element      return res  # Test arrayarr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]  print "% d" % getOddOccurrence(arr)
5

Please refer complete article on Find the Number Occurring Odd Number of Times for more details!
shubham_singh
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Iterate over characters of a string in Python
Python Program for factorial of a number
Python | Convert set into a list
Python | Convert a list into a tuple
Python | Check if a variable is string
Python program to add two numbers
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python program to find sum of elements in list
C program to traverse an Array - GeeksforGeeks

30 Mar, 2021
Given an integer array of size N, the task is to traverse and print the elements in the array.Examples: 
Input: arr[] = {2, -1, 5, 6, 0, -3} Output: 2 -1 5 6 0 -3
Input: arr[] = {4, 0, -2, -9, -7, 1} Output: 4 0 -2 -9 -7 1  
Approach:-  
1. Start a loop from 0 to N-1, where N is the size of array. 
for(i = 0; i < N; i++)
2. Access every element of array with help of 
arr[index]
3. Print the elements. 
printf("%d ", arr[i])
Below is the implementation of the above approach:  
C
// C program to traverse the array #include <stdio.h> // Function to traverse and print the arrayvoid printArray(int* arr, int n){    int i;     printf("Array: ");    for (i = 0; i < n; i++) {        printf("%d ", arr[i]);    }    printf("\n");} // Driver programint main(){    int arr[] = { 2, -1, 5, 6, 0, -3 };    int n = sizeof(arr) / sizeof(arr[0]);     printArray(arr, n);     return 0;}
Array: 2 -1 5 6 0 -3
 
Time Complexity: O(n)
Auxiliary Space: O(1)
souravmahato348
C-Arrays
Arrays
C Programs
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
Python - Remove elements at Indices in List - GeeksforGeeks

01 Dec, 2021
Given List, remove all the elements present in indices list.
Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] Output : [5, 6, 7, 2, 10] Explanation : 3, 6, and 1 has been removed.Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] Output : [5, 6, 7, 8, 1, 2, 10] Explanation : 3 has been removed.  
Method #1 : Using enumerate() + loop
In this, we iterate for all the elements, and if index is present in list, then that index element is omitted from result list.
Python3
# Python3 code to demonstrate working of# Remove elements at Indices in List# Using loop # initializing listtest_list = [5, 6, 3, 7, 8, 1, 2, 10] # printing original listprint("The original list is : " + str(test_list)) # initializing idx listidx_list = [2, 4, 5, 7] res = []for idx, ele in enumerate(test_list):         # checking if element not present in index list    if idx not in idx_list:        res.append(ele) # printing resultsprint("Filtered List after removal : " + str(res))
The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]
Method #2 : Using enumerate() + list comprehension
In this, we perform task of iteration using list comprehension in compact way, rest all method similar to above.
Python3
# Python3 code to demonstrate working of# Remove elements at Indices in List# Using enumerate() + list comprehension # initializing listtest_list = [5, 6, 3, 7, 8, 1, 2, 10] # printing original listprint("The original list is : " + str(test_list)) # initializing idx listidx_list = [2, 4, 5, 7] # one-liner to test for element in index listres = [ele for idx, ele in enumerate(test_list) if idx not in idx_list] # printing resultsprint("Filtered List after removal : " + str(res))
The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]
rajeev0719singh
Python list-programs
Python
Python Programs
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Merging two list of dictionaries - GeeksforGeeks

12 Oct, 2021
Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value.
Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id.
# Python code to  merge two list of dictionaries # based on some value.  from collections import defaultdict  # List initializationInput1 = [{'roll_no': ['123445', '1212'], 'school_id': 1},          {'roll_no': ['HA-4848231'], 'school_id': 2}]  Input2 = [{'roll_no': ['473427'], 'school_id': 2},          {'roll_no': ['092112'], 'school_id': 5}]    # Using defaultdicttemp = defaultdict(list)   # Using extendfor elem in Input1:    temp[elem['school_id']].extend(elem['roll_no'])  for elem in Input2:    temp[elem['school_id']].extend(elem['roll_no'])  Output = [{"roll_no":y, "school_id":x} for x, y in temp.items()]  # printingprint(Output)
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]
 Method #2: Using extend() only.
# Python code to  merge two list of dictionaries # based on some value.  # List initializationInput1 = [{'roll_no': ['123445', '1212'], 'school_id': 1},          {'roll_no': ['HA-4848231'], 'school_id': 2}]Input2 = [{'roll_no': ['473427'], 'school_id': 2},          {'roll_no': ['092112'], 'school_id': 5}]  # Iterating and using extend to convertfor elm2 in Input2:      for elm1 in Input1:        if elm2['school_id'] == elm1['school_id']:            elm1['roll_no'].extend(elm2['roll_no'])            break    else:        Input1.append(elm2)  # printing print(Input1)
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]
Akanksha_Rai
gabaa406
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary