code-rag-bench/online-tutorials huggingface dataset:
How to Get the Tkinter Label Text?

11 Dec, 2020
Prerequisite: Python GUI – Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task.
In this article, we are going to write a Python script to get the tkinter label text. Below are the various methods discussed:
Method #1: Using cget() method.
Approach:
Importing the module.
Create the main window (container).
Add Label widgets to the main window.
Apply the cget() method and get label text.
Implementation:
Python3
# import modulesimport tkinter as tk  # object of tkinter# and background set for light greymaster = tk.Tk()master.configure(bg='light grey')  # create labell = tk.Label(master,             text="Welcome to geeksforgeeks",             bg="red")  # apply cget()print("Label text: ", l.cget("text"))  l.pack()master.mainloop()
Output:
Method #2: Using Dictionary label object.
Approach:
Importing the module.
Create the main window (container).
Add Label widgets to the main window.
Use Dictionary label object and get label text.
Python3
# import modules import tkinter as tk  # object of tkinter # and background set for light grey master = tk.Tk() master.configure(bg = 'light grey')     # create labell = tk.Label(master,              text = "Welcome to geeksforgeeks",              bg = "red")  # using dictionary label objectprint("Label text: ", l["text"])  l.pack()tk.mainloop()
Output:
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to change the color of horizontal line (<hr> element) using CSS ?

18 Nov, 2020
The HTML <hr> tag is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections. The color of the <hr> tag can be set by using the background-color property in CSS.
Example:
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">      <style>        hr {            height: 4px;            background-color: red;            border: none;        }    </style></head>  <body>    <h1>GeeksForGeeks</h1>      <h2>        How to Changing the co lor         of an hr element using CSS?    </h2>      <p>This is a paragraph</p>    <hr>          <p>This is another paragraph</p></body>  </html>
Output:
Supported browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Ruby | Numeric divmod() function

07 Jan, 2020
The divmod() is an inbuilt method in Ruby returns the integer quotient and modulus after performing the division.
Syntax: num1.divmod(num2)
Parameters: The function needs two numbers whose integer division is to be performed.
Return Value: It returns returns the integer quotient and modulus after performing the division..
Example 1:
#Ruby program for divmod() method in Matrix  #Initialize a numbernum1 = 15  #Prints quotient and modulus of num1 / 4puts num1.divmod(4)
Output:
3
3

Example 2:
#Ruby program for divmod() method in Matrix  #Initialize a numbernum1 = 20  #Prints quotient and modulus of num1 / 2puts num1.divmod(2)
Output:
10
0
Ruby Numeric-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are the DML commands in DBMS?

The structured query language (SQL) commands deal with the manipulation of data present in the database that belongs to the DML or Data Manipulation Language. This includes most of the SQL statements.
The examples of DML in the Database Management System (DBMS) are as follows −
SELECT − Retrieve data from the database.
SELECT − Retrieve data from the database.
INSERT − Insert data into a table.
INSERT − Insert data into a table.
UPDATE − Update existing data within a table.
UPDATE − Update existing data within a table.
DELETE − Delete records from a database table.
DELETE − Delete records from a database table.
The syntax for the DML commands are as follows −
Insert command is used to insert data into a table.
The syntax for insert command is as follows −
Syntax
Insert into <table_name> (column list) values (column values);
For example, if we want to insert multiple rows to the Employee table, we can use the following command −
Example
Insert into Employee(Emp_id, Emp_name) values (001, “ bhanu”);
Insert into Employee(Emp_id, Emp_name) values (002, “ hari”);
Insert into Employee(Emp_id, Emp_name) values (003, “ bob”);
Select command is used to retrieve data from the database.
The syntax for the select command is as follows −
Syntax
SELECT * from <table_name>;
For example, if we want to select all rows from the Employee database, we can use the following command −
Example
SELECT * from Employee;
Delete command is used to delete records from a database table.
The syntax for the delete command is as follows -
Syntax
 Delete from <table_name>WHERE condition;
For example, if we want to delete an entire row of employee id 002, we can use the following command −
Example
DELETE from Employee WHERE Emp_id=002;
Update command is used to update existing data within a table.
The syntax for the update command is as follows -
Syntax
UPDATE <table_name> SET column_number =value_number WHERE condition;
For example, if we want to update the name of the employee having the employee id 001, we can use the command given below −
Example
UPDATE Employee SET Emp_name= Ram WHERE Emp_id= 001;
Take input from stdin in Python

