code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas DatetimeIndex.dayofyear - GeeksforGeeks

24 Dec, 2018
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 DatetimeIndex.dayofyear attribute outputs the ordinal value of the day of the year for each entries of the DatetimeIndex object.
Syntax: DatetimeIndex.dayofyear
Return: Index object
Example #1: Use DatetimeIndex.dayofyear attribute to find the ordinal value of the day of the year for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'W' represents Weekly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='W',                             periods = 3, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find ordinal value of day for each entries in the DatetimeIndex object.
# find the ordinal value of the day # for each entries present in the objectdidx.dayofyear
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the days present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.dayofyear attribute to find the ordinal value of the day of the year for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'M' represents Monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M',                               periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :Now we want to find ordinal value of day for each entries in the DatetimeIndex object.
# find the ordinal value of the day # for each entries present in the objectdidx.dayofyear
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the days present in each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Plot data from CSV file with Matplotlib

To extract CSV file for specific columns to list in python, we can use Pandas read_csv() method.
Make a list of columns that have to be extracted.
Use read_csv() method to extract the CSV file data into a data frame.
Print the exracted data.
Plot the data frame using plot() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ["Name", "Marks"]
df = pd.read_csv("input.csv", usecols=columns)
print("Contents in csv file:\n", df)
plt.plot(df.Name, df.Marks)
plt.show()
How can we simulate the MySQL MINUS query?

Since we cannot use the MINUS query in MySQL, we will use JOIN to simulate the MINUS query. It can be understood with the help of the following example −
In this example, we are two tables namely Student_detail and Student_info having the following data −
mysql> Select * from Student_detail;
+-----------+---------+------------+------------+
| studentid | Name    | Address    | Subject    |
+-----------+---------+------------+------------+
|       101 | YashPal | Amritsar   | History    |
|       105 | Gaurav  | Chandigarh | Literature |
|       130 | Ram     | Jhansi     | Computers  |
|       132 | Shyam   | Chandigarh | Economics  |
|       133 | Mohan   | Delhi      | Computers  |
|       150 | Rajesh  | Jaipur     | Yoga       |
|       160 | Pradeep | Kochi      | Hindi      |
+-----------+---------+------------+------------+
7 rows in set (0.00 sec)

mysql> Select * from Student_info;
+-----------+-----------+------------+-------------+
| studentid | Name      | Address    | Subject     |
+-----------+-----------+------------+-------------+
|       101 | YashPal   | Amritsar   | History     |
|       105 | Gaurav    | Chandigarh | Literature  |
|       130 | Ram       | Jhansi     | Computers   |
|       132 | Shyam     | Chandigarh | Economics   |
|       133 | Mohan     | Delhi      | Computers   |
|       165 | Abhimanyu | Calcutta   | Electronics |
+-----------+-----------+------------+-------------+
6 rows in set (0.00 sec)
Now, the following query using JOINS will simulate MINUS to return the ‘studentid’ values in student_info but not in the Student_detail table.
mysql> SELECT studentid from student_info LEFT JOIN Student_detail USING(studentid) WHERE student_detail.studentid IS NULL;
+-----------+
| studentid |
+-----------+
|       165 |
+-----------+
1 row in set (0.07 sec)
Now, the following query will give us the opposite result of the above query i.e. it will return the ‘studentid’ values in student_detail but not in Student_info table.
mysql> SELECT studentid from student_detail LEFT JOIN Student_info USING(studentid) WHERE student_info.studentid IS NULL;
+-----------+
| studentid |
+-----------+
|       150 |
|       160 |
+-----------+
2 rows in set (0.00 sec)
Define integer literals as octal values in Java

Literals with a leading zero are octal literals. Any number prefixed with a 0 is considered octal. Octal numbers can only use digits 0-7, just like decimal can use 0-9, and binary can use 0-1.
To define integer literals as octal value in Java is effortless. Here is the declaration and initialization.
int myOct = 023;

 Live Demo
