code-rag-bench/online-tutorials huggingface dataset:
Deep Copy and Shallow Copy in Java

Both deep copy and shallow copy refer to creating a copy of the object given in different ways −
This basically creates a new instance of the object and copies all the data from the original data set to the newly created instance. This means the newly created instance has to be specifically cast into the original object. It is also known as ‘shallow cloning’.
 Live Demo
import java.util.* ;
class Demo{
   private int[] my_data;
   public Demo(int[] my_vals){
      my_data = my_vals;
   }
   public void display_data(){
      System.out.println(Arrays.toString(my_data) );
   }
}
public class Use_Demo{
   public static void main(String[] args){
      int[] my_vals = {56, 89, 91};
      Demo my_inst = new Demo(my_vals);
      my_inst.display_data();
      my_vals[0] = 65;
      my_inst.display_data();
   }
}
[56, 89, 91]
[65, 89, 91]
A class named Demo contains a variable, and a constructor that copies elements of the array into a
new array. Another function named ‘display_data’ displays this array of data. In the main function,
an instance is created, the array is defined, and the function is called. Relevant output is displayed
on the console with all the changes reflecting in it.
This is used when a separate copy of the data is required for different purpose or usage. All the
members of the class need to implement the ‘Cloneable’ interface and override the ‘clone’ method.
 Live Demo
import java.util.*;
class Demo{
   private int[] my_data;
   public Demo(int[] my_vals){
      my_data = new int[my_vals.length];
      for (int i = 0; i < my_data.length; i++){
         my_data[i] = my_vals[i];
      }
   }
   public void display_data(){
      System.out.println(Arrays.toString(my_data));
   }
}
public class Use_Demo{
   public static void main(String[] args){
      int[] my_vals = {56, 89, 91};
      Demo my_inst = new Demo(my_vals);
      my_inst.display_data();
      my_vals[0] = 65;
      my_inst.display_data();
   }
}
[56, 89, 91]
[56, 89, 91]
A class named Demo contains a variable, and a constructor that iterates through the array, and
copies it to another array. Another function named ‘display_data’ displays this array of data. In the
main function, an instance is created, the array is defined, and the function is called. Relevant output is displayed on the console with all the changes reflecting in it.
Powershell - Do..While Loop

The following scripts demonstrates the do.. while loop.
> $array = @("item1", "item2", "item3")
$counter = 0;

do {
   $array[$counter]
   $counter += 1
} while($counter -lt $array.length)
Python Tuple max() Method

Python tuple method max() returns the elements from the tuple with maximum value.
Following is the syntax for max() method −
max(tuple)

tuple − This is a tuple from which max valued element to be returned.
tuple − This is a tuple from which max valued element to be returned.
This method returns the elements from the tuple with maximum value.
The following example shows the usage of max() method.
#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)
print "Max value element : ", max(tuple1)
print "Max value element : ", max(tuple2)
When we run above program, it produces following result −
Max value element :  zara
Max value element :  700
create_web_element driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around create_web_element driver method in Selenium. create_web_element method is used to create a web element with the specified element_id. One can store an element’s id and can create a web element much faster later when required
Syntax –
driver.create_web_element(element_id)
Example –Now one can use create_web_element method as a driver method as below –
element_clone = driver.create_web_element(id)


To demonstrate, create_web_element method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # get id of elementid = element._id  # create another elementelement_clone = driver.create_web_element(id)
Output –New element clone is created from saved id as verified below –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
How to Reset MySQL Root Password in Windows using cmd?

28 Feb, 2021
There might arise a situation where you need to reset the root password for your MySQL database.  It can be because you forgot your password or you need to change the password for security reasons. 
In this article, we will look into the process of resetting the MySQL password using Windows cmd. To do so follow the below steps:
Step 1: Stop the MySQL server
Begin by checking if you’re logged in as an administrator.
Press Win+R (hold the Windows/Super key, and press “r”.) Once the “Run” box appears type:
services.msc
Click OK.
Scroll down the list of services to find the MySQL service. Right-click that entry then left-clicks Stop.
Step 2: Launch a Text Editor
Click on the menu and search for Notepad.
Alternatively, you can use the path: Menu > Windows Accessories > Notepad.
Step 3: Create a New Text File with the Password Command
Enter the following line into the text editor:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
Make sure you keep the quote marks and semicolon. Replace NewPassword with the password of your choice.
Use the File > Save As menu to save the file to the root of your hard drive (C:\ ). Choose a filename that makes sense, such as mysql-init.txt.
Consequently, the localhost command will make the password change on your local system. If you’re trying to change the password on a system over the network, substitute the hostname for localhost.
Step 4: Open a Command Prompt
Press Ctrl+Shift+Esc.
Then, click on the File menu > Run new task.
Type cmd.exe, and check the box to run as administrator.
Click OK.
Step 5: Restart the MySQL Server with Your New Config File
 Navigate to the MySQL directory using the command prompt:
cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"
Accordingly, the command line will show that you’re working in this folder.
 Enter the following:
mysqld --init-file=C:\\mysql-init.txt
Note that there are two slashes after the C: prompt.
Also, if you chose a different name in Step 2, use the same name after the double slash.
Step 6: Clean up
Now, you can log into your MySQL server as root using the new password.
Double-check to make sure it works. If you have unique configuration options (such as launching MySQL with a -defaults-file option), go ahead and do so.
Once MySQL launches, and you’ve confirmed the password change, delete the C:\myswl-init.txt file.
At this stage, you have successfully reset the root password for your MySQL database.
DBMS
SQL
TechTips
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Nested list comprehension in python

A nested list is a list within a list. Python provides features to handle nested list gracefully and apply common functions to manipulate the nested lists. In this article we will see how to use list comprehension to create and use nested lists in python.
Creating a matrix involves creating series of rows and columns. We can use for loop for creating the matrix rows and columns by putting one python list with for loop inside another python list with for loop.
 Live Demo
matrix = [[m for m in range(4)] for n in range(3)]
print(matrix)
Running the above code gives us the following result:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

We can use the list comprehension with filtering feature by using the for loop within the sub-lists. Below we have a 2 dimensional list with one layer of sub-list inside a bigger list. We access selective elements from each of these nested lists. By using a filter condition.
 Live Demo
years = [['January', 'February', 'March'], ['April', 'May', 'June'], ['July', 'August', 'September'],['October','November','December']]
# Nested List comprehension with an if condition
years = [years for sublist in years for years in sublist if len(years) <= 5]
print(years)
Running the above code gives us the following result:
['March', 'April', 'May', 'June', 'July']

We can also take a nested list and flatten it by creating a single list without having any sub-list inside it.
 Live Demo
nested_list = [[1] ,[17, 19], [21,23,25], [32,35,37,39]]
# Nested List Comprehension to flatten a given 2-D matrix
flattened_list = [value for sublist in nested_list for value in sublist]
print(flattened_list)
Running the above code gives us the following result:
[1, 17, 19, 21, 23, 25, 32, 35, 37, 39]
GATE | GATE-CS-2015 (Set 2) | Question 20

28 Jun, 2021
A binary tree T has 20 leaves. The number of nodes in T having two children is(A) 18(B) 19(C) 17(D) Any number between 10 and 20Answer: (B)Explanation:
Sum of all degrees = 2 * |E|.
Here considering tree as a k-ary tree :

Sum of degrees of leaves + Sum of degrees for Internal Node except root + Root's degree = 2 * (No. of nodes - 1).

Putting values of above terms,

L + (I-1)*(k+1) + k = 2 * (L + I - 1)

L + k*I - k + I -1 + k = 2*L + 2I - 2

L + K*I + I - 1 = 2*L + 2*I - 2

K*I + 1 - I = L

(K-1)*I + 1 = L

Given k = 2, L=20

==> (2-1)*I + 1 = 20
==> I = 19
==> T has 19 internal nodes which are having two children.

See Handshaking Lemma and Interesting Tree Properties for proof.
This solution is contributed by Anil Saikrishna DevarasettyQuiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE IT 2006 | Question 20
How can I update MySQL table after quoting the values of a column with a single quote?

As we know that with the help of QUOTE() function we can put the values of a column in single quotes. By using QUOTE() function with UPDATE clause we can update the table having quoted values. We need to give column name as the parameter of QUOTE() function. Following example will update the table ‘examination_btech’ after putting the values of column ‘Course’ in single quotes.
mysql> UPDATE examination_btech SET Course = QUOTE(Course);
Query OK, 10 rows affected (0.05 sec)