01 Jul, 2022
In this article, we will see How to Read from stdin in Python. 
There are a number of ways in which we can take input from stdin in Python. 
sys.stdin
input()
fileinput.input()
The sys module in python helps us to access the variables maintained by the interpreter. It also provides functions to interact with the interpreter. To use sys in Python, we firstly import sys
Using sys.stdin: sys.stdin can be used to get input from the command line directly. It used is for standard input. It internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence. let see a sys stdin python example:
Python3
import sys for line in sys.stdin:    if 'q' == line.rstrip():        break    print(f'Input : {line}') print("Exit")
Output 
 
The input() can be used to take input from the user while executing the program and also in the middle of the execution.
Python3
# this accepts the user's input# and stores in inpinp = input("Type anything") # prints inpprint(inp)
Output:
 
Using fileinput.input(): If we want to read more than one file at a time, we use fileinput.input() . There are two ways to use fileinput.input(). To use this method, first, we need to import fileinput.
Example 1: 
Here, we pass the name of the files as a tuple in the “files” argument. Then we loop over each file to read it.
Python3
import fileinput with fileinput.input(files=('sample.txt', 'no.txt')) as f:    for line in f:        print(line)
Output: 
 
Example 2: 
Here, we pass the file name a sys argument in the command line. 
Python3
import fileinput for f in fileinput.input():    print(f)
Output: 
 
kalrap615
kapoorsagar226
surajkumarguptaintern
python-basics
python-input-output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vscan – Vulnerability Scanner Tool Using Nmap And NSE Scripts in Kali Linux

07 Oct, 2021
Vscan is a free and open-source tool available on GitHub. Vscan has based nmap scanning techniques, the easiest and useful tool for reconnaissance. Vscan interface is very similar to Metasploit 1 and Metasploit 2. Vscan has its own modules that add additional value to the standard scanner which is nmap. Vscan has NSE scripts that give additional features to nmap to detect and find vulnerabilities and further which can be used to perform exploitation.  Nse scripts have many modules such as network discovery and backdoor detection. This tool provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain) which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. Vscan is a web reconnaissance tool written in bash script. It has so many modules such as database interaction, built-in convenience functions, NSE scripts interactive help, and command completion. Vscan provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the domain or ip address with ports.
It can be used with nmap for network discoveries on ports.
It can give more sophisticated versions in-network detection.
It can be used to detect vulnerability detection.
It can be used for backdoor detection on host/victim IP addresses.
It can be used to exploit vulnerabilities in the network.
Step 1: Open your kali linux operating system terminal and use the following command in order to install the tool. Use the second command to move into the directory of the Vscan.
git clone https://github.com/xen0vas/vscan.git
cd vscan
Step 2: Now use the following command to list out the contents of the tool.
ls
Step 3. The tool has been successfully installed now use the following command to run the tool.
./vscan.sh
The tool is running successfully now we will see examples to use the tool.
./vscan.sh 192.168.162.90 http 80
The tool has started scanning the given IP address.
In this way, the tool will give a report of scanning.
./vscan.sh 192.168.162.10-90 http 80
Vscan automates the Nmap vulnerability scanner using NSE scripts.
sweetyty
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
C# program to find Union of two or more Lists

Firstly, create lists −
//three lists
var list1 = new List{3, 4, 5};
var list2 = new List{1, 2, 3, 4, 5};
var list3 = new List{5, 6, 7, 8};
Use the union method to get the union of list1 and list2 −
var res1 = list1.Union(list2);
var res2 = res1.Union(list3);
The following is the complete code −
 Live Demo
using System.Collections.Generic;
using System.Linq;
using System;

public class Demo {
   public static void Main() {
      //three lists
      var list1 = new List<int>{3, 4, 5};
      var list2 = new List<int>{1, 2, 3, 4, 5};
      var list3 = new List<int>{5, 6, 7, 8};

      // finding union
      var res1 = list1.Union(list2);
      var res2 = res1.Union(list3);

      foreach(int i in res2) {
         Console.WriteLine(i);
      }
   }
}
3
4
5
1
2
6
7
8
Tcl - If else Statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
The syntax of an 'if...else' statement in Tcl language is −
if {boolean_expression} {
   # statement(s) will execute if the boolean expression is true 
} else {
   # statement(s) will execute if the boolean expression is false
}

If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.
Tcl language uses the expr command internally and hence it's not required for us to use expr statement explicitly.
#!/usr/bin/tclsh

set a 100

#check the boolean condition 
if {$a < 20 } {
   #if condition is true then print the following 
   puts "a is less than 20"
} else {
   #if condition is false then print the following 
   puts "a is not less than 20"
}
puts "value of a is : $a"
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100

