code-rag-bench/online-tutorials huggingface dataset:
Batch Script - String Concatenation - GeeksforGeeks

28 Nov, 2021
String Concatenation is combining two or more strings to create a new string. For instance, let a string “Good” and take another string “Morning” now by string concatenation i.e. “Good” + “Morning” and we got new string i.e. “Good Morning”. This is string concatenation.
Let see some examples of string concatenation using batch script.
Example 1 :
In this example, we concatenate two strings.
First, we create a batch file named “concatenation.bat” and open it in notepad.
@echo off
:: We take two string Good and Morning
set str1=Good
set str2=Morning
:: Below command will join two string and store it in str_new variable
set str_new=%str1% %str2%
echo %str_new%
pause
Save the above batch script and run it.
Note:  “pause” is used to hold the screen of the executed file until any key is pressed.
Output : 
Good Morning
Example 2 :
In this example, we concatenate more than two strings.
First, open the notepad and write the following command.
@echo off
:: Here we take three string
set str1=Hello Dear
set str2=Welcome to Geeks For Geeks site
set str3=This is example of string Concatenation
:: Below command will join these strings and store it in str_new variable
set str_new=%str1% %str2% and %str3%
echo %str_new%
pause
Save the above batch script with the .bat extension and run it.
Output : 
Hello Dear Welcome to Geeks For Geeks site and This is example of string Concatenation
Above in both examples, we see how to concatenate string using batch script.
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Delete a Linked List node at a given position in C++

In this tutorial, we are going to learn how to delete a node in singly linked list with the given position.
Let's see the steps to solve the problem.
Write struct with data, and next pointer.
Write struct with data, and next pointer.
Write a function to insert the node into the singly linked list.
Write a function to insert the node into the singly linked list.
Initialize the singly linked list with dummy data.
Initialize the singly linked list with dummy data.
Initialize the position to delete the node.
Initialize the position to delete the node.
Iterate over the linked list and find the node with the given position to delete the node.
Iterate over the linked list and find the node with the given position to delete the node.
Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.
Write a function to delete the node. Consider the following three cases while deleting the node.
If the node is head node, then move the head to next node.
If the node is head node, then move the head to next node.
If the node is middle node, then link the next node to the previous node
If the node is middle node, then link the next node to the previous node
If the node is end node, then remove the previous node link.
If the node is end node, then remove the previous node link.
Let's see the code
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node *next;
};
void insertNode(struct Node** head_ref, int new_data) {
   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
void deleteNode(struct Node **head_ref, int position) {
   if (*head_ref == NULL) {
      return;
   }
   struct Node* temp = *head_ref;
   if (position == 1) {
      *head_ref = temp->next;
      free(temp);
      return;
   }
   for (int i = 2; temp != NULL && i < position - 1; i++) {
      temp = temp->next;
   }
   if (temp == NULL || temp->next == NULL) {
      return;
   }
   struct Node *next = temp->next->next;
   free(temp->next);
   temp->next = next;
}
void printLinkedList(struct Node *node) {
   while (node != NULL) {
      cout << node->data << "->";
      node = node->next;
   }
}
int main() {
   struct Node* head = NULL;
   insertNode(&head, 1);
   insertNode(&head, 2);
   insertNode(&head, 3);
   insertNode(&head, 4);
   insertNode(&head, 5);
   cout << "Linked list before deletion:" << endl;
   printLinkedList(head);
   deleteNode(&head, 1);
   cout << "\nLinked list after deletion:" << endl;
   printLinkedList(head);
   return 0;
}
If you execute the above program, then you will get the following result.
Linked list before deletion:
5->4->3->2->1->
Linked list after deletion:
4->3->2->1->
If you have any queries in the tutorial, mention them in the comment section.
Ceil and floor functions in C++

The ceil function returns the smallest possible integer value which is equal to the value or greater than that. This function is declared in “cmath” header file in C++ language. It takes single value whoes ceil value is to be calculated. The datatype of variable should be double/float/long double only.
Here is the syntax of ceil function in C++ language,
double ceil(double x);
float ceil(float x);
Here is an example of ceil function in C++ language,
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   float var = 1234.25;
   float res;
   res = ceil(var);
   cout << "Ceil value of " << var << " = " << res << endl;
   return 0;
}
Ceil value of 1234.25 = 1235
The floor function returns the largest possible integer value which is equal to the value or smaller than that. This function is also declared in “cmath” header file in C++ language. It takes single value whoes floor value is to be calculated. The datatype of variable should be double/ float/ long double only.
Here is the syntax of floor function in C++ language,
double floor(double x);
float floor(float x);
Here is an example of floor in C++ language,
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   float var = 211.876;
   float res;
   res = floor(var);
   cout << "Floor value of " << var << " = " << res << endl;
   return 0;
}
Floor value of 211.876 = 211
Python Closures?

