code-rag-bench/online-tutorials huggingface dataset:
Baseball Game in Python

Suppose we have a baseball game point recorder. We have a list of strings; each string can be one of the 4 following types −
Integer (one round's score) − Indicates the number of points we get in this round.
"+" (one round's score) − Indicates the points we get in this round are the sum of the last two valid round's points.
"D" (one round's score ) − Indicates the points we get in this round are the doubled data of the last valid round's points.
"C" (an operation, which isn't a round's score) − Indicates the last valid round's points we get were invalid and should be removed.
Note that each round's operation is permanent and could have an impact on the round before and the round after. We have to find the sum of the points we could get in all the rounds.
So, if the input is like ["5","2","C","D","+"], then the output will be 30. This is actually for
Round 1 − We could get 5 points. The sum is: 5.
Round 2 − We could get 2 points. The sum is: 7.
Operation 1 − The data of the round 2 was invalid. The sum is: 5.
Round 3 − We could get 10 points. The sum is: 15.
Round 4 − We could get 5 + 10 = 15 points. The sum is: 30.
To solve this, we will follow these steps −
stack := empty list
for each i in ops, doif i is same as "+", thenfirst := stack[size of stack - 1], second := stack[size of stack - 2]insert (first + second) into stack at the endotherwise when i is same as "D", theninsert (last element of stack * 2) into stack at the endotherwise when i is same as "C", thendelete last element from stackotherwise,insert i into stack at the end
if i is same as "+", thenfirst := stack[size of stack - 1], second := stack[size of stack - 2]insert (first + second) into stack at the end
first := stack[size of stack - 1], second := stack[size of stack - 2]
insert (first + second) into stack at the end
otherwise when i is same as "D", theninsert (last element of stack * 2) into stack at the end
insert (last element of stack * 2) into stack at the end
otherwise when i is same as "C", thendelete last element from stack
delete last element from stack
otherwise,insert i into stack at the end
insert i into stack at the end
return sum of all elements of stack
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def calPoints(self, ops):
      stack = []
      for i in ops:
         if i == "+":
            first, second = stack[len(stack) - 1],
            stack[len(stack) - 2]
            stack.append(first + second)
         elif i == "D":
            stack.append(stack[-1] * 2)
         elif i == "C":
            stack.pop()
         else:
            stack.append(int(i))
      return sum(stack)
ob = Solution()
print(ob.calPoints(["5","2","C","D","+"]))
["5","2","C","D","+"]
30
Check if the camera is opened or not using OpenCV-Python - GeeksforGeeks

07 Oct, 2021
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos.
While writing code in Python using OpenCV, we may not be sure whether at the remote end camera is opened and working properly or not. The camera plays an essential role in areas such as Security and Video Surveillance System. In a real-time video monitoring system, to ensure that the camera is opened and working properly we have isOpened() of OpenCV. The idea behind the article is to check whether the camera is connected and if the camera is found to be disconnected then a mail will be sent to the Admin or the concerned person.
1. Check whether the camera is opened/connected or not.
Approach:
Importing necessary libraries(NumPy and OpenCV)
Starting camera. Here, in VideoCapture()-0 denotes built-in webcam while 1 will denote the use of external webcams.
If the camera is opened, we will loop over frames whereas in the other case, a message “Alert! Camera disconnected” will be printed on the terminal window.
Below is the implementation.
# Python program to check# whether the camera is opened # or not    import numpy as npimport cv2    cap = cv2.VideoCapture(0)while(cap.isOpened()):          while True:                  ret, img = cap.read()        cv2.imshow('img', img)        if cv2.waitKey(30) & 0xff == ord('q'):            break                  cap.release()    cv2.destroyAllWindows()else:    print("Alert ! Camera disconnected")
2. Sending Mail if camera is found to be disconnected/not opened.
Approach:
Import the necessary libraries(smtplib is the python library to send mails).
Establish a connection with the server and login to the account.
Specify the receiver’s email address and message to be sent (“Alert! Camera disconnected!” in this case).
Once the mail is sent, close the connection or quit the session.
Below is the implementation.
# Python program to send # the mail    import smtplib    conn = smtplib.SMTP('smtp.gmail.com', 587)  conn.ehlo()conn.starttls()  # Enter the sender's detailsconn.login('Enter sender \'s gmail address',            'Enter sender\'s password')  conn.sendmail('Enter sender\'s gmail address',               'Enter Receiver\'s gmail address',               'Enter message to be sent')  conn.quit()
sagar0719kumar
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
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
Python | Reshape a list according to given multi list - GeeksforGeeks

25 Apr, 2019
Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list.
Examples:
Input : list1 = [[1], [2, 3], [4, 5, 6]]
        list2 = ['a', 'b', 'c', 'd', 'e', 'f']
Output : [['a'], ['b', 'c'], ['d', 'e', 'f']]

Input : list1 = [[8, 2, 5], [1], [12, 4, 0, 24]]
        list2 = ['m', 'n', 'o', 'p', 'q', 'r', 's', 't']
Output : [['m', 'n', 'o'], ['p'], ['q', 'r', 's', 't']]

 Method #1 : Using extended slices
A simple and naive method is to use a for loop and Python extended slices to append each sublist of list2 to a variable ‘res’.
# Python3 program to reshape a list # according to multidimensional list          def reshape(lst1, lst2):    last = 0    res = []    for ele in list1:        res.append(list2[last : last + len(ele)])        last += len(ele)              return res  # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2))
[['a'], ['b', 'c'], ['d', 'e', 'f']]

 Method #2 : islice from itertools module
Another method is to use islice function from itertools module. islice selectively prints the values mentioned in its iterable container. Thus, we yield slices of list2 according to list1 and append it to variable ‘res’.
# Python3 program to reshape a list # according to multidimensional listfrom itertools import islice  def yieldSublist(lst1, lst2):    iter2 = iter(lst2)    for sublist1 in lst1:        sublist2 = list(islice(iter2, len(sublist1)))        yield sublist2          def reshape(lst1, lst2):    res = list()    for sub2 in yieldSublist(list1, list2):        res.append(sub2)              return res  # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2))
[['a'], ['b', 'c'], ['d', 'e', 'f']]

 
Method #3 : Python iterator with list comprehension
The iter() method returns an iterator for list2 and save it in variable ‘iterator’. Now using list comprehension reshape list2 according to list1.
# Python3 program to reshape a list # according to multidimensional list  def reshape(lst1, lst2):    iterator = iter(lst2)    return [[next(iterator) for _ in sublist]                          for sublist in lst1]  # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2))
[['a'], ['b', 'c'], ['d', 'e', 'f']]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Connecting MongoDB with NodeJS

This method is used to connect the Mongo DB server with our Node application. This is an asynchronous method from MongoDB module.
mongodb.connect(path[, callback])
•path – The server path where the MongoDB server is actually running along with its port.
•path – The server path where the MongoDB server is actually running along with its port.
•callback – This function will give a callback if any error occurs.
•callback – This function will give a callback if any error occurs.
Before proceeding to try connect your application with Nodejs, we need to setup our MongoDB server first.
Use the following query to install mongoDB from npm.
Use the following query to install mongoDB from npm.
npm install mongodb –save
Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB.
Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB.
mongod --dbpath=data --bind_ip 127.0.0.1
Create a MongodbConnect.js and copy-paste the following code snippet into that file.
Create a MongodbConnect.js and copy-paste the following code snippet into that file.
Now, run the following command to run the code snippet.
Now, run the following command to run the code snippet.
node MongodbConnect.js
// Calling the required MongoDB module.
const MongoClient = require("mongodb");

// Server path
const url = 'mongodb://localhost:27017/';

// Name of the database
const dbname = "Employee";

MongoClient.connect(url, (err,client)=>{
   if(!err) {
      console.log("successful connection with the server");
   }
   else
      console.log("Error in the connectivity");
})
C:\Users\tutorialsPoint\> node MongodbConnect.js
(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)
successful connection with the server.
How to find the longest common substring from more than two strings in Python?

Common dynamic programming implementations for the Longest Common Substring algorithm runs in O(nm) time. The following is an implementation of the longest common substring algorithm:
def longest_common_substring(s1, s2):
   m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
   longest, x_longest = 0, 0
   for x in xrange(1, 1 + len(s1)):
       for y in xrange(1, 1 + len(s2)):
           if s1[x - 1] == s2[y - 1]:
               m[x][y] = m[x - 1][y - 1] + 1
               if m[x][y] > longest:
                   longest = m[x][y]
                   x_longest = x
           else:
               m[x][y] = 0
   return s1[x_longest - longest: x_longest]
print(longest_common_substring('wellbeing', 'welcome'))
wel
This is how it works
Initially, we initialized the counter array(m) all 0.
Initially, we initialized the counter array(m) all 0.
Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2.
Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2.
While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position.
While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position.
At the end we return the longest sub-string using indices we calculated in the loops.
Matcher group() method in Java with Examples

The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The group() method of this (Matcher) class returns the matched input subsequence during the last match.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> "
         + "where <b>every</b> alternative <b>word</b> is <b>bold</b>. "
         + "It <i>also</i> contains <i>italic</i> words</p>";
      //Regular expression to match contents of the bold tags
      String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group());
      }
   }
}
<b>is</b>
<b>example</b>
<b>script</b>
<b>every</b>
<b>word</b>
<b>bold</b>
<i>also</i>
<i>italic</i>
Another variant of this method accepts an integer variable representing the group, where the captured groups are indexed starting from 1 (left to right).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
   public static void main(String[] args) {
      String regex = "(.*)(\\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between.";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("match: "+matcher.group(0));
         System.out.println("First group match: "+matcher.group(1));
         System.out.println("Second group match: "+matcher.group(2));
         System.out.println("Third group match: "+matcher.group(3));
      }
   }
}
match: This is a sample Text, 1234, with numbers in between.
First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.
Deleting all rows older than 5 days in MySQL