An 'if' statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if , else if, else statements there are few points to keep in mind −
An 'if' can have zero or one else's and it must come after any else if's.
An 'if' can have zero or one else's and it must come after any else if's.
An 'if' can have zero to many else if's and they must come before the else.
An 'if' can have zero to many else if's and they must come before the else.
Once an 'else if' succeeds, none of the remaining else if's or else's will be tested.
Once an 'else if' succeeds, none of the remaining else if's or else's will be tested.
The syntax of an 'if...else if...else' statement in Tcl language is −
if {boolean_expression 1} {
   # Executes when the boolean expression 1 is true
} elseif {boolean_expression 2} {
   # Executes when the boolean expression 2 is true 
} elseif {boolean_expression 3} {
   # Executes when the boolean expression 3 is true 
} else {
   # executes when the none of the above condition is true 
}

#!/usr/bin/tclsh

set a 100

#check the boolean condition
if { $a == 10 } {
   # if condition is true then print the following 
   puts "Value of a is 10"
} elseif { $a == 20 } {
   # if else if condition is true 
   puts "Value of a is 20"
} elseif { $a == 30 } {
   # if else if condition is true 
   puts "Value of a is 30"
} else {
   # if none of the conditions is true 
   puts "None of the values is matching"
}

puts "Exact value of a is: $a"
When the above code is compiled and executed, it produces the following result −
None of the values is matching
Exact value of a is: 100

 Print
 Add Notes
 Bookmark this page
C++ Regex Library - regex_replace

It makes a copy of the target sequence (the subject) with all matches of the regular expression rgx (the pattern) replaced by fmt (the replacement). The target sequence is either s or the character sequence between first and last, depending on the version used.
Following is the declaration for std::regex_replace.
template <class traits, class charT>
   basic_string<charT>regex_replace (const charT* s,
          const basic_regex<charT,traits>& rgx,
          const charT* fmt,
template <class traits, class charT>
   basic_string<charT>regex_replace (const charT* s,
          const basic_regex<charT,traits>& rgx,
          const charT* fmt,
template <class traits, class charT>
   basic_string<charT>regex_replace (const charT* s,
          const basic_regex<charT,traits>& rgx,
          const charT* fmt,
s − It is a string with the target sequence.
s − It is a string with the target sequence.
rgx − It is a basic_regex object to match.
rgx − It is a basic_regex object to match.
flags − It is used to control how rgx is matched.
flags − It is used to control how rgx is matched.
m − It is an object of a match_results type.
m − It is an object of a match_results type.
It returns a string object with the resulting sequence.
No-noexcept − this member function never throws exceptions.
In below example for std::regex_replace.
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

int main () {
   std::string s ("there is a subsequence in the string\n");
   std::regex e ("\\b(sub)([^ ]*)");

   std::cout << std::regex_replace (s,e,"sub-$2");
  
   std::string result;
   std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
   std::cout << result;

   std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
   std::cout << std::endl;

   return 0;
}
The output should be like this −
there is a sub-sequence in the string
there is a sequence in the string
sub and sequence

 Print
 Add Notes
 Bookmark this page
CSS - font-variant

The font-variant property determines the use of one of two font faces to be used in the rendering of a given element's text.
normal − Specifies a normal font face; that is, whatever is the default face for the font in use.
normal − Specifies a normal font face; that is, whatever is the default face for the font in use.
small-caps − Specifies a small-caps face; that is, a face in which lowercase characters are rendered as capital letters which are smaller than the letters used for uppercase characters.
small-caps − Specifies a small-caps face; that is, a face in which lowercase characters are rendered as capital letters which are smaller than the letters used for uppercase characters.
All the HTML elements.
object.style.fontVariant = "small-caps";

Here is the example using this property −
<html>
   <head>
   </head>

   <body>
      <p style = "font-variant:small-caps;">
         This text will be rendered as small caps
      </p>
   </body>
</html> 
This will produce following result −

   This text will be rendered as small caps


    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to query MongoDB with “like”?

You can easily query MongoDB with “like”:
db.yourCollectionName.find({"yourFieldName" : /.*yourMatchingValue.*/}).pretty();
To understand the above syntax, let us create a collection with some documents. Here, we have
a collection with the name ‘employee’. The query is as follows:
> db.employee.insert({"EmployeeName":"John","EmployeeSalary":450000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Carol","EmployeeSalary":150000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"James","EmployeeSalary":550000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Jace","EmployeeSalary":670000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Larry","EmployeeSalary":1000000});
WriteResult({ "nInserted" : 1 })
Now you can display all documents from a collection using find() method. The query is as
follows:
> db.employee.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"),
   "EmployeeName" : "John",
   "EmployeeSalary" : 450000
}
{
   "_id" : ObjectId("5c6c0b3b68174aae23f5ef5a"),
   "EmployeeName" : "Carol",
   "EmployeeSalary" : 150000
}
{
   "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"),
   "EmployeeName" : "James",
   "EmployeeSalary" : 550000
}
{
   "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"),
   "EmployeeName" : "Jace",
   "EmployeeSalary" : 670000
}
{
   "_id" : ObjectId("5c6c0b9e68174aae23f5ef5d"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 1000000
}
Here is the query in MongoDB with “like” operator:
> db.employee.find({"EmployeeName":/.*J.*/}).pretty();
The following is the output:
{
   "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"),
   "EmployeeName" : "John",
   "EmployeeSalary" : 450000
}
{
   "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"),
   "EmployeeName" : "James",
   "EmployeeSalary" : 550000
}
{
   "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"),
   "EmployeeName" : "Jace",
   "EmployeeSalary" : 670000
}
Neo4j - Backup & Restore