To better understand python closures, lets first understand what’s nested function and python class. In short, python closure is also a function which encapsulates data with code.
A function defined inside another function is called a nested function. A nested function can access variables of the enclosing scope.
def funcOut():
   print("This is outer function.")
   def funcIn():
      print("This function is defined inside funcOut. \nThis function(funcIn) is called\
nested function.")
   print("We can call nested function here.")
   funcIn()
print("We are in outer function.\nCalling funcOut.")
funcOut()
We are in outer function.
Calling funcOut.
This is outer function.
We can call nested function here.
This function is defined inside funcOut.
This function(funcIn) is called nested function.
So, the funcIn is the nested function which is defined inside funcOut. By seeing above output, we can understand the calling sequence of the functions.
In case we want to have all the functionalities of funcIn from funcOut, for that we may have to do “return funcIn” in the above program, this is called closure in python.
In short, a closure is a function (object) that remembers its creation environment (enclosing scope).
def closureFunc(start):
   def incrementBy(inc):
      return start + inc
   return incrementBy
closure1 = closureFunc(9)
closure2 = closureFunc(90)
print ('clsure1(3) = %s' %(closure1(3)))
print ('closure2(3) = %s' %(closure2(3)))
clsure1(3) = 12
closure2(3) = 93
Calling the variable closure1(which is of function type) with closure1(3) will return 12, while closure2(3) will return 93. While closure1 and closure2 are both referencing the same function incrementBy, we have two different variables closure1 & closure2 which are bind together by identifier closureFunc, leading to different results.
__closure__ attribute and cell objects
To get more information we can use __closure__ attribute and cell objects:
def closureFunc(start):
   def incrementBy(inc):
      return start + inc
   return incrementBy

a= closureFunc(9)
b = closureFunc(90)

print ('type(a)=%s' %(type(a)))
print ('a.__closure__=%s' %(a.__closure__))
print ('type(a.__closure__[0])=%s' %(type(a.__closure__[0])))
print ('a.__closure__[0].cell_contents=%s' %(a.__closure__[0].cell_contents))

print ('type(b)=%s' %(type(b)))
print ('b.__closure__=%s' %(b.__closure__))
print ('type(b.__closure__[0])=%s' %(type(b.__closure__[0])))
print ('b.__closure__[0].cell_contents=%s' %(b.__closure__[0].cell_contents))
type(a) = <class 'function'>
a.__closure__ = <cell at 0x057F8490: int object at 0x68A65770>

type(a.__closure__[0]) = <class 'cell'>
a.__closure__[0].cell_contents = 9

type(b)=<class 'function'>
b.__closure__ = <cell at 0x0580BD50: int object at 0x68A65C80>

type(b.__closure__[0]) = <class 'cell'>
b.__closure__[0].cell_contents=90
From the above output, we can see each cell of the objects retains the value at the time of its creation.
Insert records in MongoDB collection if it does not exist?

You can use update() function to insert records in MongoDB if it does not exist. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.insertIfNotExistsDemo.insertOne({"StudentName":"Mike","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7eec7b559dd2396bcfbfc2")
}
> db.insertIfNotExistsDemo.insertOne({"StudentName":"Sam","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7eec97559dd2396bcfbfc3")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.insertIfNotExistsDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"),
   "StudentName" : "Mike",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c7eec97559dd2396bcfbfc3"),
   "StudentName" : "Sam",
   "StudentAge" : 22
}
Here is the query to insert a record if it does not already exist −
> key = {"StudentName":"David"}
{ "StudentName" : "David" }
> value = {"StudentName":"David","StudentAge":26}
{ "StudentName" : "David", "StudentAge" : 26 }
> db.insertIfNotExistsDemo.update(key, value, upsert=true);
The following is the output −
WriteResult({
   "nMatched" : 0,
   "nUpserted" : 1,
   "nModified" : 0,
   "_id" : ObjectId("5c7eecd4c743760e97af8261")
})
Let us check all documents from a collection. The query is as follows −
> db.insertIfNotExistsDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"),
   "StudentName" : "Mike",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c7eec97559dd2396bcfbfc3"),
   "StudentName" : "Sam",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5c7eecd4c743760e97af8261"),
   "StudentName" : "David",
   "StudentAge" : 26
}
Look at the sample output, the “StudentName”:”David” and “StudentAge”:26 has been inserted successfully.
How to add a string before each numeric value in an R data frame column?