mysql> Select * from examination_btech;
+--------+----------+----------+
| RollNo | Name     | Course   |
+--------+----------+----------+
| 1      | Rahul    | 'B.Tech' |
| 2      | Raman    | 'B.Tech' |
| 3      | Sahil    | 'B.Tech' |
| 4      | Shalini  | 'B.Tech' |
| 5      | Pankaj   | 'B.Tech' |
| 6      | Mohan    | 'B.Tech' |
| 7      | Yash     | 'B.Tech' |
| 8      | digvijay | 'B.Tech' |
| 9      | Gurdas   | 'B.Tech' |
| 10     | Preeti   | 'B.Tech' |
+--------+----------+----------+
10 rows in set (0.00 sec)
Python MongoDB - Query

While retrieving using find() method, you can filter the documents using the query object. You can pass the query specifying the condition for the required documents as a parameter to this method.
Following is the list of operators used in the queries in MongoDB.
Following example retrieves the document in a collection whose name is sarmista.
from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['sdsegf']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
   {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
   {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
   {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
   {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
   {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")

#Retrieving data
print("Documents in the collection: ")

for doc1 in coll.find({"name":"Sarmista"}):
   print(doc1)
Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}

Following example retrieves the document in a collection whose age value is greater than 26.
from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['ghhj']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
   {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
   {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
   {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
   {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
   {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")

#Retrieving data
print("Documents in the collection: ")

for doc in coll.find({"age":{"$gt":"26"}}):
   print(doc)
Data inserted ......
Documents in the collection:
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Python | Remove additional spaces in list

08 Apr, 2019
Sometimes, we have a list that contains strings and spaces in between them. We desire to have uniformity, so that later if we decide them, we just have single spaces between the lists. Hence its sometimes necessary to remove the additional unnecessary spaces between the words in a list.
Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + enumerate()In this method we create a whole new list rather than modifying the original one, and check for element and its preceding element for spaces and add only add one occurrence of space and leaving the rest.
# Python3 code to demonstrate # removing multiple spaces# using list comprehension + enumerate()  # initializing list of liststest_list = ["GfG", "", "", "", "", "is", "", "", "best"]  # printing original list print("The original list : " +  str(test_list))  # using list comprehension + enumerate()# removing multiple spacesres = [val for idx, val in enumerate(test_list)       if val or (not val and test_list[idx - 1])]  # printing result print("The list after removing additional spaces :  " + str(res))
The original list : ['GfG', '', '', '', '', 'is', '', '', 'best']
The list after removing additional spaces :  ['GfG', '', 'is', '', 'best']

 
Method #2 : Using list comprehension + zip() + list slicingIn this method, we take a pair at a time and check if it’s both elements are empty, if so, we discard it. If anyone is empty or both are non-empty, we keep it in the list.
# Python3 code to demonstrate # removing multiple spaces# using list comprehension + zip() + list slicing  # initializing list of liststest_list = ["GfG", "", "", "", "", "is", "", "", "best"]  # printing original list print("The original list : " +  str(test_list))  # using list comprehension + zip() + list slicing# removing multiple spacesres = test_list[ : 1] + [j for i, j in      zip(test_list, test_list[1 : ]) if i or j]  # printing result print("The list after removing additional spaces :  " + str(res))
The original list : ['GfG', '', '', '', '', 'is', '', '', 'best']
The list after removing additional spaces :  ['GfG', '', 'is', '', 'best']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python | Print unique rows in a given boolean matrix using Set with tuples

26 Dec, 2017
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn’t matter.
Examples:
Input:
    mat = [[0, 1, 0, 0, 1],
             [1, 0, 1, 1, 0],
             [0, 1, 0, 0, 1],
             [1, 1, 1, 0, 0]]
Output:
          (1, 1, 1, 0, 0)
          (0, 1, 0, 0, 1)
          (1, 0, 1, 1, 0)

We have existing solution for this problem please refer link. We can solve this problem in python quickly using Set data structure. Approach is very simple.
We are given list of boolean values list, put all rows (list) in set because set contains unique values.Since list is an unhashable type for set because it is mutable that’s why first we convert each row (list) into tuple then we put all tuple in set.Resultant set will contain only unique valued tuples (row).
We are given list of boolean values list, put all rows (list) in set because set contains unique values.
Since list is an unhashable type for set because it is mutable that’s why first we convert each row (list) into tuple then we put all tuple in set.
Resultant set will contain only unique valued tuples (row).
# Python program to Print unique rows in a # given boolean matrix using Set with tuples  # Function to print unique rows in a given boolean matrix  def uniqueRows(input):      # convert each row (list) into tuple    # we are mapping tuple function on each row of     # input matrix    input = map(tuple, input)      # put all rows in set    result = set(input)      # print all unique rows    for row in list(result):        print (row)  # Driver programif __name__ == "__main__":    input = [[0, 1, 0, 0, 1],             [1, 0, 1, 1, 0],             [0, 1, 0, 0, 1],             [1, 1, 1, 0, 0]]    uniqueRows(input)
Output:
(1, 1, 1, 0, 0)
(0, 1, 0, 0, 1)
(1, 0, 1, 1, 0)

python-tuple
Matrix
Python
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
QTP - Environment Variables

QTP environment variables are special types of variables that can be accessed by all actions, function libraries, and recovery scenarios. There are in-built environment variables for Windows that are available to all the applications running on that particular system, but QTP environment variables are only available to that particular test script during run-time.
Built-in Environment Variables − provides a range of environment parameters that can provide information such as test name, action name, the test path, local host name, the operating system name, type and its version. The Environment Variable names can be accessed by navigating to "File" → "Test Settings" → "Environment" Tab.
User defined Internal − User defined variables can be saved by selecting "User Defined" in the Environment Tab Window. The "+" button is clicked to enter Parameter Name and Value as shown below −
User Defined External − User Defined Variables can be stored in an external file as a .xml file and can be loaded into the test as shown in the figure given below. It can also be loaded dynamically during run-time as explained below in one of the examples.
1. ExternalFileName Property − Returns the name of the loaded external environment variable file specified in the Environment tab of the Test Settings dialog box. If no external environment variable file is loaded, this property returns an empty string.
x = Environment.ExternalFileName 
print x

2. LoadFromFile Method − Loads the specified environment variable file (.xml) dynamically during run time. When using this method, the environment variables need not be added manually into the Environment Tab.
Environment.LoadFromFile "D:\config.xml"
b = Environment.Value("Browser")
print b
3. Value Property − Retrieves the value of environment variables. We can also set the value of user-defined internal environment variables using this property.
' Get the Value of the InBuilt Environment Variables
a = Environment.Value("OS")
print a
b = Environment.Value("ActionName")
print b
  
'Loaded from External File
Environment.LoadFromFile "D:\config.xml"
c = Environment.Value("Browser")
An interesting time complexity question

30 Oct, 2015
What is the time complexity of following function fun()?
int fun(int n){        for (int i = 1; i <= n; i++)    {        for (int j = 1; j < n; j += i)        {            // Some O(1) task        }    }    }
For i = 1, the inner loop is executed n times.For i = 2, the inner loop is executed approximately n/2 times.For i = 3, the inner loop is executed approximately n/3 times.For i = 4, the inner loop is executed approximately n/4 times...........................................................................................................................For i = n, the inner loop is executed approximately n/n times.
So the total time complexity of the above algorithm is (n + n/2 + n/3 + ... + n/n)
Which becomes n * (1/1 + 1/2 + 1/3 + ... + 1/n)
The important thing about series (1/1 + 1/2 + 1/3 + ... + 1/n) is, it is equal to Θ(Logn) (See this for reference). So the time complexity of the above code is Θ(nLogn).
As a side note, the sum of infinite harmonic series is counterintuitive as the series diverges. The value of  is ∞. This is unlike geometric series as geometric series with ratio less than 1 converges.
Reference:http://en.wikipedia.org/wiki/Harmonic_series_%28mathematics%29#Rate_of_divergencehttp://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap03.htm
This article is contributed by Rahul. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Functions | Question 7

28 Jun, 2021
What is the output of the following program :
import resentence = 'horses are fast'regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')matched = re.search(regex, sentence)print(matched.groupdict())
(A) {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}(B) (‘horses’, ‘are’, ‘fast’)(C) ‘horses are fast’(D) ‘are’Answer: (A)Explanation: This function returns a dictionary that contains all the matches.Quiz of this Question
Functions
Python-Quizzes
Python-Quizzes-Functions
Python-Quizzes
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python-Quizzes | Python List Quiz | Question 4
Python-Quizzes | Python List Quiz | Question 5
Python-Quizzes | Python Dictionary Quiz | Question 25
Output of Python Program - Dictionary (set 25)
Why do people prefer Selenium with Python?
Python-Quizzes | Python Dictionary Quiz | Question 23
Python | Animated Banner showing 'GeeksForGeeks'
Python-Quizzes | Data Type | Question 3
Python | Output Type | Question 4
Python-Quizzes | Python Dictionary Quiz | Question 1
Octal numbers in c - GeeksforGeeks

29 Aug, 2017
There are some less known facts in C related to octal numbers. Let us look at the below example code first.
Examples:
// program to show octal number interpretation#include <stdio.h>  int main(){    int x = 012;    printf("%d", x);    return 0;}
Output:
10

Surprisingly the output is not 12. This happens because an integer digit preceded by 0 is interpreted as an octal number. An octal number for decimal value 12 is 10. But what if x equals 092 well then the compiler will show an error because 92 is not a valid octal number.
Octal escape sequenceIn C octal escape sequence is represented by \ followed by three octal digits. Note that one or two octal digits are also allowed. An octal sequence ends either ends after three octal digits following \ or when a digit after \ is not an octal digit.
Examples:
// program to show octal escape sequence#include <stdio.h>int main(){    char str[] = "31\01267";    printf("%s", str);    return 0;}
Output:
31
67

If we look at the output then after 31 a newline character is printed and then 67 is printed. This is because \012 is interpreted as \n or new line character.Actually, \012 represents octal escape sequence for \n or newline. Octal value of 12 in decimal is 10 and in ASCII it represents newline.
// program to show octal escape sequence#include <stdio.h>int main(){    char str[] = "31\12367";    printf("%s", str);    printf("\n");    char str2[] = "11\77967";    printf("%s", str2);    return 0;}
Output:
31S67
11?967

In str \123 is interpreted as octal escape sequence and value of octal 123 is 83 and character corresponding to it in my machine is ‘S’ as my machine uses ASCII. It can be different if character set used is not ASCII.In str2 \77 is interpreted as an octal escape sequence and not \779. So, the value of 77 is 63 in decimal and in ASCII it is ‘?’.
This article is contributed by Ashish Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
c-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
rand() and srand() in C/C++
Substring in C++
fork() in C
std::string class in C++
Enumeration (or enum) in C
TCP Server-Client implementation in C
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Set width between table cells with CSS

The border-spacing specifies the width between table cells. It can take either one or two values; these should be units of length.
You can try to run the following code to set the width of table cells:
<html>
   <head>
      <style>
         table.one {
            border-collapse:separate;
            width:300px;
            border-spacing:15px 40px;
         }
      </style>
   </head>
   <body>
      <table class = "one" border = "2">
         <caption>The border-spacing property</caption>
         <tr><td> India </td></tr>
         <tr><td> UK </td></tr>
      </table>
      <br />
   </body>
</html>
Setting the aspect ratio of a 3D plot in Matplotlib

To set the aspect ratio of a 3D plot in matplotlib, we can take the following steps−
Using figure() method, create a new figure or activate an existing figure.
Get the current axes, creating one if necessary, with projection='3d'.
Create data points, R, Y and z, using numpy.
Create a surface plot using R, Y and z.
Set the aspect ratio using set_aspect('auto').
Save the figure using savefig() method.
from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.gca(projection='3d')
R, Y = np.meshgrid(np.arange(0, 100, 1), np.arange(0, 60, 1))
z = 0.1 * np.abs(np.sin(R / 40) * np.sin(Y / 6))
ax.plot_surface(R, Y, z, cmap=cm.rainbow, linewidth=0)
ax.set_aspect('auto')
ax.azim = -160
ax.elev = 30
fig.savefig('data.png')
plt.show()
Concatenate two strings using Operator Overloading in Python - GeeksforGeeks

10 Jul, 2020
Operator Overloading refers to using the same operator to perform different tasks by passing different types of data as arguments. To understand how ‘+’ operator works in two different ways in python let us take the following example
Python3
# taking two numbersa = 2b = 3  # using '+' operator add themc = a+b  # printing the resultprint("The sum of these two numbers is ", c)
Output:
The sum of these two numbers is  5

In this example we used ‘+’ operator to add numbers, now let us take one more example to understand how ‘+’ operator is used to concatenate strings.
Python3
# taking two strings from the usera = 'abc'b = 'def'  # using '+' operator concatenate themc = a+b  # printing the resultprint("After Concatenation the string becomes", c)
Output:
After Concatenation the string becomes abcdef

For a better understanding of operator overloading, here is an example where a common method is used for both purposes.
Python3
# let us define a class with add methodclass operatoroverloading:        def add(self, a, b):        self.c = a+b        return self.c    # creating an object of classobj = operatoroverloading()  # using add method by passing integers# as argumentresult = obj.add(23, 9)print("sum is", result)  # using same add method by passing strings# as argumentresult = obj.add("23", "9")print("Concatenated string is", result)
Output:
sum is 32
Concatenated string is 239

Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
IMS DB - Programming

An application program which includes DL/I calls cannot execute directly. Instead, a JCL is required to trigger the IMS DL/I batch module. The batch initialization module in IMS is DFSRRC00. The application program and the DL/I module execute together. The following diagram shows the structure of an application program which includes DL/I calls to access a database.
The application program interfaces with IMS DL/I modules via the following program elements −
An ENTRY statement specifies that the PCBs are utilized by the program.
An ENTRY statement specifies that the PCBs are utilized by the program.
A PCB-mask co-relates with the information preserved in the pre-constructed PCB which receives return information from the IMS.
A PCB-mask co-relates with the information preserved in the pre-constructed PCB which receives return information from the IMS.
An Input-Output Area is used for passing data segments to and from the IMS database.
An Input-Output Area is used for passing data segments to and from the IMS database.
Calls to DL/I specify the processing functions such as fetch, insert, delete, replace, etc.
Calls to DL/I specify the processing functions such as fetch, insert, delete, replace, etc.
Check Status Codes is used to check the SQL return code of the processing option specified to inform whether the operation was successful or not.
Check Status Codes is used to check the SQL return code of the processing option specified to inform whether the operation was successful or not.
A Terminate statement is used to end the processing of the application program which includes the DL/I.
A Terminate statement is used to end the processing of the application program which includes the DL/I.
As of now, we learnt that the IMS consists of segments which are used in high-level programming languages to access data. Consider the following IMS database structure of a Library which we have seen earlier and here we see the layout of its segments in COBOL −
01 LIBRARY-SEGMENT.
   05 BOOK-ID        PIC X(5).
   05 ISSUE-DATE     PIC X(10).
   05 RETURN-DATE    PIC X(10).
   05 STUDENT-ID     PIC A(25).
	
01 BOOK-SEGMENT.
   05 BOOK-ID        PIC X(5).
   05 BOOK-NAME      PIC A(30).
   05 AUTHOR         PIC A(25).
	
01 STUDENT-SEGMENT.
   05 STUDENT-ID     PIC X(5).
   05 STUDENT-NAME   PIC A(25).
   05 DIVISION       PIC X(10).

The structure of an IMS application program is different from that of a Non-IMS application program. An IMS program cannot be executed directly; rather it is always called as a subroutine. An IMS application program consists of Program Specification Blocks to provide a view of the IMS database.
The application program and the PSBs linked to that program are loaded when we execute an application program which includes IMS DL/I modules. Then the CALL requests triggered by the application programs are executed by the IMS module.
The following IMS services are used by the application program −
Accessing database records
Issuing IMS commands
Issuing IMS service calls
Checkpoint calls
Sync calls
Sending or receiving messages from online user terminals
 Print
 Add Notes
 Bookmark this page
How to uninstall software using Package management in PowerShell?

There are mainly 3 methods by which you can uninstall software using PowerShell.
WMI Method.
WMI Method.
Using Package provider
Using Package provider
Uninstallation String.
Uninstallation String.
Here, we will discuss the method to uninstall software using Package management.
You can uninstall the software or packages which are installed with the package providers. You can get the list of the package providers using Get-PackageProvider command.
PS C:\Users\Administrator> Get-PackageProvider | Select Name, Version
Name          Version
----          -------
msi           3.0.0.0
msu           3.0.0.0
PowerShellGet 1.0.0.1
Programs      3.0.0.0
So the packages which are installed with msi, msu, Programs and PowerShellGet can be uninstalled with Uninstall-Package command.
Get-Package -Name 'Vmware tools' | ft -AutoSize
If the package exists, you can get the details of the package. In the below example, there is a package version, Source path, and the Provider Name retrieved.
Name       Version                Source                                     ProviderName
----       -------                ------                                     ------------
VMware    Tools 11.0.6.15940789    C:\Program Files\VMware\VMware Tools\ msi
To uninstall a package or software, you can pipeline Uninstall-Package command or directly run the command providing the package name.
Get-Package -Name 'Vmware tools' | Uninstall-Package
Or
Uninstall-Package -Name 'Vmware tools' -Force
Force command is to run command forcefully without asking user permission.
How to get the sum of the numbers in even positions in an array?

There are multiple ways to get the sum of numbers in even positions in an array. Let us look at 3 of these −
We can directly use a for loop and get the sum.
let arr = [1, 2, 3, 4, 5, 6];
let sum = 0;
for(let i = 0; i < arr.length; i += 2) {
   sum += arr[i];
}
console.log(sum);
9
In this method, instead of iterating explicitly over the array, we can instead use the built in function forEach to iterate. It takes a function that is executed for each element.
let arr = [1, 2, 3, 4, 5, 6];
let sum = 0;
arr.forEach((elem, i) => {
   if(i % 2 === 0) {
      sum += elem;
   }
});
console.log(sum);
9
We can use filter and reduce functions to calculate the sum. First we filter the odd indices using filter then we calculate the sum using reduce.
let arr = [1, 2, 3, 4, 5, 6];
let sum = arr.filter((_, i) => i % 2 === 0).reduce((curr, acc) => acc + curr, 0)
console.log(sum);
9
D3.js symbolTriangle symbol - GeeksforGeeks

07 Sep, 2020
The d3.symbolTriangle is a symbol type in D3.js. It is a square-shaped symbol type that can be used.
Syntax:
d3.symbolTriangle 
Example 1:
<!DOCTYPE html><html><head>    <meta charset="utf-8">      <script src=        "https://d3js.org/d3.v5.min.js">    </script></head>  <body>      <h1 style="text-align: center;         color: green;">        GeeksforGeeks    </h1>      <h3 style="text-align: center;">        D3.js | symbolTriangle     </h3>      <center>    <svg id="gfg" width="100"          height="100"></svg>    </center>      <script>        // symbolTriangle        var sym = d3.symbol().type(d3.symbolTriangle).size(500);        d3.select("#gfg")            .append("path")            .attr("d", sym)            .attr("fill", "green")            .attr("transform", "translate(50, 50)");      </script></body>  </html>
Output:
Example 2:
<!DOCTYPE html>    <html>    <head>        <meta charset="utf-8">          <script src=            "https://d3js.org/d3.v5.min.js">        </script>    </head>      <body>          <h1 style="text-align: center;             color: green;">            GeeksforGeeks        </h1>          <h3 style="text-align: center;">            D3.js | symbolTriangle        </h3>          <center>        <svg id="gfg" width="100"             height="100"></svg>        </center>          <script>            // symbolTriangle             var sym = d3.symbol().type(d3.symbolTriangle).size(500);            d3.select("#gfg")                .append("path")                .attr("d", sym)                .attr("fill", "none")                .attr("stroke", "green")                .attr("stroke-width", "5px")                .attr("transform", "translate(50, 50)");        </script>    </body>      </html>
Output:
D3.js
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Swing Examples - Show Input Dialog with Text Box

Following example showcase how to get user input from a textbox in a dialog in swing based application.
We are using the following APIs.
JOptionPane − To create a standard dialog box.
JOptionPane − To create a standard dialog box.
JOptionPane.showInputDialog() − To show the message alert with input options.
JOptionPane.showInputDialog() − To show the message alert with input options.
options as null − To show a text box in input box.
options as null − To show a text box in input box.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JLabel label = new JLabel();
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            String result = (String)JOptionPane.showInputDialog(
               frame,
               "Select one of the color", 
               "Swing Tester",            
               JOptionPane.PLAIN_MESSAGE,
               null,            
               null, 
               "Red"
            );
            if(result != null && result.length() > 0){
               label.setText("You selected:" + result);
            }else {
               label.setText("None selected");
            }
         }
      });

      panel.add(button);
      panel.add(label);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
} 
 Print
 Add Notes
 Bookmark this page
statvfs() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint

int statvfs(const char *path, struct statvfs *buf); 
int fstatvfs(int fd, struct statvfs *buf); 


  struct statvfs {
    unsigned long  f_bsize;    /* file system block size */
    unsigned long  f_frsize;   /* fragment size */
    fsblkcnt_t     f_blocks;   /* size of fs in f_frsize units */
    fsblkcnt_t     f_bfree;    /* # free blocks */
    fsblkcnt_t     f_bavail;   /* # free blocks for non-root */
    fsfilcnt_t     f_files;    /* # inodes */
    fsfilcnt_t     f_ffree;    /* # free inodes */
    fsfilcnt_t     f_favail;   /* # free inodes for non-root */
    unsigned long  f_fsid;     /* file system ID */
    unsigned long  f_flag;     /* mount flags */
    unsigned long  f_namemax;  /* maximum filename length */
  };


Here the types
fsblkcnt_t and
fsfilcnt_t are defined in
<sys/types.h>. Both used to be
unsigned long. 

The field
f_flag is a bit mask (of mount flags, see
mount(8)).
Bits defined by POSIX are


It is unspecified whether all members of the returned struct
have meaningful values on all filesystems.


fstatvfs() returns the same information about an open file referenced by descriptor
fd. 

The current glibc implementation of



   pathconf(path, _PC_REC_XFER_ALIGN);
   pathconf(path, _PC_ALLOC_SIZE_MIN);
   pathconf(path, _PC_REC_MIN_XFER_SIZE);


uses the
f_frsize, f_frsize, and
f_bsize fields of the return value of
statvfs(path,buf). 
statfs (2)
statfs (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Dropout in Neural Networks - GeeksforGeeks

16 Jul, 2020
The concept of Neural Networks is inspired by the neurons in the human brain and scientists wanted a machine to replicate the same process. This craved a path to one of the most important topics in Artificial Intelligence. A Neural Network (NN) is based on a collection of connected units or nodes called artificial neurons, which loosely model the neurons in a biological brain. Since such a network is created artificially in machines, we refer to that as Artificial Neural Networks (ANN). This article assumes that you have a decent knowledge of ANN. More about ANN can be found here.Now, let us go narrower into the details of Dropout in ANN.
Problem:
When a fully-connected layer has a large number of neurons, co-adaption is more likely to happen. Co-adaptation refers to when multiple neurons in a layer extract the same, or very similar, hidden features from the input data. This can happen when the connection weights for two different neurons are nearly identical.
This poses two different problems to our model:
Wastage of machine’s resources when computing the same output.
If many neurons are extracting the same features, it adds more significance to those features for our model. This leads to overfitting if the duplicate extracted features are specific to only the training set.
Solution to the problem:
As the title suggests, we use dropout while training the NN to minimize co-adaption.In dropout, we randomly shut down some fraction of a layer’s neurons at each training step by zeroing out the neuron values. The fraction of neurons to be zeroed out is known as the dropout rate, . The remaining neurons have their values multiplied by  so that the overall sum of the neuron values remains the same.
The two images represent dropout applied to a layer of 6 units, shown at multiple training steps. The dropout rate is 1/3, and the remaining 4 neurons at each training step have their value scaled by x1.5. Thereby, we are choosing a random sample of neurons rather than training the whole network at once. This ensures that the co-adaption is solved and they learn the hidden features better.Dropout can be applied to a network using TensorFlow APIs as,
tf.keras.layers.Dropout(    rate)  # rate: Float between 0 and 1. # The fraction of the input units to drop.
Neural Network
Tensorflow
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
Support Vector Machine Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to install Python on Windows? - GeeksforGeeks

05 Oct, 2021
Prerequisite: Python Language Introduction Before we start with how to install Python3 on Windows, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions- Python 2 and Python 3. Both are quite different.
Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:
To check if your device is pre-installed with Python or not, just go to the Command line(search for cmd in the Run dialog( + R).Now run the following command:
python --version

If Python is already installed, it will generate a message with the Python version available.
Before starting with the installation process, you need to download it. For that all versions of Python for Windows are available on python.org.
Download the required version and follow the further instructions for the installation process.
Beginning the installation.
Getting Started:
Installing Libraries:
Installing pip and other features:
Finishing Installation:
To verify the installation enter the following commands in your Terminal.
python

Let’s consider a simple Hello World Program.
# Python program to print# Hello World  print("Hello World")
how-to-install
python-basics
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
Installation of Node.js on Linux
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Install and Run Apache Kafka on Windows?