code-rag-bench/online-tutorials huggingface dataset:
Python Program for Product of unique prime factors of a number

03 Dec, 2018
Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself.
Examples:
Input: num = 10
Output: Product is 10
Explanation:
Here, the input number is 10 having only 2 prime factors and they are 5 and 2.
And hence their product is 10.

Input : num = 25
Output: Product is 5
Explanation:
Here, for the input to be 25  we have only one unique prime factor i.e 5.
And hence the required product is 5.

Method 1 (Simple)Using a loop from i = 2 to n and check if i is a factor of n then check if i is prime number itself if yes then store product in product variable and continue this process till i = n.
# Python program to find sum of given# series.  def productPrimeFactors(n):    product = 1          for i in range(2, n+1):        if (n % i == 0):            isPrime = 1                          for j in range(2, int(i/2 + 1)):                if (i % j == 0):                    isPrime = 0                    break                              # condition if \'i\' is Prime number            # as well as factor of num            if (isPrime):                product = product * i                      return product                    # main()n = 44print (productPrimeFactors(n))  # Contributed by _omg
Output:
22

Method 2 (Efficient) :The idea is based on Efficient program to print all prime factors of a given number
# Python program to find product of # unique prime factors of a number  import math  def productPrimeFactors(n):    product = 1          # Handle prime factor 2 explicitly so that    # can optimally handle other prime factors.    if (n % 2 == 0):        product *= 2        while (n%2 == 0):            n = n/2                  # n must be odd at this point. So we can    # skip one element (Note i = i +2)    for i in range (3, int(math.sqrt(n)), 2):        # While i divides n, print i and        # divide n        if (n % i == 0):            product = product * i            while (n%i == 0):                n = n/i                      # This condition is to handle the case when n    # is a prime number greater than 2    if (n > 2):        product = product * n              return product           # main()n = 44print (int(productPrimeFactors(n)))  # Contributed by _omg
Output:
22

Please refer complete article on Product of unique prime factors of a number for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python
Start/Stop/Restart Services Using Systemctl in Linux

11 Feb, 2021
Systemctl is a controller or utility of Systemd(is an init system with compost for a set of programs executed in the background), with auxiliary in manage services, these commands are executed in mode root if you aren’t mode root the system, requesting the password of root.
systemctl list-unit-files --type service -all
Syntax:
sudo systemctl start service.service
The command start serves for starting (activate) one or more units specified on the command line.
Example:
sudo systemctl start mariadb
Command Start
Syntax:
sudo systemctl stop service.service
The command stop serves for stopping the service or (deactivate) one or more units specified on the command line.
Example:
sudo systemctl stop mariadb
Command Stop and Status
Syntax:
sudo systemctl status service.service
The command status serves to check the status of the service. Show terse runtime status information about one or more units, followed by the most recent log data from the journal. If no units are specified, show system status.
Example:
sudo systemctl status mariadb
Command Status
Syntax:
sudo systemctl restart service.service
The command restart serves for restarting the service in execution. Stop and then start one or more units specified on the command line. If the units are not running yet, they will be started.
Example:
sudo systemctl restart mariadb
Command Restart
Syntax:
sudo systemctl enable name_service.service
The enable command serves for executing the service since the initialization if consists of one or more units or unit instances. This will create a set of symlinks, as encoded in the [Install] sections of the indicated unit files. the system manager configuration is reloaded (in a way equivalent to daemon-reload), in order to ensure the changes are taken into account immediately. 
Example
sudo systemctl enable mariadb
Command Enable
Command Status
Syntax:
sudo systemctl disable name_service.service
The disable command serves for withdrawing the service since the initialization of one or more units. This removes all symlinks to the unit files backing the specified units from the unit configuration directory and hence undoes any changes made by enabling or link.
Example:
sudo systemctl disable mariadb
Command Disable
Command Status
Linux-Tools
Picked
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enable In-Built Dark Mode on Windows 10

06 Jun, 2022
Most of us love to surf our desktop and apps through dark mode as it will reduce our eye strain and resultantly makes us more productive But many of us do not know how to enable dark mode on a Windows system. Windows 10 comes with the dark mode inbuilt. This can be achieved through the settings menu and it applies a dark theme to apps you get from the Windows Store.
To enable dark mode in your Windows machine follow the below steps:
Step 1: Navigate to your settings and click on personalization.
Click on personalization
Step 2: Click on Colors.
Click on Colors
Step 3: Now choose your color and set it as dark to enable dark mode.
Enabling Dark Mode
At this stage, the system sets itself into the Dark Mode. A simple before and after image from the Dark Mode is depicted below:
The PC before enabling Dark Mode.
Normal Mode
The PC after enabling Dark Mode.
Dark Mode
sumitgumber28
Technical Scripter 2020
How To
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
YEAR() Function in SQL Server - GeeksforGeeks

11 Jan, 2021
YEAR() function :This function in SQL Server is used to return the year for a date stated.
Features :
This function is used to find the year for a date specified.
This function comes under Date Functions.
This function accepts only one parameter i.e, date.
This function can also include time with the stated date.
Syntax :
YEAR(date)
Parameter :This method accepts only one parameter as given below :
date : Specified date from which the year is to be returned.
Returns :It returns the year for a date specified.
Example-1 :Using YEAR() function and getting the year from the date specified.
SELECT YEAR('2020/01/02');
Output :
2020
Example-2 :Using YEAR() function with a variable and getting the year from the date specified.
DECLARE @date VARCHAR(50);
SET @date = '2017/07/05';
SELECT YEAR(@date);
Output :
2017
Example-3 :Using YEAR() function with date as parameter which includes time as well.
SELECT YEAR('2018/11/22 07:44');
Output :
2018
Example-4 :Using YEAR() function with a variable and a date as parameter which includes time as well.
DECLARE @date VARCHAR(50);
SET @date = '1995/05/13 23:59';
SELECT YEAR(@date);
Output :
1995
Application :This function is used to find the year from a date specified.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | DROP, TRUNCATE
How to Select Data Between Two Dates and Times in SQL Server?
SQL vs NoSQL: Which one is better to use?
Advanced SQL Interview Questions
SQL | OFFSET-FETCH Clause
Insert multiple values into multiple tables using a single statement in SQL Server
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Comments
SQL | CREATE
Adding multiple constraints in a single table
How to implement MAX(distinct...) in MySQL and what is the difference without using DISTINCT?

Let us see the first syntax, which uses DISTINCT in MAX() −
select max(DISTINCT yourColumnName) from yourTableName;
The second syntax is as follows. It isn’t using DISTINCT −
select max( yourColumnName) from yourTableName;
NOTE − Both the above queries give the same result with or without a DISTINCT keyword. MySQL internally converts MAX(yourColumnName) to DISTINCT keyword.
Let us now see an example and create a table −
mysql> create table DemoTable
(
   Number int
);
Query OK, 0 rows affected (1.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(68);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+
| Number |
+--------+
|     80 |
|     88 |
|     78 |
|     88 |
|     68 |
|     88 |
+--------+
6 rows in set (0.00 sec)
CASE 1 − Following is the query to implement MAX(DISTINCT..) −
mysql> select max(DISTINCT Number) from DemoTable;
This will produce the following output −
+----------------------+
| max(DISTINCT Number) |
+----------------------+
|                   88 |
+----------------------+
1 row in set (0.00 sec)
CASE 2 − Following is the query to implement MAX() without DISTINCT −
mysql> select max(Number) from DemoTable;
This will produce the following output −
+-------------+
| max(Number) |
+-------------+
|          88 |
+-------------+
1 row in set (0.07 sec)
As you can see above, both of them give the same result.
groupadd- Unix, Linux Command

groupadd - Creates a new group.
groupadd [options] group
 groupadd command creates a new group account using the values specified on the command line and the default values from the system. The new group will be entered into the system files as needed.
The numeric identifiers of new system groups are choosen in the SYS_GID_MIN-SYS_GID_MAX range, defined in login.defs, instead of GID_MIN-GID_MAX.
Example: -K GID_MIN=100 -K GID_MAX=499


Note: -K GID_MIN=10,GID_MAX=499 doesn't work yet.
Example-1:
This example would create a new group called "newgroup".
# groupadd newgroup
output:
to verify greoup created , search in /etc/group
# grep test /etc/grouptest:x:1002:
Example-2:
To create new group with specific groupid
#  groupadd -g 9090 newgroup
output:
# grep newgroup /etc/groupnewgroup:x:9090:
Example-3:
To create group in user defined range ( not range from system i.e /etc/login.defs)
# groupadd newgroup -K GID_MIN=8888 -K GID_MAX=9999
output:
# grep newgroup /etc/groupnewgroup:x:9091:

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Priority of AND and OR operator in MySQL select query?

The AND has the highest priority than the OR operator in MySQL select query.
Let us check how MySQL gives the highest priority to AND operator.
The query is as follows
mysql> select 0 AND 0 OR 1 as Result;
The following is the output
+--------+
| Result |
+--------+
| 1     |
+--------+
1 row in set (0.00 sec)
If you are considering the OR operator has the highest priority then MySQL will wrap up the above query like this.
The query is as follows
select 0 AND (0 OR 1) as Result
First, solve the 0 OR 1, this will give result 1. After that 0 and 1 will give the result 0.
But the above case is not fine because we are getting 0 and the output is 1. So, in the above query, AND gets the highest priority than OR to get result 1.
The query is as follows
select 0 AND 0 OR 1 as Result
First, solve AND operator first. 0 AND 0 give result 0.
After that 0 OR 1 gives result 1.
Now we are getting the exact output.
volatile Keyword in Java

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory.
Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.
public class MyRunnable implements Runnable {
   private volatile boolean active;
   public void run() {
      active = true;
      while (active) {
      }
   }
   public void stop() {
      active = false;
   }
}
C++ String Library - rfind

It searches the string for the last occurrence of the sequence specified by its arguments.
Following is the declaration for std::string::rfind.
size_t rfind (const string& str, size_t pos = npos) const;
size_t rfind (const string& str, size_t pos = npos) const noexcept;
size_t rfind (const string& str, size_t pos = npos) const noexcept;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::rfind.
#include <iostream>
#include <string>
#include <cstddef>

int main () {
   std::string str ("sairamkrishna mammahe is a one of the tech person in tutorialspoint.com");
   std::string key ("mammahe");

   std::size_t found = str.rfind(key);
   if (found!=std::string::npos)
      str.replace (found,key.length(),"tech");

   std::cout << str << '\n';

   return 0;
}
The sample output should be like this −
sairamkrishna tech is a one of the tech person in tutorialspoint.com

 Print
 Add Notes
 Bookmark this page
How to create canvas line using Fabric.js ? - GeeksforGeeks

16 Jul, 2021
In this article, we are going to see how to create a canvas line using FabricJS. The canvas line means the line is movable and can be stretched according to your requirements. Further, the line can be customized when it comes to initial stroke color and its starting and ending coordinates.Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our line. After this, we will initialize instances of Canvas and Line provided by FabricJS and render the Line instance on the Canvas instance as given in the example below.Syntax:  
fabric.Line(points, options); 
Parameters: This function accepts two parameters as mentioned above and described below:  
points: It specifies the starting and ending coordinates of the line which are in the sequence like start x-coordinate, start y-coordinate, end x-coordinate and end y-coordinate.
options: It specifies the additional options to be applied.
Example: We can use FabricJS to create simple editable canvas line. 
html
<!DOCTYPE html><html>  <head>    <title>        How to create canvas        line using Fabric.js?    </title>         <!-- Loading the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head>  <body>    <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000;">    </canvas>         <script>                 // Initiate a Canvas instance        var canvas = new fabric.Canvas("canvas");          // Initiate a line instance        var line = new fabric.Line([50, 10, 200, 150], {            stroke: 'green'        });          // Render the rectangle in canvas        canvas.add(line);    </script></body> </html>
sagar0719kumar
Fabric.js
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to convert LinkedList to Array in Java? - GeeksforGeeks

11 Dec, 2018
Given a Linked List in Java, the task is to convert this LinkedList to Array.
Examples:
Input: LinkedList: ['G', 'e', 'e', 'k', 's'] 
Output: Array: ['G', 'e', 'e', 'k', 's'] 

Input: LinkedList: [1, 2, 3, 4, 5]
Output: Array: [1, 2, 3, 4, 5] 

Approach:
Get the LinkedListConvert the LinkedList to Object array using toArray() method.Convert the Object array to desired type array using Arrays.copyOf() method.Return the print the Array
Get the LinkedList
Convert the LinkedList to Object array using toArray() method.
Convert the Object array to desired type array using Arrays.copyOf() method.
Return the print the Array
Below is the implementation of the above approach:
// Java program to convert// LinkedList to Array  import java.util.*;  public class GFG {      // Function to convert LinkedList to Array    public static <T> Object[] convertLinkedListToArray(LinkedList<T> linkedList)    {          // Converting LinkedList to Array        Object[] array = linkedList.toArray();          return array;    }      public static void main(String args[])    {        // Creating linked list        LinkedList<String>            linkedList = new LinkedList<String>();          // Adding elements to the linked list        linkedList.add("G");        linkedList.add("e");        linkedList.add("e");        linkedList.add("k");        linkedList.add("s");          // Print the LinkedList        System.out.println("Linked list: "                           + linkedList);          // Converting LinkedList to Object Array        Object[] objArray = convertLinkedListToArray(linkedList);          // Convert Object[] to String[]        String[] array = Arrays.copyOf(objArray,                                       objArray.length,                                       String[].class);        // Print the String Array        System.out.println("Array: "                           + Arrays.toString(array));    }}
Linked list: [G, e, e, k, s]
Array: [G, e, e, k, s]

Java-Array-Programs
Java-Arrays
Java-Collections
java-LinkedList
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
How to iterate any Map in Java
What are recursive stored procedures and why MySQL limits the recursion?

A stored procedure is called recursive if it calls itself. Basically, this concept is called recursion. MySQL limits the recursion so the errors will be less rigorous. We can check this limit with the help of the following query −
mysql> Show variables LIKE '%recur%';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| max_sp_recursion_depth |   0   |
+------------------------+-------+
1 row in set (0.01 sec)
We can change this value up to 255 with the help of the following query −
mysql> SET @@GLOBAL.max_sp_recursion_depth = 255//
Query OK, 0 rows affected (0.00 sec)

mysql> Show variables LIKE '%recur%'//
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| max_sp_recursion_depth | 255   |
+------------------------+-------+
1 row in set (0.01 sec)
The limit can be extended while writing the procedure also.
How to clear screen using C#?

Use the Console.Clear() method to clear screen and the console buffer. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window.
Here, we have cleared the screen and then set the ForegroundColor and BackgroundColor −
ConsoleColor newForeColor = ConsoleColor.Blue;
ConsoleColor newBackColor = ConsoleColor.Yellow;
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      ConsoleColor foreColor = Console.ForegroundColor;
      ConsoleColor backColor = Console.BackgroundColor;
      Console.WriteLine("Clearing the screen!");
      Console.Clear();
      ConsoleColor newForeColor = ConsoleColor.Blue;
      ConsoleColor newBackColor = ConsoleColor.Yellow;
   }
}
Clearing the screen!
Python | Pandas Timestamp.now

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.now() function return the current time in the local timezone. It is Equivalent to datetime.now([tz]).
Syntax :Timestamp.now()
Parameters : None
Return : Timestamp
Example #1: Use Timestamp.now() function to return the current time in the local timezone.
# 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.now() function to find the current time in the local timezone.
# return the current timets.now()
Output :
As we can see in the output, the Timestamp.now() function has returned the current time in the local timezone. It auto detects the local timezone. Example #2: Use Timestamp.now() function to return the current time in the local timezone.
# 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.now() function to find the current time in the local timezone.
# return the current timets.now()
Output :
As we can see in the output, the Timestamp.now() function has returned the current time in the local timezone. It auto detects the local timezone.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to scrape Comment using Beautifulsoup in Python?

29 Dec, 2020
Comments are provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The Comment object is just a special type of NavigableString and is used to make the codebase more readable.
Syntax: 
<!-- COMMENT --> 

Below given examples explain the concept of comments in Beautiful Soup. Example 1: In this example, we are going to create a comment.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Create the documentdoc = "<b><!-- COMMENT --></b>"  # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser")  # Get the whole comment inside b tagcomment = soup.b  # Print the commentprint(comment)
Output: 
<b><!-- COMMENT --></b>

Example 2: In this example, we are going to create a comment and see its type.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Create the documentdoc = "<b><!-- COMMENT --></b>"  # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser")  # Get the whole comment inside b tagcomment = soup.b.string  # Print the type of the commentprint(type(comment))
Output: 
<class 'bs4.element.Comment'> 

Python web-scraping-exercises
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?

02 Dec, 2021
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE.
Prerequisite: Make sure you have installed Java Development Kit (JDK) version 8 or newer. To check simply go to the terminal and enter the below command to check if it is present or not.
javac -version
Procedure: These are steps to be followed sequentially which are discussed further with visual aids as listed:
Download SpringToolSuite as per the operating system to the local machine.Move the downloaded JAR file to the corresponding folder.Unzip this JAR file and open the corresponding folder.Click on the SpringToolSuite4 Application fileSelect the directory representing workspace and press the ‘LAUNCH’ button.
Download SpringToolSuite as per the operating system to the local machine.
Move the downloaded JAR file to the corresponding folder.
Unzip this JAR file and open the corresponding folder.
Click on the SpringToolSuite4 Application file
Select the directory representing workspace and press the ‘LAUNCH’ button.
Step 1: Go to their website and in Spring Tools 4 for the Eclipse section in order to download. choose your corresponding file according to your OS. 
Here we are going with Windows operating systems so do we have chosen Windows option as seen in the below image. 
Step 2: After clicking on the button a Jar file will be downloaded to your local system. Now create a folder and move this Jar file to that folder. And double-click on that Jar file. A pop-up window will appear like this. 
Step 3: After successfully Unpacking a new folder will create as shown in the below image. Now open the folder. 
Step 4: In this folder now click on the SpringToolSuite4 Application file as shown in the below image. 
Step 5: Now select your directory as workspace by clicking on the Browse button and then click on the Launch button. And you are done. 
This is the Home screen for Spring Tool Suite (Spring Tools 4 for Eclipse) IDE
sweetyty
Java-Spring
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
Matplotlib.axes.Axes.set_yscale() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_yscale() function in axes module of matplotlib library is used to set the y-axis scale.
Syntax: Axes.set_xscale(self, value, **kwargs)
Parameters: This method accepts the following parameters.
value : This parameter is the axis scale type to apply.
**kwargs: There are different keyword arguments which are accepted and its depend on the scale.
Below examples illustrate the matplotlib.axes.Axes.set_yscale() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()  ax.set_yscale("log")ax.set_adjustable("datalim")ax.plot([1, 3, 10], [1, 9, 100], "o-",        color ="green")  ax.set_ylim(1e-1, 1e3)ax.set_aspect(1)fig.suptitle('matplotlib.axes.Axes.set_yscale()\ function Example\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt    fig, ax4 = plt.subplots()  x = 10.0**np.linspace(0.0, 2.0, 15)y = x**2.0ax4.set_xscale("log", nonposx ='clip')ax4.set_yscale("log", nonposy ='clip')  ax4.errorbar(x, y, xerr = 0.1 * x,             yerr = 2.0 + 1.75 * y,             color ="green")  ax4.set_ylim(bottom = 0.1)  fig.suptitle('matplotlib.axes.Axes.set_yscale() \function Example\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How to shuffle a dataframe in R by rows

14 Sep, 2021
In this article, we will discuss how to shuffle a dataframe by rows in the R programming language.
Shuffling means reordering or rearranging the data. We can shuffle the rows in the dataframe by using sample() function. By providing indexing to the dataframe the required task can be easily achieved.
Syntax:
 dataframe[sample(1:nrow(dataframe)), ]
Where.
dataframe is the input dataframe
sample() function is used to shuffle the rows that takes a parameter with a function called nrow() with a slice operator to get all rows shuffled.
nrow() is sued to get all rows by taking the input parameter as a dataframe
Example: R program to create a dataframe with 3 columns and 6 rows and shuffle the dataframe by rows
R
# create a dataframe of students with id,name and marksdata=data.frame(id=c(1,2,3,4,5,6),                name=c("sravan","bobby","ojaswi","gnanesh",                       "rohith","satwik"),                marks=c(89,90,98,78,98,78))  # display dataframeprint(data)print("_______________________________________________________")  # shuffle the dataframe by rowsshuffled_data= data[sample(1:nrow(data)), ]  # displayprint(shuffled_data)
Output:
Example: R program to create a student dataframe with 2 columns and 3 rows
R
# create a dataframe of students with id,namedata = data.frame(id=c(1, 2, 3), name=c(  "sravan", "bobby", "ojaswi"))  # display dataframeprint(data)print("_______________________________________________________")  # shuffle the dataframe by rowsshuffled_data = data[sample(1:nrow(data)), ]  # displayprint(shuffled_data)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
How to fetch single and multiple documents from MongoDb using Node.js ?

20 Nov, 2020
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). Refer (this) article.
MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. (Refer to this article). We can also use promises, in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject the error occurs during connection.
Installing module:
node install mongodb

Project Structure:
Running the server on Local IP: data is folder name
mongod --dbpath=data --bind_ip 127.0.0.1

MongoDB Database:
Database:GFG
Collection:GFGcollections

Index.js
1. Fetching single document of GFGcollections
Javascript
const MongoClient = require("mongodb");const url = 'mongodb://localhost:27017/';const databasename = "GFG";  // Database nameMongoClient.connect(url).then((client) => {      const connect = client.db(databasename);      // Connect to collection    const collection = connect            .collection("GFGcollections");      // Fetching the records having     // name as saini    collection.find({ "name": "saini" })        .toArray().then((ans) => {            console.log(ans);        });}).catch((err) => {      // Printing the error message    console.log(err.Message);})
Output:
2. Fetching all documents of the GFGcollections
Javascript
const MongoClient = require("mongodb");const url = 'mongodb://localhost:27017/';const databasename = "GFG";  // Database nameMongoClient.connect(url).then((client) => {      const connect = client.db(databasename);      // Connect to collection    const collection = connect        .collection("GFGcollections");      collection.find({}).toArray().then((ans) => {        console.log(ans);    });}).catch((err) => {      // Printing the error message    console.log(err.Message);})
Output:
Node.js-Misc
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to Construct Transitive Closure Using Warshall’s Algorithm

If a directed graph is given, determine if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Reachable mean that there is a path from vertex i to j. This reach-ability matrix is called transitive closure of a graph. Warshall algorithm is commonly used to find the Transitive Closure of a given graph G. Here is a C++ program to implement this algorithm.
Begin
   1.Take maximum number of nodes as input.
   2.For Label the nodes as a, b, c .....
   3.To check if there any edge present between the nodes make a for loop:
      for i = 97 to less than 97 + number of nodes
         for j = 97 to less than 97 + number of nodes
            if edge is present do,
               adj[i - 97][j - 97] = 1
            else
               adj[i - 97][j - 97] = 0
            end loop
      end loop.
   4.To print the transitive closure of graph:
      for i = 0 to number of nodes
         c = 97 + i
      end loop.
      for i = 0 to number of nodes
         c = 97 + i;
      for j = 0 to n_nodes
         print adj[I][j]
      end loop
   end loop
End
#include<iostream>
using namespace std;
const int n_nodes = 20;
int main() {
   int n_nodes, k, n;
   char i, j, res, c;
   int adj[10][10], path[10][10];
   cout << "\n\tMaximum number of nodes in the graph :";
   cin >>n;
   n_nodes = n;
   cout << "\nEnter 'y' for 'YES' and 'n' for 'NO' \n";
   for (i = 97; i < 97 + n_nodes; i++)
      for (j = 97; j < 97 + n_nodes; j++) {
         cout << "\n\tIs there an edge from " << i << " to " << j << " ? ";
         cin >>res;
         if (res == 'y')
            adj[i - 97][j - 97] = 1;
         else
            adj[i - 97][j - 97] = 0;
      }
      cout << "\nTransitive Closure of the Graph:\n";
      cout << "\n\t\t\t ";
      for (i = 0; i < n_nodes; i++) {
         c = 97 + i;
         cout << c << " ";
      }
      cout << "\n\n";
      for (int i = 0; i < n_nodes; i++) {
         c = 97 + i;
         cout << "\t\t\t" << c << " ";
         for (int j = 0; j < n_nodes; j++)
            cout << adj[i][j] << " ";
            cout << "\n";
      }
      return 0;
}
Maximum number of nodes in the graph :4
Enter 'y' for 'YES' and 'n' for 'NO'

Is there an edge from a to a ? y
Is there an edge from a to b ?y
Is there an edge from a to c ? n
Is there an edge from a to d ? n
Is there an edge from b to a ? y
Is there an edge from b to b ? n
Is there an edge from b to c ? y
Is there an edge from b to d ? n
Is there an edge from c to a ? y
Is there an edge from c to b ? n
Is there an edge from c to c ? n
Is there an edge from c to d ? n
Is there an edge from d to a ? y
Is there an edge from d to b ? n
Is there an edge from d to c ? y
Is there an edge from d to d ? n
Transitive Closure of the Graph:

a b c d

a 1 1 0 0
b 1 0 1 0
c 1 0 0 0
d 1 0 1 0
PHP - json_decode() Function

The json_decode() function can decode a JSON string. 
mixed json_decode( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

The json_decode() function can take a JSON encoded string and convert into a PHP variable. 
The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.
<?php 
   $jsonData= '[
                  {"name":"Raja", "city":"Hyderabad", "state":"Telangana"}, 
                  {"name":"Adithya", "city":"Pune", "state":"Maharastra"},
                  {"name":"Jai", "city":"Secunderabad", "state":"Telangana"}
               ]';

   $people= json_decode($jsonData, true);
   $count= count($people);

   // Access any person who lives in Telangana
   for ($i=0; $i < $count; $i++) { 
      if($people[$i]["state"] == "Telangana") {
         echo $people[$i]["name"] . "\n";
         echo $people[$i]["city"] . "\n";
         echo $people[$i]["state"] . "\n\n";
      }
   }
?>
Raja
Hyderabad
Telangana

Jai
Secunderabad
Telangana

<?php
   // Assign a JSON object to a variable
   $someJSON = '{"name" : "Raja", "Adithya" : "Jai"}';
 
   // Convert the JSON to an associative array
   $someArray = json_decode($someJSON, true);
 
   // Read the elements of the associative array
   foreach($someArray as $key => $value) {
      echo "[" . $key . "][" . $value . "]";
   }
?>
[name][Raja][Adithya][Jai]


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
p5.js | loop() Function - GeeksforGeeks

17 Jan, 2020
The loop() function is an inbuilt function in p5.js library. This function is used to play the audio on the web in a loop. The loop function can call after or before the play() function, it does not matter. It will play that loaded sound again and again in a loop.
Syntax:
loop( startTime, rate, amp, cueStart, duration )
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.
Parameter: This function accepts five parameters as mentioned above and described below:
startTime: This parameter holds an integer number as seconds that defines the scheduled playback and it is an optional parameter.
rate: This parameter holds an integer number that defines playback rate and it is an optional parameter.
amp: This parameter holds an integer number that defines the amplitude of the playback and it is an optional parameter.
cueStart: This parameter holds an integer number as seconds that define the cue start time in seconds and it is an optional parameter.
duration: This parameter holds an integer number that defines the duration of playback in seconds and it is an optional parameter.
Below given example illustrate the p5.js loop() function in JavaScript:Example:
var sound;   function preload() {       // Initialize sound     sound = loadSound("pfivesound.mp3"); }   function setup() {       // Playing the preloaded sound in a loop    sound.play();     sound.loop();} 
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Supported Browsers: The browsers supported by p5.js loop() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
PHP switch Statement

The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks 
of code to be executed.
This is how it works: First we have a single expression n (most often a
variable), that is evaluated once. The value of the expression is then compared
with the values for each case in the structure. If there is a match, the block
of code associated with that case is executed. Use break to prevent the
code from running into the next case automatically. The default statement is used if no 
match is found.
Create a switch statement that will output "Hello"
if $color is "red", and "welcome"
if $color is "green".
 ($color) {
   "red":
    echo "Hello";
    break;
   "green":
    echo "Welcome";
    break;
}

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Automatically Rescale ylim and xlim in Matplotlib

To rescale ylim and xlim automatically, we can take the following steps −
To plot a line, use plot() method and data range from 0 to 10.
To plot a line, use plot() method and data range from 0 to 10.
To scale the xlim and ylim automatically, we can make the variable scale_factore=6.
To scale the xlim and ylim automatically, we can make the variable scale_factore=6.
Use scale_factor (from Step 2) to rescale the xlim and ylim, using xlim() and ylim() methods, respectively.
Use scale_factor (from Step 2) to rescale the xlim and ylim, using xlim() and ylim() methods, respectively.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.plot(range(0, 10))
scale_factor = 6
xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
plt.xlim(xmin * scale_factor, xmax * scale_factor)
plt.ylim(ymin * scale_factor, ymax * scale_factor)
plt.show()
OCR of English alphabets in Python OpenCV - GeeksforGeeks

15 Sep, 2021
OCR which stands for Optical character recognition is a computer vision technique used to recognize characters such as digits, alphabets, signs, etc. These characters are common in day-to-day life and we can perform character recognition based on our requirements. We will implement optical character recognition of the English alphabets using OpenCV. here we will use the KNN algorithm which is used for classification. 
Note: You can find the data here data for which we will perform the OCR. 
There are 20000 rows of data containing 17 columns where the first column represents the alphabet and the remaining 16 will represent its different features. We have to process the data by converting the alphabets into ASCII characters. To perform classification we will use 10000 rows as training_data and 10000 row as testing_data.
Below is the implementation. 
Python3
#Import the librariesimport cv2 as cvimport numpy as np   # Read data and use converters# to convert the alphabets to# Numeric value.data= np.loadtxt('letter-recognition',                 dtype= 'float32',                 delimiter = ',',                 converters= {0: lambda ch: ord(ch)-ord('A')}) # split the data into train_data# and test_datatrain_data, test_data = np.vsplit(data,2)  # split train_data and test_data# to features and responses.responses, training = np.hsplit(train_data,[1])classes, testing = np.hsplit(test_data,[1])  # Create the knn classifierknn = cv.ml.KNearest_create()knn.train(training, cv.ml.ROW_SAMPLE, responses)  # Obtain the results of the classifier# determine the number of neighbors.ret, Output, neighbours,distance = knn.findNearest(testing, k=7)  # Match the Output to find the# number of wrong predictions.correct_OP = np.count_nonzero(Output == classes)  #calculate accuracy and display it.accuracy = (correct_OP*100.0)/(10000)print( accuracy )
Output 
92.82
 
sumitgumber28
Python-OpenCV
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 ?
Selecting rows in pandas DataFrame based on conditions
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
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()