To delete all rows older than 5 days, you can use the following syntax −
delete from yourTableName
   where datediff(now(), yourTableName.yourDateColumnName) > 5;
Note − Let’s say the current date is 2019-03-10.
To understand the concept, let us create a table. The query to create a table is as follows −
mysql> create table deleteRowsOlderThan5Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Post_Date date
   -> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Larry','2019-03-
11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Mike','2019-02-
12');
Query OK, 1 row affected (0.17 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Sam','2019-03-
10');
Query OK, 1 row affected (0.12 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Carol','2019-03-
01');
Query OK, 1 row affected (0.23 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('David','2019-01-
31');
Query OK, 1 row affected (0.19 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Maxwell','2019-01-
26');
Query OK, 1 row affected (0.10 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('John','2019-02-
19');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from deleteRowsOlderThan5Demo;
Here is the output −
+----+---------+------------+
| Id | Name    | Post_Date  |
+----+---------+------------+
| 1  | Larry   | 2019-03-11 |
| 2  | Mike    | 2019-02-12 |
| 3  | Sam     | 2019-03-10 |
| 4  | Carol   | 2019-03-01 |
| 5  | David   | 2019-01-31 |
| 6  | Maxwell | 2019-01-26 |
| 7  | John    | 2019-02-19 |
+----+---------+------------+
7 rows in set (0.00 sec)
Here is the query to delete all rows older than 5 days −
mysql> delete from deleteRowsOlderThan5Demo
   -> where datediff(now(), deleteRowsOlderThan5Demo.Post_Date) > 5;
Query OK, 5 rows affected (0.14 sec)
Let us check the table records once again. The query is as follows −
mysql> select *from deleteRowsOlderThan5Demo;
Here is the output −
+----+-------+------------+
| Id | Name  | Post_Date  |
+----+-------+------------+
| 1  | Larry | 2019-03-11 |
| 3  | Sam   | 2019-03-10 |
+----+-------+------------+
2 rows in set (0.00 sec)
Find length of one array element in bytes and total bytes consumed by the elements in Numpy - GeeksforGeeks

23 Jul, 2021
In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes.
Syntax: array.itemsize  
Return :It will return length(int) of the array in bytes.  
 
Syntax: array.nbytes  
Return :It will return total bytes consumed by the elements. 
Example 1:
Python
import numpy as np  array = np.array([1,3,5], dtype=np.float64) # Size of the arrayprint(array.size) # Length of one array element in bytes,print( array.itemsize) # Total bytes consumed by the elements# of the arrayprint(array.nbytes)
  Output:
3
8
24
Example 2:
Python
import numpy as np  array = np.array([20, 34, 56, 78, 1, 9], dtype=np.float64) # Size of the arrayprint(array.size) # Length of one array element in bytes,print(array.itemsize) # Total bytes consumed by the elements# of the arrayprint(array.nbytes)
 Output: 
6
8
48
rajeev0719singh
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Wide char and library functions in C++

In this section we will see what is the wide character in C++. We will also see some
functions that are used to handle wide characters.
Wide characters are similar to character datatype. The main difference is that
char takes 1-byte space, but wide character takes 2-bytes (sometimes 4-byte
depending on compiler) of space in memory. For 2-byte space wide character can
hold 64K (65536) different characters. So the wide char can hold UNICODE
characters. The UNICODE values are international standard which allows for
encoding for characters virtually for any character of any language.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   wchar_t wide_character = L'a';
   cout << "The wide character is: " << wide_character << endl;
   cout << "Wide character size: " <<sizeof(wide_character);
}
The wide character is: 97
Wide character size: 2
We can see that to make wide character we have to add ‘L’ before the character
literal. But the character value is not displayed in the output using cout. So to use
wide char we have to use wcout, and for taking input we have to use wcin.
We can make some wide character array, and print them as string.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   char str1[] = "This is character array";
   cout << str1 << endl;
   wchar_t str2 [] = L"This is wide character array";
   wcout << str2;
}
This is character array
This is wide character array
Now let us see some functions that are used for wide characters.
Tryit Editor v3.7

Tryit: HSLA color values
Fix navbar to the bottom of the page with Bootstrap

To fix navbar to the bottom, use the navbar-fixed-bottom class:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <nav class = "navbar navbar-default navbar-fixed-bottom" role = "navigation" style="background: orange;">
         <div class = "navbar-header">
            <a class = "navbar-brand" href = "#">Java Topics</a>
         </div>
         <div>
            <ul class = "nav navbar-nav">
               <li class = "active"><a href = "#">Basics</a></li>
               <li><a href = "#">Interface</a></li>
               <li><a href = "#">Polymorphism</a></li>
               <li><a href = "#">Encapsulation</a></li>
            </ul>
         </div>
      </nav>
   </body>
</html>
Pandas - All combinations of two columns - GeeksforGeeks

15 Mar, 2021
In this article, we will see how to get the combination of two columns of a DataFrame. First, let’s create a sample DataFrame.
Code: An example code to create a data frame using dictionary.
Python3
# importing pandas module for the  # data frameimport pandas as pd  # creating data frame for student details # using dictionarydata = pd.DataFrame({'id': [7058, 7059, ],                      'name': ['sravan', 'jyothika']})  print(data)
Output:
To combine two columns in a data frame using itertools module. It provides various functions that work on iterators to produce complex iterators. To get all combinations of columns we will be using itertools.product module. This function computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function is tuples in sorted order.
Syntax: itertools.product(iterables, repeat=1)
Code:
Python3
# import pandas as pdimport pandas as pd  # creating data framedf = pd.DataFrame(data=[['sravan', 'Sudheer'],                         ['radha', 'vani'], ],                  columns=['gents', 'ladies'])  print(df)
Output:
Code:
Python3
# importing productfrom itertools import product  # apply product methodprint(list(product(df['gents'], df['ladies'])))
Output:
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
AtomicBoolean compareAndSet() method in Java with Examples - GeeksforGeeks

27 Feb, 2019
The java.util.concurrent.atomic.AtomicBoolean.compareAndSet() is an inbuilt method in java that sets the value to the passed value in the parameter if the current value is equal to the expected value which is also passed in the parameter. The function returns a boolean value which gives us an idea if the update was done or not.
Syntax:
public final boolean compareAndSet(boolean expect, boolean val)
Parameters: The function accepts two mandatory parameters which are described below:
expect: which specifies the value that the atomic object should be.
val: which specifies the value to be updated if the atomic Boolean is equal to expect.
Return Value: The function returns a boolean value, it returns true on success else false.
Below programs illustrate the above function:
Program 1:
// Java Program to demonstrates// the compareAndSet() function  import java.util.concurrent.atomic.AtomicBoolean;  public class GFG {    public static void main(String args[])    {          // Initially value as false        AtomicBoolean val = new AtomicBoolean(false);          // Prints the updated value        System.out.println("Previous value: "                           + val);          // Checks if previous value was false        // and then updates it        boolean res = val.compareAndSet(false, true);          // Checks if the value was updated.        if (res)            System.out.println("The value was"                               + " updated and it is "                               + val);        else            System.out.println("The value was "                               + "not updated");    }}
Previous value: false
The value was updated and it is true

Program 2:
// Java Program to demonstrates// the compareAndSet() function  import java.util.concurrent.atomic.AtomicBoolean;  public class GFG {    public static void main(String args[])    {          // Initially value as true        AtomicBoolean val = new AtomicBoolean(true);          // Prints the updated value        System.out.println("Previous value: "                           + val);          // Checks if previous value was true        // and then updates it        boolean res = val.compareAndSet(true, false);          // Checks if the value was updated.        if (res)            System.out.println("The value was"                               + " updated and it is "                               + val);        else            System.out.println("The value was "                               + "not updated");    }}
Previous value: true
The value was updated and it is false

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#compareAndSet(boolean, %20boolean)
Java-AtomicBoolean
Java-concurrent-package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Set in Java
Multidimensional Arrays in Java
Python | Data Comparison and Selection in Pandas - GeeksforGeeks

17 Sep, 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.
The most important thing in Data Analysis is comparing values and selecting data accordingly. The “==” operator works for multiple values in a Pandas Data frame too. Following two examples will show how to compare and select data from a Pandas Data frame.
To download the CSV file used, Click Here.
Example #1: Comparing DataIn the following example, a data frame is made from a csv file. In the Gender Column, there are only 3 types of values (“Male”, “Female” or NaN). Every row of Gender column is compared to “Male” and a boolean series is returned after that.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # storing boolean series in newnew = data["Gender"] == "Male"  # inserting new series in data framedata["New"]= new  # displaydata
Output:As show in the output image, for Gender= “Male”, the value in New Column is True and for “Female” and NaN values it is False.
 Example #2: Selecting DataIn the following example, the boolean series is passed to the data and only Rows having Gender=”Male” are returned.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # storing boolean series in newnew = data["Gender"] != "Female"  # inserting new series in data framedata["New"]= new  # displaydata[new]  # OR # data[data["Gender"]=="Male"]# Both are the same
Output:As shown in the output image, Data frame having Gender=”Male” is returned.
Note: For NaN values, the boolean value is False.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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()
C# Program to Get the Operating System Version of Computer using Environment Class - GeeksforGeeks

24 Oct, 2021
In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. In this article, we are going to discuss how to get the operating system version of the computer. So we use the OSVersion property of the Environment class. This property returns the current OS version of the system or platform identifier. It will also return an InvalidOperationException if this property does not get the current version of the system or a platform identifier that is not part of PlatformID. 
Syntax:
Environment.OSVersion
spa
Return: It returns the platform identifier or the version of the system.
Example: 
In the below example, using the OsVersion property of Environment class we find the current OS version of our computer system.
C#
// C# program to get the current operating// system version of the computer // Using Environment Classusing System;using System.Collections;  class GFG{      static public void Main()    {          // Display the current OS version of the system         // Using OSVersion property of the Environment class        Console.WriteLine("The current operating System version is " +                          Environment.OSVersion);    }}
Output:
The current operating System version is Unix 20.3.0.0
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C#
Program for sum of geometric series in C

Given three inputs first one is “a” which is for the first term of geometric series second is “r” which is the common ratio and “n” which are the number of series whose sum we have to find.
Geometric series is a series which have a constant ratio between its successive terms. Using the above stated inputs “a”, “r” and “n” we have to find the geometric series i.e., a, ar, ar2 , ar3 , ar4 , ... and their sum, i.e., a + ar + ar2+ ar3 + ar4 +...
Input
a = 1
r = 0.5
n = 5
Output
1.937500
Input
a = 2
r = 2.0
n = 8
Output
510.000000
Take all the inputs a, r, n.
Take all the inputs a, r, n.
Calculate the sum of geometric series, adding the full series.
Calculate the sum of geometric series, adding the full series.
Start
In function float sumgeometric(float a, float r, int n)
   Step 1→Declare and Initialize sum = 0
   Step 2→ Loop For i = 0 and i < n and i++
      Set sum = sum + a
      Set a = a * r
   Step 3→ Return sum
In function int main()
   Step 1→ Declare and initialize a = 1
   Step 2→ Declare and Initialize float r = 0.5
   Step 3→ Declare and initialize n = 5
   Step 4→ Print sumgeometric(a, r, n)
Stop
 Live Demo
#include <stdio.h>
// function to calculate sum of
// geometric series
float sumgeometric(float a, float r, int n){
   float sum = 0;
   for (int i = 0; i < n; i++){
      sum = sum + a;
      a = a * r;
   }
   return sum;
}
int main(){
   int a = 1; // first term
   float r = 0.5; // their common ratio
   int n = 5; // number of terms
   printf("%f", sumgeometric(a, r, n));
   return 0;
}
If run the above code it will generate the following output −
1.937500
Clojure - Functions with Multiple Arguments

Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type. The number of parameters is the function’s arity. This chapter discusses some function definitions with different arities.
In the following example, the function demo is defined with multiple arguments for each function definition.
(defn demo [] (* 2 2))
(defn demo [x] (* 2 x))
(defn demo [x y] (* 2 x y))
In the above example, the first function definition is a 0-arity function, since it has 0 arguements, one-param is 1-arity, and two-params is 2-arity and so on.
 Print
 Add Notes
 Bookmark this page
Arduino - If statement

It takes an expression in parenthesis and a statement or block of statements. If the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
Form 1
if (expression)
   statement;

You can use the if statement without braces { } if you have one statement.
Form 2
if (expression) {
   Block of statements;
}

/* Global variable definition */
int A = 5 ;
int B = 9 ;

Void setup () {

}

Void loop () {
   /* check the boolean condition */
   if (A > B) /* if condition is true then execute the following statement*/
   A++;
   /* check the boolean condition */
   If ( ( A < B ) && ( B != 0 )) /* if condition is true then execute the following statement*/ { 
      A += B;
      B--;
   }
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
MySQL Tryit Editor v1.0

SELECT CONCAT("SQL ", "Tutorial ", "is ", "fun!") AS ConcatenatedString;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Software Testing Tools - GeeksforGeeks

30 Jan, 2020
Software Testing tools are the tools which are used for the testing of software. Software testing tools are often used to assure firmness, thoroughness and performance in testing software products. Unit testing and subsequent integration testing can be performed by software testing tools. These tools are used to fulfill all the requirements of planned testing activities. These tools also works as commercial software testing tools. The quality of the software is evaluated by software testers with the help of various testing tools.
Types of Testing Tools:As software testing is of two types, static testing and dynamic testing. Also the tools used during these testing are named accordingly on these testings. Testing tools can be categorized into two types which are as follows:
1. Static Test Tools
2. Dynamic Test Tools
These are explained in detail as following below:
1. Static Test Tools:Static test tools are used to work on the static testing processes. In the testing through these tools, typical approach is taken. These tools do not test the real execution of the software. Certain input and output are not required in these tools. Static test tools consists of the following:
Flow analyzers:Flow analyzers provides flexibility in data flow from input to output.
Path Tests:It finds the not used code and code with inconsistency in the software.
Coverage Analyzers:All rationale paths in the software are assured by the coverage analyzers.
Interface Analyzers:They check out the consequences of passing variables and data in the modules.
2. Dynamic Test Tools:Dynamic testing process is performed by the dynamic test tools. These tools test the software with existing or current data. Dynamic test tools comprises of the following:
Test driver:Test driver provides the input data to a module-under-test (MUT).
Test Beds:It displays source code along with the program under execution at the same time.
Emulators:Emulators provides the response facilities which are used to imitate parts of the system not yet developed.
Mutation Analyzers:They are used for testing fault tolerance of the system by knowingly providing the errors in the code of the software.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DFD for Library Management System
What is DFD(Data Flow Diagram)?
Software Engineering | Black box testing
Software Engineering | Software Design Process
System Testing
RUP and its Phases
Software Engineering | Seven Principles of software testing
Software Development Life Cycle (SDLC)
Software Engineering | Incremental process model
Software Engineering | Rapid application development model (RAD)
Multi-Line Statements in Python

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −
total = item_one + \
        item_two + \
        item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
       'Thursday', 'Friday']
Maximum Collatz sequence length | Practice | GeeksforGeeks

Starting with any positive integer N, we define the Collatz sequence corresponding to N as the numbers formed by the following operations:
If N is even, N→ N/2
if N is odd,   N→ 3N+ 1
It is conjectured but not yet proven that no matter which positive integer we start with; we always end up with 1.
For example, 10 → 5  → 16  → 8  → 4  → 2  → 1. You have to give the maximum collatz sequence length among all the numbers from 1 to N(both included).

Example 1:
Input: N = 1
Output: 1
Explaination: Here N can have only one 
value 1.

Example 2:
Input: N = 3
Output: 8
Explaination: For N= 3 we need to check 
sequence length when sequence starts with 
1, 2, and 3.
when sequence starts with 1, it's : 1 
length = 1
when sequence starts with 2, it's : 2->1, 
length = 2
when sequence starts with 3, it's : 
3->10->5->16->8->4->2->1, length = 8.


Your Task:
You do not need to read input or print anything. Your task is to complete the function collatzLength()which takes N as input parameter and returns the maximum collatz sequence length.

Expected Time Complexity:O(N)
Expected Auxiliary Space: O(N)

Constraints:
1 < N < 106
0
hazemk5375 months ago
it is brute force or dp
0
hazemk537
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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

There are three ways to access JavaScript properties −
Using dot property access: object.property
Using square brackets notation: object[‘property’]
Using object destructuring: let {property} = object
Following is the code for accessing JavaScript object properties −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Access JavaScript object properties</h1>
<div><pre class="sample">{a:22,b:44}</pre></div>
<div class="result"></div>
<button class="Btn">Access</button>
<h3>Click on the above button to access object properites</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj = { a: 22, b: 44 };
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML += "obj.a = " + obj.a + "<br>";
      resEle.innerHTML += "obj['a'] = " + obj["a"] + "<br>";
      let { a } = obj;
      resEle.innerHTML += "{a}=obj = " + a + "<br>";
   });
</script>
</body>
</html>
On clicking the ‘Access’ button −
Anonymous object in Java

Yes, we can use a method on an object without assigning it to any reference. 
Live Demo
public class Tester {
   public String message(){
      return "Hello World!";
   }
   public static void main(String[] args) {
      System.out.println(new Tester().message());
   }
 }   
Here we've used message() method on new Tester() which is an anonymous object.
F# - Bitwise Operators

Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &&& (bitwise AND), ||| (bitwise OR), and ^^^ (bitwise exclusive OR) are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
A&&&B = 0000 1100
A|||B = 0011 1101
A^^^B = 0011 0001
~~~A = 1100 0011
The Bitwise operators supported by F# language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
let a : int32 = 60 // 60 = 0011 1100
let b : int32 = 13 // 13 = 0000 1101
let mutable c : int32 = 0

c <- a &&& b // 12 = 0000 1100
printfn "Line 1 - Value of c is %d" c

c <- a ||| b // 61 = 0011 1101
printfn "Line 2 - Value of c is %d" c

c <- a ^^^ b // 49 = 0011 0001
printfn "Line 3 - Value of c is %d" c

c <- ~~~a // -61 = 1100 0011
printfn "Line 4 - Value of c is %d" c

c <- a <<< 2 // 240 = 1111 0000
printfn "Line 5 - Value of c is %d" c

c <- a >>> 2 // 15 = 0000 1111
printfn "Line 6 - Value of c is %d" c
When you compile and execute the program, it yields the following output −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is 49
Line 5 - Value of c is 240
Line 6 - Value of c is 15

 Print
 Add Notes
 Bookmark this page
Downcasting in Java

Yes, a variable can be downcast to its lower range substitute by casting. It may lead to data loss although. See the example below −
 Live Demo
public class Tester {
   public static void main(String[] args) {
      int a = 300;
      byte b = (byte)a;
      System.out.println(b);
   }
}
It will print output as
44
XSD - Complex Empty Element

Complex Empty Element can only have attribute, but no content. See the following example −
<student rollno = "393" />

We can declare Complex Empty elements using the following methods −
Define a complex type element "StudentType" and then create element student of type "StudentType".
<xs:complexType name = "StudentType">
   <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>   
</xs:complexType>

<xs:element name = 'student' type = 'StudentType' />			 
Define an element of complexType with complexContent. ComplexContent specifies that the content of the element is to be restricted.
<xs:element name = "student">
   <xs:complexType>
      <xs:complexContent>
         <xs:restriction base = "xs:integer">
            <xs:attribute name = "rollno" type = "xs:positiveInteger"/>
         </xs:restriction>
      </xs:complexContent>
   </xs:complexType>
</xs:element>		 
Define an element of complexType with required attribute element only.
<xs:element name = "student">
   <xs:complexType>
      <xs:attribute name = "rollno" type = "xs:positiveInteger"/>
   </xs:complexType>
</xs:element>
 Print
 Add Notes
 Bookmark this page
Get a list of a particular column values of a Pandas DataFrame - GeeksforGeeks

28 Jul, 2020
In this article, we’ll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get marks of all the students in a particular subject, get phone numbers of all employees, etc. Let’s see how we can achieve this with the help of some examples.
Example 1: We can have all values of a column in a list, by using the tolist() method.
Syntax: Series.tolist().
Return type: Converted series into List.
Code:
Python3
# import pandas libraeyimport pandas as pd  # dictionarydict = {'Name': ['Martha', 'Tim',                'Rob', 'Georgia'],         'Marks': [87, 91,                   97, 95]}  # create a dataframe objectdf = pd.DataFrame(dict)  # show the dataframeprint(df)  # list of values of 'Marks' columnmarks_list = df['Marks'].tolist()  # show the listprint(marks_list)
Output:
Example 2: We’ll see how we can get the values of all columns in separate lists.
Code:
Python3
# import pandas libraryimport pandas as pd  # dictionarydict = {'Name': ['Martha', 'Tim',                 'Rob', 'Georgia'],        'Marks': [87, 91,                  97, 95]}  # create a dataframe objectdf = pd.DataFrame(dict)  # show the dataframeprint(df)  # iterating over and calling # tolist() method for # each columnfor i in list(df):        # show the list of values      print(df[i].tolist())
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
C# Aggregate() method

The Aggregate() method applies an accumulator function over a sequence.
The following is our array −
string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"};
Now use the Aggregate() method. We have set the ssed value as “DemoFive” for comparison.
string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower());
Here, the resultant string should have more number of characters than the initial seed value i.e. “DemoFive”.
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"};
      string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length >       longest.Length ? next : longest,str => str.ToLower());
      Console.WriteLine("The string with more number of characters: {0}", res);
   }
}
The string with more number of characters: demothree