public class Demo {
   public static void main(String []args) {
      int myOct = 023;
      System.out.println(myOct);
   }
}
19

Let us see another example.
 Live Demo
public class Demo {
   public static void main(String []args) {
      int myOct = 010;
      System.out.println(myOct);
   }
}
8
D3.js dsv() Function - GeeksforGeeks

17 Aug, 2020
The d3.dsv() function in D3.js is a part of the request API that returns a request for the file of type DSV. The mime type is text/DSV. An optional row conversion function can be specified to map and filter row objects.
Syntax:
d3.dsv(delimiter, inputfile, function);

Parameters: This function accepts three parameters as mentioned above and described below:
delimiter: It is the delimited such as “,” or “-” and so on that separates the columns.
inputfile: It is the location of the input file.
function: It is the function that is user-defined which performs certain actions to deal with the data.
Below given are a few examples of the function given above.
Note: Please create and save a file name sample.dsv before going with the code.
Example1:
HTML
<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8" />        <meta            name="viewport"            path1tent="width=device-width,                        initial-scale=1.0"/>        <title>D3.js dsv() Function</title>    </head>    <style></style>    <body>        <script src="https://d3js.org/d3.v4.min.js">        </script>        <script src="https://d3js.org/d3-dsv.v1.min.js">        </script>        <script src="https://d3js.org/d3-fetch.v1.min.js">        </script>          <script>            d3.dsv(",", "sample.dsv", (data) => {                console.log(data);            });        </script>    </body></html>
Output:
Example 2: When the delimiter is ” ” (space)
HTML
<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8" />        <meta            name="viewport"            path1tent="width=device-width,                        initial-scale=1.0"/>        <title>D3.js dsv() Function</title>    </head>    <style></style>    <body>        <script src="https://d3js.org/d3.v4.min.js">        </script>        <script src="https://d3js.org/d3-dsv.v1.min.js">        </script>        <script src="https://d3js.org/d3-fetch.v1.min.js">        </script>          <script>            d3.dsv(" ", "sample.dsv", (data) => {                console.log(data.year, " ", data.population);            });        </script>    </body></html>
Output:
D3.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
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using 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?
Tryit Editor v3.7

HTML Input types
Tryit: dates with max and min values
Python - Flatten Nested Tuples - GeeksforGeeks

04 Jan, 2022
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let’s discuss certain way in which this task can be performed.
Input : test_tuple = ((4, 7), ((4, 5), ((6, 7), (7, 6))))
Output : ((4, 7), (4, 5), (6, 7), (7, 6))

Input : test_tuple = ((4, 7), (5, 7), (1, 3))
Output : ((4, 7), (5, 7), (1, 3))

Method : Using recursion + isinstance()The combination of above functionalities can help us achieve solution to this problem. In this we use recursion to perform the task of digging into each tuple for inner tuples, and for decision of flattening, isinstance() is used depending upon tuple container or primitive data.
Python3
# Python3 code to demonstrate working of # Flatten Nested Tuples# Using recursion + isinstance()  # helper functiondef flatten(test_tuple):          if isinstance(test_tuple, tuple) and len(test_tuple) == 2 and not isinstance(test_tuple[0], tuple):        res = [test_tuple]        return tuple(res)      res = []    for sub in test_tuple:        res += flatten(sub)    return tuple(res)  # initializing tupletest_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Flatten Nested Tuples# Using recursion + isinstance()res = flatten(test_tuple)  # printing result print("The flattened tuple : " + str(res)) 
The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : ((4, 5), (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))

 
surinderdawra388
Python Nested-Tuples
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Bootstrap hide.bs.tab event

The hide.bs.tab fires when the tab is about to be hidden in Bootstrap.
Fire the hide.bs.tab and generate the alert before the modal is hidden −
$('.nav-tabs a').on('hide.bs.tab', function(e){
  alert('Previous tab will hide now!');
});
The first tab is the active tab and fade in property is also set −
<div id="home" class="tab-pane fade in active">
  <h3>Home</h3>
  <p>This is demo text!</p>