In real-time applications, we should take backup of our application database regularly, so that we can restore to some working condition at any failure point.
This rule is applicable for both RDBMS and NoSQL databases.
In this section, we are going to discuss about two important DBA tasks.
How to back up a Neo4j Database.
How to restore Neo4j Database to a specific backup.
Note − These steps are applicable to Windows Operating System only. We should use similar kind of commands to do the same steps in other operating systems.
Step 1 − Click "Neo4j Community" using the following path −
Windows "Start" button → "All Programs" → "Neo4j Community" → "Neo4j Community"
By default, it selects c:\Users\[username]\Documents\Neo4j\default.graphdb. However if we wish to, we can change the path to a different directory.
Step 2 − Here we have changed to our Neo4j Database folder.
C:\Ne04j2.0db
Step 3 − Click the "Start" button.
Once the server starts, we can observe our Neo4j Database files are generated at a specified directory.
Before taking a database backup, the first and foremost thing we should do is shutdown the Neo4j Database server.
Step 4 − Click the "Stop" button to shut down the server.
Neo4j Database files are available at C:\Ne04j2.0db
Step 5 − Open the command prompt.
Step 6 − Create a folder "Neo4jDbBackup-01" at C:\Neo4j (This may be any location in your file system).
mkdir C:\Neo4j\Neo4jDbBackup-01 

It creates a new folder "Neo4jDbBackup-01" at the specified file system location "C:\Neo4j\"
Step 7 − Type the following command and press Enter key.
copy C:\Ne04j2.0db C:\Neo4j\Neo4jDbBackup-01 

This means our files are copied to the required destination folder. Access that folder and observe that the folder has our database files.
Step 8 − Use any Windows compression/decompression tool like WinZip, 7 Zip, or WinRAR to zip our Database folder.
Step 9 − Now our Neo4jDbBackup-01.zip file is created. If you have any memory constraints in your file system, then remove "Neo4jDbBackup-01" folder at "C:\Neo4j\"
Step 1 − Shutdown the database server. Please refer to the previous steps to shut down the server.
Step 2 − Empty the current database folder.
Step 3 − Use any Windows compression/decompression tool like WinZip, 7 Zip, or WinRar to unzip our backup folder.
Step 4 − Open the command prompt and execute the following command.
Copy C:\Neo4j\Neo4jDbBackup-01 C:\Ne04j2.0db 

Now we can observe that our database folder contains working backup files
Step 5 − Start the server by clicking the "Start" button.
Step 6 − Execute some MATCH + RETURN commands to verify whether we have restored our database properly.
 Print
 Add Notes
 Bookmark this page
How to change the Pandas datetime format in Python? - GeeksforGeeks

11 Dec, 2020
Prerequisites: Pandas
The date-time default format is “YYYY-MM-DD”. Hence, December 8, 2020, in the date format will be presented as “2020-12-08”. The datetime format can be changed and by changing we mean changing the sequence and style of the format. 
strftime() can change the date format in python. 
Syntax:
strftime(format) 
Where, format is a string representing the type of required date format. 
For year %y 
For month %m
For day %d 
Import module
Provide date
Change the format using above function
Example
Python3
# importing pandas as pdimport pandas as pd  # Creating the date seriesdate_sr = pd.Series(pd.date_range(    '2019-12-31', periods=3, freq='M', tz='Asia/Calcutta'))  # Creating the indexind = ['Day 1', 'Day 2', 'Day 3']  # set the indexdate_sr.index = indchange_format = date_sr.dt.strftime('%d,%m,%Y')  # Print the formated dateprint(change_format)
Output
Example
Python3
# importing pandas as pdimport pandas as pd  # change in date time formatdate_sr = pd.to_datetime(pd.Series("2020-12-08"))change_format = date_sr.dt.strftime('%d/%m/%Y')  # Print the formated dateprint(change_format)
Output
Example
Python3
# importing pandas as pdimport pandas as pd  # change in date time formatdate_sr = pd.to_datetime(pd.Series("2012-09-02"))change_format = date_sr.dt.strftime('%d-%m-%Y')  # Print the formated dateprint(change_format)
Output
Python pandas-datetime
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Vim - Remote File Editing