Sometimes the unique identity column of a data frame is not recorded as intended, it contains only numeric values that does not solve the data characteristic purpose. Therefore, we might want to add a string before those numeric values to make the data more sensible for viewers and analysts. This can be easily done with the help of gsub function.
Consider the below data frame −
 Live Demo
set.seed(111)
x1<-1:20 x2<sample(1:10,20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
x1 x2
1 1 6
2 2 8
3 3 4
4 4 6
5 5 4
6 6 5
7 7 1
8 8 6
9 9 5
10 10 1
11 11 6
12 12 6
13 13 1
14 14 1
15 15 2
16 16 5
17 17 2
18 18 10
19 19 4
20 20 7
Adding ID before each value in column x1 of data frame df1 −
df1$x1<-sub("^","ID",df1$x1)
df1
x1 x2
1 ID1 4
2 ID2 3
3 ID3 9
4 ID4 5
5 ID5 3
6 ID6 8
7 ID7 10
8 ID8 1
9 ID9 10
10 ID10 4
11 ID11 8
12 ID12 10
13 ID13 9
14 ID14 8
15 ID15 1
16 ID16 7
17 ID17 5
18 ID18 1
19 ID19 9
20 ID20 8
Let’s have a look at another example −
 Live Demo
Class<-1:20
Score<-sample(36:100,20)
df2<-data.frame(Class,Score)
df2
Class Score
1 1 89
2 2 82
3 3 55
4 4 63
5 5 57
6 6 99
7 7 90
8 8 43
9 9 86
10 10 42
11 11 44
12 12 56
13 13 80
14 14 45
15 15 46
16 16 37
17 17 41
18 18 60
19 19 59
20 20 68
Adding Class before each value in column Class of data frame df2 −
df2$Class<-sub("^","Class ",df2$Class)
df2
Class Score
1 Class 1 60
2 Class 2 70
3 Class 3 42
4 Class 4 87
5 Class 5 71
6 Class 6 63
7 Class 7 73
8 Class 8 100
9 Class 9 97
10 Class 10 39
11 Class 11 66
12 Class 12 41
13 Class 13 65
14 Class 14 40
15 Class 15 72
16 Class 16 89
17 Class 17 96
18 Class 18 76
19 Class 19 95
20 Class 20 77
Group a JavaScript Array

Suppose, we have a JavaScript array like this −
const data = [
   {
      "dataId": "1",
      "tableName": "table1",
      "column": "firstHeader",
      "rows": [
         "a","b","c"
      ]
   },
   {
      "dataId": "2",
      "tableName": "table1",
      "column": "secondHeader",
      "rows": [
         "d","e","f",
      ]
   }, {
      "dataId": "3",
      "tableName": "table2",
      "column": "aNewFirstHeader",
      "rows": [
         1,2,3
      ]
   }
];
We are required to write a JavaScript function that in one such array. The function should construct a new grouped array of objects, based on the original array.
The grouped array should contain the data for separate, unique "tableName" objects into their own objects.
Therefore ultimately, the output should look like −
const output = [
   {
      "tableName": "table1",
      "column": ["firstHeader", "secondHeader"],
      "rows": [["a","b","c"], ["d","e","f"]]
   },
   {
      "tableName": "table2",
      "column": ["aNewFirstHeader"],
      "rows": [[1,2,3]]
   }
];
const arr = [
   {
      "dataId": "1",
      "tableName": "table1",
      "column": "firstHeader",
      "rows": [ "val","b","c" ]
   },
   {
      "dataId": "2",
      "tableName": "table1",
      "column": "secondHeader",
      "rows": [
         "d","e","f",
      ]
   },
   {
      "dataId": "3",
      "tableName": "table2",
      "column": "aNewFirstHeader",
      "rows": [
         1,2,3
      ]
   }
];
const groupArray = (arr = []) => {
   const res = arr.reduce((obj => (acc, val) => {
      let item = obj.get(val.tableName);
      if (!item) {
         item = {
            tableName: val.tableName, column: [], rows: []
         }
         obj.set(val.tableName, item); acc.push(item);
      };
      item.column.push(val.column); item.rows.push(val.rows);
      return acc;
   })(new Map), []);
   return res;
};
console.log(JSON.stringify(groupArray(arr), undefined, 4));
And the output in the console will be −
[
   {
      "tableName": "table1",
      "column":
      [
         "firstHeader",
         "secondHeader"
      ],
      "rows": [
         [
            "val", "b", "c"
         ],
         [
            "d", "e", "f"
         ]
      ]
   }, {
      "tableName": "table2",
      "column": [
            "aNewFirstHeader"
         ],
         "rows": [
         [
            1, 2, 3
         ]
      ]
   }
]
Python unittest - assertIsNone() function - GeeksforGeeks

29 Aug, 2020
assertIsNone() in Python is a unittest library function that is used in unit testing to check that input value is None or not. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is equal to None assertIsNone() will return true else return false.
Syntax: assertIsNone(testValue, message)
Parameters: assertIsNone() accept two parameters which are listed below with explanation:
testValue:  test variable as the input value to check equality with None
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest  class TestMethods(unittest.TestCase):    # test function     def test_negative(self):        firstValue = "geeks"        # error message in case if test case got failed        message = "Test value is not none."        # assertIsNone() to check that if input value is none        self.assertIsNone(firstValue, message)  if __name__ == '__main__':    unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "p1.py", line 14, in test_negative
    self.assertIsNone(firstValue, message)
AssertionError: 'geeks' is not None : Test value is not none.

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)