</div>
You can try to run the following code to implement the hide.bs.tab event −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h2>Web Dev</h2>
    <ul class="nav nav-tabs">
      <li class="active"><a href="#home">Home</a></li>
      <li><a href="#two">PHP</a></li>
      <li><a href="#three">C#.NET</a></li>
      <li><a href="#four">Ruby</a></li>
      <li><a href="#five">HTML5</a></li>
    </ul>
    <div class="tab-content">
      <div id="home" class="tab-pane fade in active">
        <h3>Home</h3>
        <p>This is demo text!</p>
      </div>
      <div id="two" class="tab-pane fade">
        <h3>PHP</h3>
        <p>This is demo text!</p>
      </div>
      <div id="three" class="tab-pane fade">
        <h3>C#.NET</h3>
        <p>This is demo text!</p>
      </div>
      <div id="four" class="tab-pane fade">
        <h3>Ruby</h3>
        <p>This is demo text!</p>
      </div>
      <div id="five" class="tab-pane fade">
        <h3>HTML5</h3>
        <p>This is demo text!</p>
      </div>
   </div>
 </div>

<script>
$(document).ready(function(){
  $(".nav-tabs a").click(function(){
    $(this).tab('show');
  });
  $('.nav-tabs a').on('show.bs.tab', function(){
    alert('New tab will be visible now!');
  });
  $('.nav-tabs a').on('shown.bs.tab', function(){
    alert('New tab is now visible!');
  });
  $('.nav-tabs a').on('hide.bs.tab', function(e){
    alert('Previous tab will hide now!');
  });
  $('.nav-tabs a').on('hidden.bs.tab', function(){
    alert('Previous Tab is hidden now!');
  });
});

</script>

</body>
</html>
Find all the numbers in a string using regular expression in Python

Extracting only the numbers from a text is a very common requirement in python data analytics. It is done easily using the python regular expression library. This library helps us define the patterns for digits which can be extracted as substrings.
In the below example we use the function findall() from the re module. The parameters to these function are the pattern which we want to extract and the string from which we want to extract. Please note with below example we get only the digits and not the decimal points or the negative signs.
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list = re.findall(r'\d+', str)
print(num_list)
Running the above code gives us the following result −
Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '8', '4', '112']
We can expand the search pattern to include the decimal points and the negative or positive signs also in the search result.
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list=re.findall(r'[-+]?[.]?[\d]+',str)
print(num_list)
Running the above code gives us the following result −
Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '.8', '-4', '.112']
Tryit Editor v3.7

Tryit: SVG rectangle with rounded corners
BufferedReader Class lines() method in Java with Examples - GeeksforGeeks

28 Jan, 2021
BufferedReader.lines() is the method of the  Java Buffered Reader Class in the Java Library which returns lines in terms of Stream and from this Buffered Reader class. With the help of the stream, there are a lot of methods that mimic the output according to our needs.
Syntax:
BufferedReader.lines() : Stream<String>
Parameters: This method does not take any kind of parameter.
Return: This method returns the stream of lines in terms of Stream and the Generic Type Change the stream into String.
Exception: IOException will be thrown when accessing the underlying BufferedReader which is wrapped in an UncheckedIOException.
Example: Find the line containing Hello as a word it will only work in a continuous scanning
The directory contains one txt files named as GFG.txt
The text File contains two lines: 
Java
// Java program to demonstrate the continuous scanning// by BufferedReader.lines() method and return the stream// of lines that contains the specific word  import java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.*;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;  class GFG {    public static void main(String[] args)    {        FileReader f= new FileReader("location of the file");                BufferedReader b = new BufferedReader(f);          // taking the stream as a string        Stream<String> i = b.lines();           i.filter(line -> line.contains("Hello")).findAny().ifPresent(System.out::println);                // filter the stream that line contains Hello is        // preset output        b.close();        f.close();    }}
Output:
Hello this is the first line. Hello this is the second line.
Java-BufferReader
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
Apply an IF condition to every element in an HTML table with JavaScript?