Many times we need to work with remote servers. And often we edit files from those remote servers. One of the obvious solution to edit those files is to log in to the remote sever and edit files. But sometimes it is convenient to edit those files from local machine because we might have installed and configured various plug-in on our local system. In this chapter, we will discuss following items −
Access remote files
Understand netread and netwrite
Other supported protocol
Vim supports remote file editing using following syntax −
$vim scp://user@server.com/filepath

In above example vim will recognize that it has to use scp protocol and it will access file using that protocol. For instance −
$ vim scp://jarvis@remote-server.com//tmp/message.txt

Above command will open /tmp/message.txt file from remote-server. It will use SCP protocol and jarvis user’s credentials for authentication.
Vim supports nread and nwrite functionality which stands for net read and net write respectively. Previous section shows method to access remote file while launching Vim. But what if you are already in Vim? Then you can use following commands −
:Nread scp://jarvis@localhost//tmp/message.txt

In addition to reading we can also modify file on remote server directly. In that case use Nwrite command as follows −
:Nwrite scp://jarvis@localhost//tmp/message.txt

Once file is opened, you can use regular Vim commands.
In addition to SCP, Vim supports following protocols −
FTP
SFTP
HTTP (read-only)
rsync

    46 Lectures 
     5.5 hours 

 Jason Cannon
 Print
 Add Notes
 Bookmark this page
Calculate average values of two given NumPy arrays - GeeksforGeeks

20 Aug, 2020
Finding average of NumPy arrays is quite similar to finding average of given numbers. We just have to get the sum of corresponding array elements and then divide that sum with the total number of arrays.
Let’s see an example:
Example 1: Calculate average values of two given NumPy 1d-arrays
Python3
# import libraryimport numpy as np  #  create a numpy 1d-arraysarr1 = np.array([3, 4])arr2 = np.array([1, 0])  # find average of NumPy arraysavg = (arr1 + arr2) / 2  print("Average of NumPy arrays:\n",      avg)
Output:
Average of NumPy arrays:
 [2. 2.]
Example 2: Calculate average values of two given NumPy 2d-arrays
Python3
# import libraryimport numpy as np  #  create a numpy 2d-arraysarr1 = np.array([[3, 4], [8, 2]])arr2 = np.array([[1, 0], [6, 6]])  # find average of NumPy arraysavg = (arr1 + arr2) / 2  print("Average of NumPy arrays:\n",      avg)
Output:
Average of NumPy arrays:
 [[2. 2.]
 [7. 4.]]
Python numpy-Linear Algebra
Python-numpy
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python | pandas.to_markdown() in Pandas

22 Apr, 2020
With the help of pandas.to_markdown() method, we can get the markdown table from the given dataframes by using pandas.to_markdown() method.
Syntax : pandas.to_markdown()
Return : Return the markdown table.
Example #1 :In this example we can see that by using pandas.to_markdown() method, we are able to get the markdown table from the given dataframes by using this method.
# import pandasimport pandas as pd  df = pd.DataFrame({"A": [1, 2, 3],                   "B": [1.1, 2.2, 3.3]},                     index =['a', 'a', 'b'])  # Using pandas.to_markdown() methodgfg = df.to_markdown()  print(gfg)
Output :
|    |   A |   B |
|:---|----:|----:|
| a  |   1 | 1.1 |
| a  |   2 | 2.2 |
| b  |   3 | 3.3 |

Example #2 :
# import pandasimport pandas as pd  df = pd.DataFrame({"A": [3, 4, 5],                   "B": ['c', 'd', 'e']},                   index =['I', 'II', 'III'])  # Using pandas.to_markdown() methodgfg = df.to_markdown()  print(gfg)
Output :
|     |   A | B   |
|:----|----:|:----|
| I   |   3 | c   |
| II  |   4 | d   |
| III |   5 | e   |

Python pandas-dataFrame
Python pandas-dataFrame-methods
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Numpy ndarray.tobytes() function | Python