Example 2: Positive Test case
Python3
# unit test caseimport unittest    class TestMethods(unittest.TestCase):    # test function     def test_positive(self):        firstValue = None        # error message in case if test case got failed        message = "Test value is not none."        # assertIsNone() to check that if input value is none        self.assertIsNone(firstValue, message)  if __name__ == '__main__':    unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK



Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
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 ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
How to call PHP function from string stored in a Variable - GeeksforGeeks

02 Nov, 2018
Given the names of some user-defined functions stored as strings in variables. The task is to call the functions using the names stored in the variables.
Example:
<?php  // Function without argument function func() {    echo "geek";}  // Function with argumentfunction fun($msg) {    echo $msg;}  // Call func and fun using $var and $var1$var = "func";$var1 = "fun";     ?>
There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used.
Program:
<?php  // Function without argument function func() {    echo "hello ";}  // Function with argumentfunction fun($msg) {    echo $msg." ";}      $var = "func";$var1 = "fun";       // 1st method by using variable name$var();$var1("geek");  echo "\n";  // 2nd method by using php inbuilt// function call_user_func()call_user_func($var);call_user_func($var1, "fun_function");   ?>
hello geek 
hello fun_function

Another Method: Using eval() Function: The eval() function is an inbuilt function in PHP which is used to evaluate string as PHP code.Note: This method is contributed by Vineet Joshi.Syntax:
eval( $code )
Parameters: This function accepts single parameter code which is used to hold the PHP code as a string.
Example:
<?php  // Function without argument function writeMessage() {    echo "Welcome to GeeksforGeeks!";}  // Declare variable and store// function name    $functionName = "writeMessage();";  // Function call using evaleval($functionName);?>
Welcome to GeeksforGeeks!

Technical Scripter 2018
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to convert array to string in PHP ?
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
Google Online Challenge 2020 - GeeksforGeeks

21 Aug, 2020
The Google online challenge 2020 for summer internships 2021 was held on August 16. It was a 60-minute online test having 2 questions to code.
First Question: Size of the smallest subset with maximum Bitwise OR
Second Question: Given a list which initially contains 0, the following queries can be performed:
0 X: add X to the list
1 X: replace each element “A” of the list by A^X, where ^ is the xor operator.
Return a list with the result elements in increasing order.
Example:
5 (no of queries)
0 4
0 2
1 4
0 5
1 8
Answer:
8 12 13 14
Google
Bit Magic
Dynamic Programming
Internship
Interview Experiences
Google
Dynamic Programming
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Program to find whether a given number is power of 2
Add two numbers without using arithmetic operators
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Python - Add list elements to tuples list - GeeksforGeeks

27 Aug, 2021
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be done. 
Input : test_list = [(5, 6), (2, 4), (5, 7), (2, 5)], sub_list = [5, 4] Output : [(5, 6, 5, 4), (2, 4, 5, 4), (5, 7, 5, 4), (2, 5, 5, 4)]Input : test_list = [(5, 6), (2, 4), (5, 7), (2, 5)], sub_list = [5] Output : [(5, 6, 5), (2, 4, 5), (5, 7, 5), (2, 5, 5)]  
Method #1 : Using list comprehension + “+” operator The combination of above functionalities can be used to solve this problem. In this, we perform task of adding tuple to list using “+” operator and iteration over all tuples is done using list comprehension. 
Python3
# Python3 code to demonstrate working of# Add list elements to tuples list# Using list comprehension + "+" operator # initializing listtest_list = [(5, 6), (2, 4), (5, 7), (2, 5)] # printing original listprint("The original list is : " + str(test_list)) # initializing listsub_list = [7, 2, 4, 6] # Add list elements to tuples list# Using list comprehension + "+" operatorres = [sub + tuple(sub_list) for sub in test_list] # printing resultprint("The modified list : " + str(res))
The original list is : [(5, 6), (2, 4), (5, 7), (2, 5)]
The modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]
 
 Method #2 : Using list comprehension + “*” operator The combination of above functions can be used to solve this problem. In this, we perform the task of adding list to a tuple using pack-unpack operator “*”. This is more efficient method than above method. 