For this, you can use document.querySelectorAll.forEach().
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <table>
      <tr>
         <td class="demo"> Java </td>
      </tr>
      <tr>
         <td class="demo"> MySQL </td>
      </tr>
      <tr>
      </tr>
   </table>
</body>
<script>
   document.querySelectorAll(".demo").forEach(function (obj) {
      if (obj.innerText.trim() === "MySQL") {
         obj.innerText = "Javascript";
      }
      if (obj.innerText.trim() === "MongoDB") {
         obj.innerText = "Python";
      }
   });
</script>
</html>
To run the above program, save the file name anyName.html(index.html). Right click on the file
and select the option “Open with live server” in VS Code editor.
This will produce the following output −
Set width and precision to format output in Java

Set width in output as shown below. Here, %10 sets a 10 character field
System.out.printf("d1 = %10.2f \nd2 = %8g", d1, d2);
Above, the value after the decimal is for decimal places i.e. 5.3 is for 3 decimal places −
System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);
The following is an example −
 Live Demo
public class Demo {
   public static void main(String[] args) throws Exception {
      double d1 = 399.8877;
      double d2 = 298.87690;
      System.out.printf("d1 = %10.2f \nd2 = %8g", d1, d2);
      System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);
   }
}
d1 = 399.89
d2 = 298.877
d1 = 399.888
d2 = 298.87690
JavaScript | Math Object - GeeksforGeeks

01 Mar, 2019
The Math object is used to perform mathematical operations on numbers. There are many math object properties which are listed below:
Math objects: There are many math objects exists in JavaScript which are listed below:
Example 1: This example use math object properties to return their values.
<!DOCTYPE html> <html>   <head>     <title>         JavaScript Math Object    </title> </head>       <body>       <h1>GeeksforGeeks</h1>               <h2>JavaScript Math Object</h2>       <p id="GFG"></p>          <!-- Script to return math property values -->        <script>         document.getElementById("GFG").innerHTML =             "Math.LN10: " + Math.LN10 + "<br>" +            "Math.LOG2E: " + Math.LOG2E + "<br>" +            "Math.Log10E: " + Math.LOG10E + "<br>" +            "Math.SQRT2: " + Math.SQRT2 + "<br>" +            "Math.SQRT1_2: " + Math.SQRT1_2 + "<br>" +            "Math.LN2: " + Math.LN2 + "<br>" +            "Math.E: " + Math.E + "<br>" +            "Math.PI: " + Math.PI;    </script> </body>   </html>                    
Output:
Example 2: Math object methods are used in this example.
<!DOCTYPE html> <html>   <head>     <title>         JavaScript Math Object    </title> </head>       <body>       <h1>GeeksForGeeks</h1>               <h2>JavaScript Math Object</h2>       <p id="GFG" style = "color:green;"></p>          <!-- Script to use math object method -->        <script>         document.getElementById("GFG").innerHTML =         "<p><b>Math.abs(-4.7):</b> " + Math.abs(-4.7) + "</p>" +        "<p><b>Math.ceil(4.4):</b> " + Math.ceil(4.4) + "</p>" +        "<p><b>Math.floor(4.7):</b> " + Math.floor(4.7) + "</p>" +        "<p><b>Math.sin(90 * Math.PI / 180):</b> " +                 Math.sin(90 * Math.PI / 180) + "</p>" +        "<p><b>Math.min(0, 150, 30, 20, -8, -200):</b> " +                Math.min(0, 150, 30, 20, -8, -200) + "</p>" +        "<p><b>Math.random():</b> " + Math.random() + "</p>";    </script> </body>   </html>                    
Output:
javascript-math
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
numpy.imag() function - Python - GeeksforGeeks

11 Jun, 2020
numpy.imag() function return the imaginary part of the complex argument.
Syntax : numpy.imag(arr)
Parameters :arr : [array_like] Input array.
Return : [ndarray or scalar] The imaginary component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.
Code #1 :
# Python program explaining# numpy.imag() function       # importing numpy as geek import numpy as geek    arr = geek.array([1 + 3j, 5 + 7j, 9 + 11j])   gfg = arr.imag   print (gfg)
Output :
[ 3.  7. 11.]

 Code #2 :