22 Apr, 2020
numpy.ndarray.tobytes() function construct Python bytes containing the raw data bytes in the array.
Syntax : numpy.ndarray.tobytes(order=’C’)
Parameters :order : [{‘C’, ‘F’, None}, optional] Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array.
Return : Python bytes exhibiting a copy of arr’s raw data.
Code #1 :
# Python program explaining# numpy.ndarray.tobytes() function  # importing numpy as geek import numpy as geek  arr = geek.array([[0, 1], [2, 3]], dtype ='<u2')  gfg = arr.tobytes()  print (gfg)
Output :
b'\x00\x00\x01\x00\x02\x00\x03\x00'

 Code #2 :
# Python program explaining# numpy.ndarray.tobytes() function  # importing numpy as geek import numpy as geek  arr = geek.array([[0, 1], [2, 3]], dtype ='<u2')  gfg = arr.tobytes('F')  print (gfg)
Output :
b'\x00\x00\x02\x00\x01\x00\x03\x00'

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
numpy.sinc() in Python

29 Nov, 2018
numpy.sinc(array) : This mathematical function helps user to calculate sinc function for all x(being the array elements).
Parameters :array : [array_like] elements are in radians. 2pi Radians = 36o degrees
Return :An array with sinc value of x for all x i.e. array elements.
Code #1 : Working
# Python3 program explaining # sinc() function import numpy as np import math   in_array = [0, math.pi / 2, np.pi / 3, np.pi] print ("Input array : \n", in_array)   sinc_Values = np.sinc(in_array) print ("\nSinc values : \n", sinc_Values) 
Output:
Input array : 
 [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

Sinc values : 
 [ 1.         -0.19765087 -0.04490537 -0.04359863]


 Code #2 : Graphical Representation
# Python program showing Graphical # representation of sinc() function import numpy as np import matplotlib.pyplot as plt   in_array = np.linspace(-np.pi, np.pi, 12) out_array = np.sinc(in_array)   print("in_array : ", in_array) print("\nout_array : ", out_array)   # red for numpy.sinc() plt.plot(in_array, out_array, color = 'red', marker = "o") plt.title("numpy.sinc()") plt.xlabel("X") plt.ylabel("Y")   plt.show() 
Output:
in_array :  [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798   -0.28559933
  0.28559933  0.856798    1.42799666  1.99919533  2.57039399  3.14159265]

out_array :  [-4.35986286e-02  1.20821077e-01 -4.02499006e-04 -2.17227951e-01
  1.61555129e-01  8.71125992e-01  8.71125992e-01  1.61555129e-01
 -2.17227951e-01 -4.02499006e-04  1.20821077e-01 -4.35986286e-02]



Python numpy-Mathematical Function
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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
VBA - UBound Function

The UBound Function returns the largest subscript of the specified array. Hence, this value corresponds to the size of the array.
UBound(ArrayName[,dimension])

ArrayName − A required parameter. This parameter corresponds to the name of the array.
ArrayName − A required parameter. This parameter corresponds to the name of the array.
Dimension − An optional parameter. This takes an integer value that corresponds to the dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on.
Dimension − An optional parameter. This takes an integer value that corresponds to the dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on.
Add a button and add the following function.
Private Sub Constant_demo_Click()
   Dim arr(5) as Variant
   arr(0) = "1"           'Number as String
   arr(1) = "VBScript     'String
   arr(2) = 100           'Number
   arr(3) = 2.45          'Decimal Number
   arr(4) = #10/07/2013#  'Date
   arr(5) = #12.45 PM#    'Time
   msgbox("The smallest Subscript value of  the given array is : " & UBound(arr))

   ' For MultiDimension Arrays :
   Dim arr2(3,2) as Variant
   msgbox("The smallest Subscript of the first dimension of arr2 is : " & UBound(arr2,1))
   msgbox("The smallest Subscript of the Second dimension of arr2 is : " & UBound(arr2,2))
End Sub
When you execute the above function, it produces the following output.
The smallest Subscript value of the given array is : 5
The smallest Subscript of the first dimension of arr2 is : 3
The smallest Subscript of the Second dimension of arr2 is : 2
authconfig - Unix, Linux Command

If --test action is specified, authconfig can be run by
users other then root, and any configuration changes are not saved but printed
instead.
If --update action is specified, authconfig must be run by
root (or through console helper), and configuration changes are saved.
The --probe action instructs authconfig to use DNS and other means
to guess at configuration information for the current host, print its guesses
if it finds them to standard output, and exit.


If --nostart is specified (which is what the install program does),
ypbind or other daemons will not be started or stopped immediately following
program execution, but only enabled to start or stop at boot time.


The --enablenis, --enableldap, --enablewinbind,
and --enablehesiod options
are used to configure user information services in /etc/nsswitch.conf,
the --enablecache option is used to configure naming services caching,
and the --enableshadow, --enablemd5, --enableldapauth,
--enablekrb5, --enablewinbindauth,
and --enablesmbauth options are used to configure
authentication functions via /etc/pam.d/system-auth.  Each
--enable has a matching --disable option that disables the service
if it is already enabled. The respective services have parameters which configure
their server names etc.


The algorithm used for storing new password hashes can be specified by
the --passalgo option which takes one of the following possible values as
a parameter: descrypt, bigcrypt, md5, sha256, and
sha512.


The --enablelocauthorize option allows to bypass checking network
authentication services for authorization and the --enablesysnetauth
allows authentication of system accounts (with uid < 500) by these services.


The list of options mentioned here in the manual page is not exhaustive, please
refer to authconfig --help for the complete list of the options.


The authconfig-tui supports all options of authconfig but it implies
--update as the default action. Its window contains a Cancel
button by default. If --back option is specified at run time, a Back
button is presented instead. If --kickstart is specified, no interactive
screens will be seen. The values the program will use will be those specified by
the other options (--passalgo, --enableshadow, etc.).


For namelist\R you may substitute either a single name or a
comma-separated list of names.




authconfig-tui returns 0 on success, 2 on error, and 1 if the user cancelled
the program (by using either the Cancel or Back button).







Nalin Dahyabhai <nalin@redhat.com>, Preston Brown <pbrown@redhat.com>,
Matt Wilson <msw@redhat.com>, Tomas Mraz <tmraz@redhat.com>
How to create Video Player in ReactJS ?

09 Nov, 2021
In this article, we are going to learn how we can create Video Player in ReactJS. A video player is a kind of media player for playing back digital video data.
React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To create our video player we are going to use the react-loading package because it is powerful, lightweight, and fully customizable. After that, we will add our video player to our homepage using the installed package.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the react-video-js-player package using the below command:
npm i react-video-js-player
Project Structure: It will look like this.
Adding Video Player: In this example, we are going to add the react-loading on the homepage of our app using the package that we installed. We are using the below image and video in the example.
Now add the below code in the App.js file to create the video player.
Javascript
import React, { Component } from 'react';import VideoPlayer from 'react-video-js-player';   class VideoApp extends Component {    player = {}    state = {        video: {            src: "/video.mp4",            poster: "/1.png"        }    }       onPlayerReady(player){        this.player = player;    }       render() {        return (            <div>                <VideoPlayer                    controls={true}                    src={this.state.video.src}                    poster={this.state.video.poster}                    width="720"                    height="420"                    onReady={this.onPlayerReady.bind(this)}                />            </div>        );    }}export default VideoApp;
Explanation: In the above example first, we are importing the VideoPlayer component from the react-video-js-player package. After that, we are creating our onPlayerReady and state function. Then we are adding our Video Player using the VideoPlayer component of the installed package.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use strptime with milliseconds in Python

23 Aug, 2021
strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : 
string that should be converted to datetime object
format string used to parse the string.
These two string arguments are mandatory for converting a string into DateTime object.
Syntax:
strptime(date_string, format_string)
List of Format codes:
08/16/88
08/16/1998
21:30:00
%% – A literal ‘%’ character.
To use this function to produce milliseconds in python %f is used in format code.
Given below are some implementations.
Example 1: Time with milliseconds
Python3
from datetime import datetime  datetime_string = "15/06/2021 13:30:15.120"  print(type(datetime_string))  format = "%d/%m/%Y %H:%M:%S.%f"  # converting datetime string to datetime # object with milliseconds..date_object = datetime.strptime(datetime_string, format)  print("date_object =", date_object)  # Type is datetime objectprint(type(date_object))
Output:
<class 'str'>
date_object = 2021-06-15 13:30:15.120000
<class 'datetime.datetime'>
Example 2: time with milliseconds
Python3
from datetime import datetime  # Getting current datetime and converting# it to stringdate_str = str(datetime.now())  print(type(date_str))  print(datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f'))
Output:
<class 'str'>
2021-08-01 15:27:59.979673
Example 3: time with milliseconds
Python3
from datetime import datetime  # Using strptime() with milliseconds  date_time = datetime.strptime(    "17 Oct 2021 15:48:35.525001", "%d %b %Y %H:%M:%S.%f")  print(date_time)
Output:
2021-10-17 15:48:35.525001
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to disable windows firewall profiles using PowerShell?

There are 3 types of profiles that firewall supports. a) Domain b) Public and c) Private profile. You can check the same settings using the GUI in the Windows Firewall Advanced Security settings window as shown below.
You can check the above settings using the Get-NetFirewallProfile command.
Get-NetFirewallProfile | Select Name, Enabled 
Name    Enabled 
----   ------- 
Domain  True 
Private True
Public  True
To turn off or disable the above profiles using PowerShell, you need to use the command Set-NetFirewallProfile.
To disable the specific profile, use -Profile parameter. You can pass 3 different profile names in this parameter (Domain, Public, and Private). For example,
Set-NetFirewallProfile -Profile Domain -Enabled False
To disable all the windows firewall profiles,
Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled False -Verbose
You can check the same with GUI or the first command mentioned in this article.
Get-NetFirewallProfile | Select Name, Enabled Name Enabled ---- ------- Domain False Private False Public False