Python3
# Python3 code to demonstrate working of# Add list elements to tuples list# Using list comprehension + "*" operator # initializing listtest_list = [(5, 6), (2, 4), (5, 7), (2, 5)] # printing original listprint("The original list is : " + str(test_list)) # initializing listsub_list = [7, 2, 4, 6] # Add list elements to tuples list# Using list comprehension + "*" operatorres = [(*sub, *sub_list) for sub in test_list] # printing resultprint("The modified list : " + str(res))
The original list is : [(5, 6), (2, 4), (5, 7), (2, 5)]
The modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]
 
surinderdawra388
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get 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?
Performing Bitwise Operations with BigInteger in Java

BigInteger class is used for big integer calculations which are outside the limit of the primitive data types. It provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
Let us work with the testBit() method in Java to perform Bitwise operation. The java.math.BigInteger.testBit(int n) returns true if and only if the designated bit is set −
The following is an example −
 Live Demo
import java.math.*;
public class BigIntegerDemo {
   public static void main(String[] args) {
      BigInteger one;
      Boolean two;
      one = new BigInteger("5");
      two = one.testBit(2);
      System.out.println("Result: " +two);
   }
}
Result: true
Groovy - Optionals

Groovy is an “optionally” typed language, and that distinction is an important one when understanding the fundamentals of the language. When compared to Java, which is a  “strongly” typed language, whereby the compiler knows all of the types for every variable and can understand and honor contracts at compile time. This means that method calls are able to be determined at compile time.
When writing code in Groovy, developers are given the flexibility to provide a type or not. This can offer some simplicity in implementation and, when leveraged properly, can service your application in a robust and dynamic way.
In Groovy, optional typing is done via the ‘def’ keyword. Following is an example of the usage of the def method −
class Example { 
   static void main(String[] args) { 
      // Example of an Integer using def 
      def a = 100; 
      println(a); 
		
      // Example of an float using def 
      def b = 100.10; 
      println(b); 
		
      // Example of an Double using def 
      def c = 100.101; 
      println(c);
		
      // Example of an String using def 
      def d = "HelloWorld"; 
      println(d); 
   } 
} 
From the above program, we can see that we have not declared the individual variables as Integer, float, double, or string even though they contain these types of values.
When we run the above program, we will get the following result −
100 
100.10 
100.101
HelloWorld

Optional typing can be a powerful utility during development, but can lead to problems in maintainability during the later stages of development when the code becomes too vast and complex.
To get a handle on how you can utilize optional typing in Groovy without getting your codebase into an unmaintainable mess, it is best to embrace the philosophy of “duck typing” in your applications.
If we re-write the above code using duck typing, it would look like the one given below. The variable names are given names which resemble more often than not the type they represent which makes the code more understandable.
class Example { 
   static void main(String[] args) { 
      // Example of an Integer using def 
      def aint = 100; 
      println(aint); 
		
      // Example of an float using def 
      def bfloat = 100.10; 
      println(bfloat); 
		
      // Example of an Double using def 
      def cDouble = 100.101; 
      println(cDouble);
		
      // Example of an String using def 
      def dString = "HelloWorld"; 
      println(dString); 
   } 
}

    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Change the x or y interval of a Matplotlib figure - GeeksforGeeks

03 Jan, 2021
It is quite easy to change the x or y range using matplotlib.pyplot.xlim() and matplotlib.pyplot.ylim() from the Matplotlib is a library in Python. This function in pyplot module of matplotlib library is used to get or set the x-limits/ y-limits of the current axes and returns the tuple of the new x-axis/y-axis limits.
Syntax: matplotlib.pyplot.xlim(*args, **kwargs)
Parameters: 
*args:
 left: This parameter is used to set the xlim/ylim to left.
right: This parameter is used to set the xlim/ylim to right.
 **kwargs: This is Text properties that is used to control the appearance of the labels.
Example 1: Without using matplotlib.pyplot.xlim()/matplotlib.pyplot.ylim() function.
Python3
import numpy as npimport matplotlib.pyplot as plt  x = [0, 5, 9, 10, 15, 20, 25]y = [0, 1, 2, 3, 4, 5, 6]  plt.plot(x, y)plt.show()
Output:
Example 2: With the matplotlib.pyplot.xlim()/matplotlib.pyplot.ylim() function.
Python3
import numpy as npimport matplotlib.pyplot as plt  x = [0,5,9,10,15,20,25]y = [0,1,2,3,4,5,6]plt.xlim([-40, 40])plt.ylim([-40, 40])  plt.plot(x,y)plt.show()
Output:-
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to click a href link using Selenium?

We can click a href link with Selenium webdriver. There are multiple ways to achieve this. First of all we need to identify the link with the help of the locators like link text and partial link text.
The link text locator identifies the element whose text matches with text enclosed within the anchor tag. The partial link text locator identifies the element whose text matches partially with the text enclosed within the anchor tag. Once the linkwith href is identified we need to apply the click() method to it.
Let's try to click the link Privacy Policy on the page.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ClickLinkText{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element with link text then apply click()
      WebElement p=driver.findElement(By.linkText("Privacy Policy"));
      p.click();
      System.out.println("Page title after link click : " + driver.getTitle());
      driver.close();
   }
}
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ClickPartialLinkText{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element with link text then apply click()
      WebElement p=driver.findElement(By.partialLinkText("Privacy"));
      p.click();
      System.out.println("Page title after link click : " +   driver.getTitle());
      driver.close();
   }
}
Python Pandas – How to select DataFrame rows on the basis of conditions

We can set conditions and fetch DataFrame rows. These conditions can be set using logical operators and even relational operators.
At first, import the required pandas libraries −
import pandas as pd
Let us create a DataFrame and read our CSV file −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

Fetching dataframe rows with registration price less than 1000. We are using relational operator for this −
dataFrame[dataFrame.Reg_Price < 1000]
Following is the code −
import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("DataFrame...\n",dataFrame)

# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)

# fetching dataframe rows with registration price less than 1000
resData = dataFrame[dataFrame.Reg_Price < 1000]

print("DataFrame...\n",resData)
This will produce the following output −
DataFrame...
           Car   Date_of_Purchase   Reg_Price
0          BMW         10/10/2020        1000
1        Lexus         10/12/2020         750
2         Audi         10/17/2020         750
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Number of rows and column in our DataFrame = (6, 3)
DataFrame...
     Car   Date_of_Purchase   Reg_Price
1  Lexus         10/12/2020         750
2   Audi         10/17/2020         750
org.json - Property

Property class provides static methods to convert properties text into a JSONObject, and vice versa.
Following methods are covered in the example.
toJSONObject(Properties) − Converts a properties data to JSONObject Object.
toJSONObject(Properties) − Converts a properties data to JSONObject Object.
toProperties(JSONObject) − Converts a JSONObject to properties object.
toProperties(JSONObject) − Converts a JSONObject to properties object.
import java.util.Properties;
import org.json.JSONObject;
import org.json.Property;

public class JSONDemo {
   public static void main(String[] args) {
      Properties properties = new Properties();
      properties.put("title", "This is a title text");
      properties.put("subtitle", "This is a subtitle text");

      System.out.println("Properties to JSON");
      JSONObject jsonObject = Property.toJSONObject(properties);
      System.out.println(jsonObject);

      System.out.println("JSON to properties");
      System.out.println(Property.toProperties(jsonObject));
   }
}
Properties to JSON
{"subtitle":"This is a subtitle text","title":"This is a title text"}
JSON to properties
{subtitle = This is a subtitle text, title = This is a title text}


    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    107 Lectures 
     13.5 hours 

 Arnab Chakraborty

    75 Lectures 
     5 hours 

 Revathi Ramachandran

    14 Lectures 
     44 mins

 Zach Miller

    12 Lectures 
     54 mins

 Prof. Paul Cline, Ed.D

    54 Lectures 
     4 hours 

 Gilad James, PhD
 Print
 Add Notes
 Bookmark this page
How to create vertical button column with GridLayout in Java?

To create a vertical button column, let us first create some buttons and set the layout as well −
JPanel btnPanel = new JPanel(new GridLayout(10, 1, 10, 5));
btnPanel.add(new JButton("First Button"));
btnPanel.add(new JButton("Second Button"));
btnPanel.add(new JButton("Third Button"));
btnPanel.add(new JButton("Fourth Button"));
btnPanel.add(new JButton("Fifth Button"));
btnPanel.add(new JButton("Sixth Button"));
btnPanel.add(new JButton("Seventh Button"));
btnPanel.add(new JButton("Eighth Button"));
Above, we have set the GridLayout to create rows and columns with vertical and horizontal gap.
The following is an example to create vertical button column with GridLayout −
package my;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      panel.setBorder(new EmptyBorder(2, 3, 2, 3));
      JPanel layout = new JPanel(new GridBagLayout());
      layout.setBorder(new EmptyBorder(5, 5, 5, 5));
      JPanel btnPanel = new JPanel(new GridLayout(10, 1, 10, 5));
      btnPanel.add(new JButton("First Button"));
      btnPanel.add(new JButton("Second Button"));
      btnPanel.add(new JButton("Third Button"));
      btnPanel.add(new JButton("Fourth Button"));
      btnPanel.add(new JButton("Fifth Button"));
      btnPanel.add(new JButton("Sixth Button"));
      btnPanel.add(new JButton("Seventh Button"));
      btnPanel.add(new JButton("Eighth Button"));
      layout.add(btnPanel);
      panel.add(layout, BorderLayout.CENTER);
      JFrame frame = new JFrame("Demo");
      frame.add(panel);
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.setLocationByPlatform(true);
      frame.setSize(500, 400);
      frame.setVisible(true);
   }
}
Can a constructor be synchronized in Java?