# Python program explaining# numpy.imag() function       # importing numpy as geek import numpy as geek    arr = geek.array([2 + 3j, 5 + 6j, 8 + 9j])   gfg = arr.imag   print (gfg)
Output :
[3. 6. 9.]

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

29 Apr, 2022
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, Examples:
Input:  n = 11Output: true
Input:  n = 15Output: false
Input:  n = 1Output: false
CPP
// A school method based C++ program to check if a// number is prime#include <bits/stdc++.h>using namespace std; bool isPrime(int n){    // Corner case    if (n <= 1)        return false;     // Check from 2 to n-1    for (int i = 2; i < n; i++)        if (n % i == 0)            return false;     return true;} // Driver Program to test above functionint main(){    isPrime(11) ? cout << " true\n" : cout << " false\n";    isPrime(15) ? cout << " true\n" : cout << " false\n";    return 0;}
 true
 false

Time Complexity: O(n) Auxiliary Space: O(1)
Optimized School Method 
CPP
// A optimized school method based C++ program to check// if a number is prime#include <bits/stdc++.h>using namespace std; bool isPrime(int n){    // Corner cases    if (n <= 1)        return false;    if (n <= 3)        return true;     // This is checked so that we can skip    // middle five numbers in below loop    if (n % 2 == 0 || n % 3 == 0)        return false;     // Using concept of prime number    // can be represented in form of    // (6*n + 1) or(6*n - 1) hence    // we have to go for every multiple of 6 and    // prime number would always be 1 less or 1 more then    // the multiple of 6.    for (int i = 5; i * i <= n; i = i + 6)        if (n % i == 0 || n % (i + 2) == 0)            return false;     return true;} // Driver Program to test above functionint main(){    isPrime(4191) ? cout << " true\n" : cout << " false\n";    isPrime(15) ? cout << " true\n" : cout << " false\n";    return 0;}
 false
 false

Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
vikaspandey1206
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
C program to sort an array in ascending order
time() function in C
C Program to Swap two Numbers
Producer Consumer Problem in C
Program to find Prime Numbers Between given Interval
Python | Count the sublists containing given element in a list - GeeksforGeeks

16 Mar, 2019
Given a list of lists, write a Python program to count the number of sublists containing the given element x.
Examples:
Input : lst = [1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]] 
        x = 1 
Output : 3

Input : lst = (['a'], ['a', 'c', 'b'], ['d']) 
        x = 'a'
Output : 2

 Approach #1 : Naive Approach
Count the number of lists containing x. Initialize count to 0, then start a for loop and check if x exists in each list or not. If yes, increment count.
# Python3 Program to count number of# list containing a certain element # in a list of lists  def countList(lst, x):    count = 0    for i in range(len(lst)):        if x in lst[i]:            count+= 1              return count      # Driver Codelst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a'print(countList(lst, x))
2

 Approach #2 : List comprehension (Alternative for naive)A simple one-liner list comprehension can also do the job by simply converting the above mentioned Naive approach into one-liner for loop.
# Python3 Program to count number of# list containing a certain element # in a list of lists  def countList(lst, x):          return sum(x in item for item in lst)      # Driver Codelst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a'print(countList(lst, x))
2

 Approach #3 : Using chain.from_iterable() and Counter
We can use Counter to count how many lists ‘x’ occurs in. Since we don’t want to count ‘x’ for more than once for each inner list, we’ll convert each inner list to sets. After this, join those sets of elements into one sequence using chain.from_iterable().
# Python3 Program to count number of# list containing a certain element # in a list of listsfrom itertools import chainfrom collections import Counter  def countList(lst, x):          return Counter(chain.from_iterable(set(i) for i in lst))[x]      # Driver Codelst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a'print(countList(lst, x))
2

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

29 Jul, 2020
You can check whether a given date is equal to another date in Moment.js using isSame() function that checks if a moment is the same as another moment. The first argument will be parsed as a moment, if not already so.
Syntax:
moment().isSame(Moment|String|Number|Date|Array);
moment().isSame(Moment|String|Number|Date|Array, String);

Parameter: It can hold String/Number/Data/Array/Object.
Returns: True or False
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
// Requiring moduleconst moment = require('moment');  var bool1 = moment('2010-08-21')    .isSame('2010-09-21'); //falseconsole.log(bool1);  var bool2 = moment('2019-10-20')    .isSame('2019-10-20'); //trueconsole.log(bool2);
Steps to run the program:
The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false
true

The project structure will look like this:
Make sure you have installed moment module using the following command:npm install moment
npm install moment
Run index.js file using below command:node index.jsOutput:false
true

node index.js
Output:
false
true

Example 2: Filename: index.js
// Requiring moduleconst moment = require('moment');  function checkSame(date1, date2) {    return moment(date1).isSame(date2);}  var bool =  checkSame('2019-10-20', '2019-10-20')console.log(bool);
Run index.js file using below command:
node index.js
Output:
true

Reference: https://momentjs.com/docs/#/query/is-same/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Difference between Deterministic and Non-deterministic Algorithms - GeeksforGeeks

24 Nov, 2021
In deterministic algorithm, for a given particular input, the computer will always produce the same output going through the same states but in case of non-deterministic algorithm, for the same input, the compiler may produce different output in different runs. In fact non-deterministic algorithms can’t solve the problem in polynomial time and can’t determine what is the next step. The non-deterministic algorithms can show different behaviors for the same input on different execution and there is a degree of randomness to it.
To implement a non-deterministic algorithm, we have a couple of languages like Prolog but these don’t have standard programming language operators and these operators are not a part of any standard programming languages.
Some of the terms related to the non-deterministic algorithm are defined below:
choice(X) : chooses any value randomly from the set X.
failure() : denotes the unsuccessful solution.
success() : Solution is successful and current thread terminates.
Example :
Problem Statement : Search an element x on A[1:n] where n>=1, on successful search return j if a[j] is equals to x otherwise return 0.
Non-deterministic Algorithm for this problem :
1.j= choice(a, n)
2.if(A[j]==x) then
    {
       write(j);
       success();
    }
3.write(0); failure();
Algorithms-Analysis of Algorithms
Picked
Algorithms
Analysis
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to Start Learning DSA?
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Understanding Time Complexity with Simple Examples
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Time Complexity and Space Complexity
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
How to Fix: NameError name ‘np’ is not defined - GeeksforGeeks

28 Nov, 2021
In this article, we will discuss how to fix NameError np that is not defined in Python.
When we imported the NumPy module without alias and used np in the code, the error comes up.
Example: Code to depict error
Python3
# import numpymoduleimport numpy  # create numpy arraya = np.array([1, 2, 3, 45])  # displaya
Output:
name 'np' is not defined
Here np is an alias of the NumPy module so we can either import the NumPy module with the alias or import NumPy without the alias and use the name directly.
We can use an alias at the time of import to resolve the error.
Syntax:
import numpy as np
Example: Program to import numpy as alias
Python3
# import numpymoduleimport numpy as np  # create numpy arraya = np.array([1, 2, 3, 45])  # displaya
Output:
array([ 1,  2,  3, 45])
We can use NumPy module directly to use in a data structure.
Syntax:
import numpy
Example: Using NumPy directly
Python3
# import numpymoduleimport numpy  # create numpy arraya = numpy.array([1, 2, 3, 45])  # displaya
Output:
array([ 1,  2,  3, 45])
Picked
Python How-to-fix
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Automatic Captcha Verification using JavaScript - GeeksforGeeks