To disable the settings on the remote computer, you need to use Invoke-Command or PSSession.
Invoke-Command -ComputerName RemoteServerName -ScriptBlock{ Set-NetFirewallProfile -Profile Domain, Private, Public -Enabled False}
Scikit Learn - MultiTaskElasticNet

It is an Elastic-Net model that allows to fit multiple regression problems jointly enforcing the selected features to be same for all the regression problems, also called tasks. Sklearn provides a linear model named MultiTaskElasticNet, trained with a mixed L1, L2-norm and L2 for regularisation, which estimates sparse coefficients for multiple regression problems jointly. In this, the response y is a 2D array of shape (n_samples, n_tasks).
Following is the objective function to minimize −
As in MultiTaskLasso, here also, Fro indicates the Frobenius norm −
And L1L2 leads to the following −
The parameters and the attributes for MultiTaskElasticNet are like that of ElasticNet. The only difference is in li_ratio i.e. ElasticNet mixing parameter. In MultiTaskElasticNet its range is 0 < l1_ratio < = 1. If l1_ratio = 1, the penalty would be L1/L2 penalty. If l1_ratio = 0, the penalty would be an L2 penalty. If the value of l1 ratio is between 0 and 1, the penalty would be the combination of L1/L2 and L2.
And, opposite to ElasticNet, MultiTaskElasticNet doesn’t have precompute attribute.
To show the difference, we are implementing the same example as we did in Multi-task Lasso −
from sklearn import linear_model
MTENReg = linear_model.MultiTaskElasticNet(alpha = 0.5)
MTENReg.fit([[0,0], [1, 1], [2, 2]], [[0, 0],[1,1],[2,2]])
Output
MultiTaskElasticNet(alpha = 0.5, copy_X = True, fit_intercept = True, l1_ratio = 0.5,
max_iter = 1000, normalize = False, random_state = None,
selection = 'cyclic', tol = 0.0001, warm_start = False)