No, a constructor cannot be synchronized in Java. The JVM ensures that only one thread can invoke a constructor call at a given point in time. That is why no need to declare a constructor as synchronized and it is illegal in Java. However, we can use synchronized blocks inside a constructor.
If we are trying to put a synchronized keyword before a constructor, the compiler says that "error: modifier synchronized not allowed here".
public class SynchronizedConstructorTest {
      // declaration of synchronized constructor
      public synchronized SynchronizedConstructorTest() {
         System.out.println("Synchronized Constructor");
      }
      public static void main(String args[]) {
         SynchronizedConstructorTest test = new SynchronizedConstructorTest();
      }
}
SynchronizedConstructorTest.java:3: error: modifier synchronized not allowed here
public synchronized SynchronizedConstructorTest() {
^
1 error
PyQt5 – How to change text of pre-existing label | setText method - GeeksforGeeks

26 Mar, 2020
In GUI applications there is need of displaying information this done using labels in PyQt5, but sometimes there is also a need of changing the text of the label, in this tutorial we will see how it can be done.
setText() method is used to change the content of the label.
Syntax : label.setText(Info)
Argument : It takes string as an argument.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # informations        info = "info"        new_info = "new info "          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.label_1 = QLabel(info, self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # creating a label widget        self.label_2 = QLabel(info, self)          # moving position        self.label_2.move(100, 150)          # setting up border        self.label_2.setStyleSheet("border: 1px solid black;")          # changing the text of label        self.label_2.setText(new_info)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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
String Methods in Dart Programming

String class in Dart contains different methods that we use to make working with strings easier and more expressive.
There are many methods present in the String class, some of the common ones are −
contains(Pattern<>)
contains(Pattern<>)
trim()
trim()
toLowerCase()
toLowerCase()
toUpperCase()
toUpperCase()
split(Pattern)
split(Pattern)
compareTo(another string)
compareTo(another string)
We will explore each of the above string methods in this article.
The contains() method is used to find a pattern present in the string or not. If the pattern that we are searching is present in the string, then the contains() method returns true, else it returns false.
Consider the example shown below −
 Live Demo
void main(){
   String name = " Tutorials Point ";
   print(name.contains("Point"));
   print(name.contains("Sample"));
}
In the above example, we are using the contains() method on the variable name, and inside the two calls to the contains() method, we passed two string patterns, one is present in the string, and the other isn't.
true
false
The trim() method is used to remove any trailing spaces present in the string. It removes the trailing spaces from both the starting position and the ending position.
Consider the example shown below −
 Live Demo
void main(){
   String name = " Tutorials Point ";
   print(name.trim());
}
Tutorials Point
The toLowerCase() method on string is used to convert the given string characters or letters to all in lower cases.
Consider the example shown below −
 Live Demo
void main(){
   String name = "Tutorials Point";
   print(name.toLowerCase());
}
tutorials point
The toUpperCase() method on string is used to convert the given string characters or letters to all in upper cases.
Consider the example shown below −
 Live Demo
void main(){
   String name = "Tutorials Point";
   print(name.toUpperCase());
}
TUTORIALS POINT
The split method of string class, takes a pattern as an argument and it splits that string based on the provided pattern.
Consider the example shown below −
 Live Demo
void main(){
   String name = "Tutorials Point";
   print(name.split(" "));
}
In the above example, we are splitting the string on the basis of an empty string.
[Tutorials, Point]
The compareTo() method is used to compare two strings, and it returns an integer value. It returns 1, if the string comes after the other string in lexicographically sequence, -1 is before and 0 if they are the same.
Consider the example shown below −
 Live Demo
void main(){
   String name = "Tutorials Point";
   print(name.compareTo("Random Point"));
   print(name.compareTo("Tutorials Point"));
}
1
0
C# Program to Check Given Strings are Equal or Not Using equal to (==) Operator - GeeksforGeeks

11 Nov, 2021
Given two strings we need to check if they are equal by using the == operator. The == Operator compares the reference identity i.e. whether they are referring to the same identity in the heap. If they are equal then it will return true, otherwise, return false.
Example:
Input
String 1 : geeks
String 2 : geeks
Output   : Equal

Input
String 1 : geeks
String 2 : geeqs
Output   : Not Equal
Method:
For the given two strings compare them by using == operator
If it returns true then the strings are equal.
If it returns false then the strings are not equal.
Example 1:
C#
// C# program to check given strings are// equal or not. Using == operatorusing System; class GFG{     public static void Main(){    string str1 = "geeks";    string str2 = "geeks";         // Here we use == operator to check    // the equality of the strings    Console.WriteLine(str1 == str2);}}
  
True
 
Example 2:
 
C#
// C# program to check given strings// are equal or not. Using == operatorusing System; class GFG{     public static void Main(){    string str1 = "geeks";    string str2 = "geeqs";         // Here we use == operator to check    // the equality of the strings    Console.WriteLine(str1 == str2);}}
False
But the == operator might not work as expected when we are comparing strings whose reference identities are not the same. Let us understand with the help of the below example:
C#
// C# program to check given strings// are equal or not. Using == operatorusing System;  class GFG{     static void Main(string[] args) {    object str1 = "geeks";      object str2 = new string("geeks");               Console.WriteLine(str1 == str2); }      } 
False
surinderdawra388
CSharp-programs
CSharp-Strings-Programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Fortran - Environment Setup

G95 is the GNU Fortran multi-architechtural compiler, used for setting up Fortran in Windows. The windows version emulates a unix environment using MingW under windows. The installer takes care of this and automatically adds g95 to the windows PATH variable.
You can get the stable version of G95 from here
During installation, g95 is automatically added to your PATH variable if you select the option “RECOMMENDED”. This means that you can simply open a new Command Prompt window and type “g95” to bring up the compiler. Find some basic commands below to get you started.
g95 –c hello.f90
Compiles hello.f90 to an object file named hello.o
g95 hello.f90
Compiles hello.f90 and links it to produce an executable a.out
g95 -c h1.f90 h2.f90 h3.f90
Compiles multiple source files. If all goes well, object files h1.o, h2.o and h3.o are created
g95 -o hello h1.f90 h2.f90 h3.f90
Compiles multiple source files and links them together to an executable file named 'hello'
-c Compile only, do not run the linker.
-o Specify the name of the output file, either an object file or the executable.

Multiple source and object files can be specified at once. Fortran files are indicated by names ending in ".f", ".F", ".for", ".FOR", ".f90", ".F90", ".f95", ".F95", ".f03" and ".F03". Multiple source files can be specified. Object files can be specified as well and will be linked to form an executable file.
 Print
 Add Notes
 Bookmark this page
Assembly - LODS Instruction

In cryptography, a Caesar cipher is one of the simplest known encryption techniques. In this method, each letter in the data to be encrypted is replaced by a letter some fixed number of positions down the alphabet.
In this example, let us encrypt a data by simply replacing each alphabet in it with a shift of two alphabets, so a will be substituted by c, b with d and so on.
We use LODS to load the original string 'password' into the memory.
section .text
   global _start         ;must be declared for using gcc
	
_start:                  ;tell linker entry point
   mov    ecx, len
   mov    esi, s1
   mov    edi, s2
	
loop_here:
   lodsb
   add al, 02
   stosb
   loop    loop_here          
   cld
   rep     movsb
	
   mov     edx,20        ;message length
   mov     ecx,s2        ;message to write
   mov     ebx,1         ;file descriptor (stdout)
   mov     eax,4         ;system call number (sys_write)
   int     0x80          ;call kernel
	
   mov     eax,1         ;system call number (sys_exit)
   int     0x80          ;call kernel
	
section .data
s1 db 'password', 0 ;source
len equ $-s1

section .bss
s2 resb 10               ;destination
When the above code is compiled and executed, it produces the following result:
rcuuyqtf


    46 Lectures 
     2 hours 

 Frahaan Hussain

    23 Lectures 
     12 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page