01 Feb, 2019
Captcha: Captcha is a program used to protects websites through bots. It generates some tests that human can read and pass it but current computer can not do. For example, humans can read distorted text but computer can not read. The CAPTCHA is the abbreviation of Completely Automated Public Turing Test To Tell Computers and Humans Apart.
There are many paid software in market which detect captcha code. The Tessaract.js library is used to identifying numbers from the text.
Note: Its prediction is not 100% accurate however it can improve accuracy by using the str.replace(“”, “”) method. Only numeric captcha can be solved easily by using this method.
Example:
<!DOCTYPE html><html>      <head>    <title>        Auto captcha verification    </title>          <script src ='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'>    </script></head>  <body>    <img id = "img" src = "https://i.ibb.co/L97ShyB/download.jpg" />          <div id = "GFG"></div>          <!-- script for auto captcha verification -->    <script>        let progress = document.querySelector('#GFG');                  Tesseract.recognize('https://i.ibb.co/L97ShyB/download.jpg')                  .progress(function(p) {            progress.innerHTML += JSON.stringify(p) + "<br>"        })                  .then(function(result) {            var captcha = result.text;            alert(captcha)        })    </script></body>  </html>                    
Output:
Web-Programs
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
HTML | Window atob( ) Method - GeeksforGeeks

26 Jul, 2019
The Window atob() method is used for decoding a base-64 encoded string. It is used to decode a string of data which has been encoded using the btoa() method.It returns a string which represents the decoded string.
Syntax :
window.atob(EncodedString)
Parameters Used :
EncodedString : It is a mandatory parameter which specifies the encoded string.
Below program illustrates the Window atob() Method :
Decoding a string encoded using the btoa() method.
<!DOCTYPE html><html>  <head>    <title>      Window atob() Method in HTML    </title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body>      <h1>GeeksforGeeks</h1>    <h2>Window atob() Method</h2>      <p>      For decoding a base-64 encoded string,      double click the "Decode Message" button:    </p>      <button ondblclick="decode()">      Decode Message    </button>      <p id="myDecoding"></p>      <script>        function decode() {            var original = "GeeksforGeeks";            var encoded = window.btoa(original);            var decoded = window.atob(encoded);              var output = "Encoded String : "             + encoded + "<br>" + "Decoded String : "            + decoded;            document.getElementById("myDecoding").innerHTML =              output;        }    </script>  </body>  </html>
Output:
After clicking the button
Supported Browsers: The browser supported by Window atob( ) Method are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
How to create an HTML button that acts like a link?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
What are the arguments to Tkinter variable trace method callbacks?

Tkinter variable (var) is defined for a particular widget (textvariable=var) to store the updated value of a widget. Sometimes, there might be a case, while updating the variable information, we need to process some extra operations such as read, write, or undefined.
Tkinter provides a way to update the variable with a callback function trace (self, mode, callback) which takes the operation of the process such as read(r), write(w), or undefined(u). On the basis of these values, the callback decides what the process needs to do in the callback function. The other two values define the variable which needs to be traced (contains widget information) and the index of the variable.
In this example, we will trace the value of the Entry widget that gets updated when the user enters a value in it.
#Import the required library
from tkinter import*
#Create an instance of Tkinter frame
win = Tk()
win.geometry("750x250")
#create a variable to store the User Input
my_variable = StringVar()
def trace_when_Entry_widget_is_updated(var, index, mode):
   print ("{}".format(my_variable.get()))

my_variable.trace_variable("w", trace_when_Entry_widget_is_updated)
Label(win, textvariable = my_variable).pack(padx=5, pady=5)
Entry(win, textvariable = my_variable, width=20).pack(ipadx=20,padx=5, pady=5)
win.mainloop()
Executing the above code will display an Entry widget that stores the input in a variable. The callback function will trace the updated value of the variable and display it in a Label widget.
Now, type something in the given Entry widget. The label widget will mimic the input value and display the output on the window.
On the console, you will get to see the following −
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World
How to write multiple lines in text file using Python?

You can use write function to write multiple lines by separating lines by '\n'.
line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt','w') as out:
    out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
Alternatively, you can use writelines function to write these lines.
line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt','w') as out:
    out.writelines([line1, line2, line3])
SVG - Line

<line>  element is used to draw line with a start point and end point.
Following is the syntax declaration of <line> element. We've shown main attributes only.
<line
   x1="x-axis co-ordinate"
   y1="y-axis co-ordinate"
   
   x2="x-axis co-ordinate" 
   y2="y-axis co-ordinate" >    
</line>
<html>
   <title>SVG Line</title>
   <body>
      
      <h1>Sample SVG Line Image</h1>
      
      <svg width="800" height="800">
         <g>
            <text x="0" y="15" fill="black" >Line #1: Without opacity.</text>
            
            <line x1="20" y1="20" x2="150" y2="150" 
            stroke="black" stroke-width="3" fill="rgb(121,0,121)"></line> 
         </g> 
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
<html>
   <title>SVG Line</title>
   <body>
      
      <h1>Sam>le SVG Line Image</h1>
      
      <svg width="800" height="800"> 
         <g>
            <text x="0" y="15" fill="black" >Line #2: With opacity </text>
            
            <line x1="20" y1="20" x2="150" y2="150"  
            style="fill:rgb(121,0,121);stroke-width:3;
            stroke:rgb(0,0,0);stroke-opacity:0.5;opacity:0.5"></line> 
         </g>
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Python - Nested List to single value Tuple - GeeksforGeeks

03 Jul, 2020
Sometimes, while working with Python data, we can have problems in which we need to convert Python Nested lists to single values tuples. This kind of problem can have applications in domains such as web development and competitive programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[5, 6], [4, 7, 10, 17]]Output : [(5, ), (6, ), (4, ), (7, ), (10, ), (17, )]
Input : test_list = [[5, 6, 7, 8]]Output : [(5, ), (6, ), (7, ), (8, )]
Method #1 : Using list comprehension ( For single nesting )This is one of the way in which this task can be performed. We iterate each inner list and convert each element as separate tuple. This caters just for a single nesting.
# Python3 code to demonstrate working of # Convert Nested List to 1 value Tuple# Using list comprehension  # initializing listtest_list = [[5, 6], [4, 7, 10], [12], [9, 11]]  # printing original listprint("The original list is : " + str(test_list))  # Convert Nested List to 1 value Tuple# Using list comprehensionres = [(ele, ) for sub in test_list for ele in sub]  # printing result print("The converted container : " + str(res)) 
The original list is : [[5, 6], [4, 7, 10], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (12, ), (9, ), (11, )]

 
Method #2 : Using isinstance() + recursionThe combination of above functions can be used to solve this problem. In this, we perform the task of flattening and conversion using isinstance() and recursion to cater the case of random nesting as well.
# Python3 code to demonstrate working of # Convert Nested List to 1 value Tuple# Using isinstance() + recursion  # helper_fncdef hlper_fnc(test_list):    res = []    if isinstance(test_list, list):        for ele in test_list:            res.extend(hlper_fnc(ele))    elif isinstance(test_list, int):        res.append((test_list, ))    return res  # initializing listtest_list = [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]  # printing original listprint("The original list is : " + str(test_list))  # Convert Nested List to 1 value Tuple# Using isinstance() + recursionres = hlper_fnc(test_list)  # printing result print("The converted container : " + str(res)) 
The original list is : [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (45, ), (12, ), (9, ), (11, )]

Python list-programs
Python-list-of-lists
Python
Python Programs
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
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Groovy - round()

The method round returns the closest long or int, as given by the methods return type.
long round(double d)
  
int round(float f) 

d - A double or float primitive data type
f - A float primitive data type
This method Returns the closest long or int, as indicated by the method's return type, to the argument.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      double d = 100.675; 
      double e = 100.500; 
		
      float f = 100; 
      float g = 90f;  
		
      System.out.println(Math.round(d)); 
      System.out.println(Math.round(e)); 
      System.out.println(Math.round(f));
      System.out.println(Math.round(g)); 
   } 
}
When we run the above program, we will get the following result −
101 
101 
100 
90


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page