Example
#Predicting new values
MTENReg.predict([[1,0]])
Output
array([[0.69056563, 0.69056563]])

Example
#weight vectors
MTENReg.coef_
Output
array([[0.30943437, 0.30938224],
[0.30943437, 0.30938224]])

Example
#Calculating intercept
MTENReg.intercept_
Output
array([0.38118338, 0.38118338])

Example
#Calculating number of iterations
MTENReg.n_iter_
Output
15


    11 Lectures 
     2 hours 

 PARTHA MAJUMDAR
 Print
 Add Notes
 Bookmark this page
Print powers using Anonymous Function in Python

30 Nov, 2017
Prerequisite : Anonymous function
In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name.While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.Syntax:
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returnedExample:
Input : ('The total terms is:', 10)

Output :
('2 raised to power', 0, 'is', 1)
('2 raised to power', 1, 'is', 2)
('2 raised to power', 2, 'is', 4)
('2 raised to power', 3, 'is', 8)
('2 raised to power', 4, 'is', 16)
('2 raised to power', 5, 'is', 32)
('2 raised to power', 6, 'is', 64)
('2 raised to power', 7, 'is', 128)
('2 raised to power', 8, 'is', 256)
('2 raised to power', 9, 'is', 512)

# Python Program to display the powers # of 2 using anonymous function  # Change this value for a different resultterms = 10  # Uncomment to take number of terms from user# terms = int(input("How many terms? "))  # use anonymous functionresult = list(map(lambda x: 2 ** x, range(terms)))  # display the resultprint("The total terms is:", terms)for i in range(terms):   print("2 raised to power", i, "is", result[i])
Output:
('The total terms is:', 10)
('2 raised to power', 0, 'is', 1)
('2 raised to power', 1, 'is', 2)
('2 raised to power', 2, 'is', 4)
('2 raised to power', 3, 'is', 8)
('2 raised to power', 4, 'is', 16)
('2 raised to power', 5, 'is', 32)
('2 raised to power', 6, 'is', 64)
('2 raised to power', 7, 'is', 128)
('2 raised to power', 8, 'is', 256)
('2 raised to power', 9, 'is', 512)

Mathematical
Python
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe