code-rag-bench/online-tutorials huggingface dataset:
How to remove an item from a C# list by using an index?

To remove an item from a list in C# using index, use the RemoveAt() method.
Firstly, set the list −
List<string> list1 = new List<string>() {
   "Hanks",
   "Lawrence",
   "Beckham",
   "Cooper",
};
Now remove the element at 2nd position i.e. index 1
list1.RemoveAt(1);
Let us see the complete example −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> list1 = new List<string>() {
         "Hanks",
         "Lawrence",
         "Beckham",
         "Cooper",
      };

      Console.Write("Initial list...");
      foreach (string list in list1) {
         Console.WriteLine(list);
      }

      Console.Write("Removing element from the list...");
      list1.RemoveAt(1);
   
      foreach (string list in list1) {
         Console.WriteLine(list);
      }
   }
}
Initial list...
Hanks
Lawrence
Beckham
Cooper
Removing element from the list...
Hanks
Beckham
Cooper
Create a selectable list in HTML

Use the <select> tag to create a selectable list. The HTML <select> tag is used within a form for defining a select list.
The HTML <select> tag also supports the following additional attributes −
You can try to run the following code to create a selectable list in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML select Tag</title>
   </head>
   <body>
      <form action = "/cgi-bin/dropdown.cgi" method = "post">
         <select name = "dropdown">
            <option value = "Data Structures" selected>Data Structures</option>
            <option value = "Data Mining">Data Mining</option>
         </select>
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>
OpenCV Python Program to blur an image?

OpenCV is one of the best python package for image processing. Also like signals carry noise attached to it, images too contain different types of noise mainly from the source itself (Camera sensor). Python OpenCV package provides ways for image smoothing also called blurring. This is what we are going to do in this section. One of the common technique is using Gaussian filter (Gf) for image blurring. With this, any sharp edges in images are smoothed while minimizing too much blurring.
cv.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType=BORDER_DEFAULT]]] )
Where−
src – input image
src – input image
dst – output image
dst – output image
ksize – Gaussian kernel size[ height width]. If ksize is set to [0 0], then ksize is computed from sigma values.
ksize – Gaussian kernel size[ height width]. If ksize is set to [0 0], then ksize is computed from sigma values.
sigmaX – Kernel standard deviation along X-axis(horizontal direction).
sigmaX – Kernel standard deviation along X-axis(horizontal direction).
sigmaY – kernel standard deviation along Y-axis(Vertical direction).
sigmaY – kernel standard deviation along Y-axis(Vertical direction).
Bordertype – Specifies iage boundaries while kernel is applied on image borders. Few possible values are: cv.BORDER_CONSTANT, cv.BORDER_REPLICATE, cv.BORDER_REFLECT, cv.BORDER_WRAP, cv.BORDER_DEFAULT, cv.BORDER_ISOLATED, cv.BORDER_TRANSPARENT etc.
Bordertype – Specifies iage boundaries while kernel is applied on image borders. Few possible values are: cv.BORDER_CONSTANT, cv.BORDER_REPLICATE, cv.BORDER_REFLECT, cv.BORDER_WRAP, cv.BORDER_DEFAULT, cv.BORDER_ISOLATED, cv.BORDER_TRANSPARENT etc.
Below is the program to Gaussian blur an image using OpenCV package.
import cv2
import numpy

# read image
src = cv2.imread('LionKing.jpeg', cv2.IMREAD_UNCHANGED)

# apply guassian blur on src image
dst = cv2.GaussianBlur(src,(3,3),cv2.BORDER_DEFAULT)

# display input and output image
cv2.imshow("Gaussian Blur",numpy.hstack((src, dst)))
cv2.waitKey(0) # waits until a key is pressed
cv2.destroyAllWindows() # destroys the window showing image
The two images looks almost similar (original/blur). Now let us increase the kernel size and observe the result.
dst = cv2.GaussianBlur(src,(13,13),cv2.BORDER_DEFAULT)
Now there is a clear distinction between the two images.
Python - Test if Values Sum is Greater than Keys Sum in dictionary - GeeksforGeeks

12 Nov, 2020
Given a Dictionary, check if the summation of values is greater than Keys sum.
Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.
Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. 
Method #1: Using loop
In this, we compute keys and values sum in separate counter, and after the loop equate the values, if values are greater than Keys summation, True is returned.
Python3
# Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using loop  # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  key_sum = 0val_sum = 0  for key in test_dict:      # getting sum    key_sum += key    val_sum += test_dict[key]  # checking if val_sum greater than key sumres = val_sum > key_sum  # printing resultprint("The required result : " + str(res))
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result : False

Method #2 : Using sum() + values()  + keys()
In this way, keys sum and values sum is extracted using keys(), values() and summation using sum(), the required condition is checked and verdict is computed.
Python3
# Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using sum() + values()  + keys()  # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  res = sum(list(test_dict.keys())) < sum(list(test_dict.values()))  # printing resultprint("The required result : " + str(res))
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result : False

Python dictionary-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?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
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?
Which PHP function is used to establish MySQL database connection using PHP script?

PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure. Its syntax is as follows −
connection mysql_connect(server,user,passwd,new_link,client_flag);
Following table give us the parameters used in the syntax above −
MYSQL_CLIENT_SSL − Use SSL encryption.MYSQL_CLIENT_COMPRESS − Use compression protocol.MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection.
MYSQL_CLIENT_SSL − Use SSL encryption.
MYSQL_CLIENT_COMPRESS − Use compression protocol.
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection.
Java Examples - Array to Collection

How to convert an array into a collection ?
Following example demonstrates to convert an array into a collection Arrays.asList(name) method of Java Util class.
import java.util.*;
import java.io.*;

public class ArrayToCollection{
   public static void main(String args[]) throws IOException {
      BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
      System.out.println("How many elements you want to add to the array: ");
      int n = Integer.parseInt(in.readLine());
      String[] name = new String[n];
      
      for(int i = 0; i < n; i++) {
         name[i] = in.readLine();
      }
      List<String> list = Arrays.asList(name); 
      System.out.println();
      
      for(String li: list) {
         String str = li;
         System.out.print(str + " ");
      }
   }
}
The above code sample will produce the following result.
How many elements you want to add to the array:
red white green

red white green

 Print
 Add Notes
 Bookmark this page
Getting an enumerator that iterates through LinkedList in C#

To get an enumerator that iterates through LinkedList, the code is as follows −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      LinkedList<string> list = new LinkedList<string>();
      list.AddLast("A");
      list.AddLast("B");
      list.AddLast("C");
      list.AddLast("D");
      list.AddLast("E");
      list.AddLast("F");
      list.AddLast("G");
      list.AddLast("H");
      list.AddLast("I");
      list.AddLast("J");
      Console.WriteLine("Count of nodes = " + list.Count);
      Console.WriteLine("Elements in LinkedList... (Enumerator iterating through LinkedList)");
      LinkedList<string>.Enumerator demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}
This will produce the following output −
Count of nodes = 10
Elements in LinkedList... (Enumerator iterating through LinkedList)
A
B
C
D
E
F
G
H
I
J
Let us see another example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      LinkedList<string> list1 = new LinkedList<string>();
      list1.AddLast("One");
      list1.AddLast("Two");
      list1.AddLast("Three");
      list1.AddLast("Four");
      list1.AddLast("Five");
      Console.WriteLine("Elements in LinkedList1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      LinkedList<string> list2 = new LinkedList<string>();
      list2.AddLast("India");
      list2.AddLast("US");
      list2.AddLast("UK");
      list2.AddLast("Canada");
      list2.AddLast("Poland");
      list2.AddLast("Netherlands");
      Console.WriteLine("Elements in LinkedList2... (Enumerator iterating through LinkedList2)");
      LinkedList<string>.Enumerator demoEnum = list2.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
      LinkedList<string> list3 = new LinkedList<string>();
      list3 = list2;
      Console.WriteLine("Is LinkedList3 equal to LinkedList2? = "+list3.Equals(list2));
   }
}
This will produce the following output −
Elements in LinkedList1...
One
Two
Three
Four
Five
Elements in LinkedList2... (Enumerator iterating through LinkedList2)
India
US
UK
Canada
Poland
Netherlands
Is LinkedList3 equal to LinkedList2? = True
How to round the decimal number to the nearest tenth in JavaScript?

To round the decimal number to the nearest tenth, use toFixed(1) in JavaScript. The syntax is
as follows −
var anyVaribleName=yourVariableName.toFixed(1)
Let’s say the following is our decimal number −
var decimalValue =200.432144444555;
console.log("Actual value="+decimalValue)
Let’s now round the decimal number. Following is the code −
var decimalValue =200.432144444555;
console.log("Actual value="+decimalValue)
var modifiedValue=decimalValue.toFixed(1)
console.log("Modified value="+ modifiedValue);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo38.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo38.js
Actual value=200.432144444555
Modified value=200.4
Calculate the mean across dimension in a 2D NumPy array - GeeksforGeeks

29 Aug, 2020
We can find out the mean of each row and column of 2d array using numpy with the function np.mean(). Here we have to provide the axis for finding mean.
Syntax: numpy.mean(arr, axis = None)
For Row mean: axis=1
For Column mean: axis=0
Example:
Python3
# Importing Libraryimport numpy as np  # creating 2d arrayarr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])  # Calculating mean across Rowsrow_mean = np.mean(arr, axis=1)  row1_mean = row_mean[0]print("Mean of Row 1 is", row1_mean)  row2_mean = row_mean[1]print("Mean of Row 2 is", row2_mean)  row3_mean = row_mean[2]print("Mean of Row 3 is", row3_mean)    # Calculating mean across Columnscolumn_mean = np.mean(arr, axis=0)  column1_mean = column_mean[0]print("Mean of column 1 is", column1_mean)  column2_mean = column_mean[1]print("Mean of column 2 is", column2_mean)  column3_mean = column_mean[2]print("Mean of column 3 is", column3_mean)
Output:
Mean of Row 1 is 2.0
Mean of Row 2 is 5.0
Mean of Row 3 is 8.0
Mean of column 1 is 4.0
Mean of column 2 is 5.0
Mean of column 3 is 6.0

Python numpy-program
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Smallest String With Swaps in C++

Suppose we have given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. We can swap the characters at any pair of indices in the given pairs any number of times as we want. We have to find the lexicographically smallest string that s can be changed to after using the swaps. So if the input is like s = “dcab” and pairs = [[0,3], [1,2]], then the output will be “bacd”. Exchange s[0] and s[3], s = "bcad", then exchange s[1] and s[2], s = "bacd".
To solve this, we will follow these steps −
n := size of array, parent := make an array of size n, and fill this with -1
n := size of array, parent := make an array of size n, and fill this with -1
make a string called ret of size n and fill this with *
make a string called ret of size n and fill this with *
for i in range 0 to size of pairsu := pairs[i, 0] and v := pairs[i, 1]if parent of u is same as parent of v, then skip to next iterationparent[parent of u] := parent of v
for i in range 0 to size of pairs
u := pairs[i, 0] and v := pairs[i, 1]
u := pairs[i, 0] and v := pairs[i, 1]
if parent of u is same as parent of v, then skip to next iteration
if parent of u is same as parent of v, then skip to next iteration
parent[parent of u] := parent of v
parent[parent of u] := parent of v
define an array arr1 of size n
define an array arr1 of size n
for i in range 0 to n – 1: insert s[i] into arr[parent of i]
for i in range 0 to n – 1: insert s[i] into arr[parent of i]
for i in range 0 to n – 1: sort arr[i] by reading the value from right
for i in range 0 to n – 1: sort arr[i] by reading the value from right
for i in range 0 to n – 1 −ret[i] := last entry of arr1[parent of i]delete the last node from arr1[parent of i]
for i in range 0 to n – 1 −
ret[i] := last entry of arr1[parent of i]
ret[i] := last entry of arr1[parent of i]
delete the last node from arr1[parent of i]
delete the last node from arr1[parent of i]
Let us see the following implementation to get a better understanding −
class Solution {
public:
   vector <int> parent;
   int getParent(int x){
      if(parent[x] == -1) return x;
      return parent[x] = getParent(parent[x]);
   }
   string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
      int n = s.size();
      parent = vector <int>(n, -1);
      string ret(n, '*');
      for(int i = 0; i < pairs.size(); i++){
         int u = pairs[i][0];
         int v = pairs[i][1];
         if(getParent(u) == getParent(v)) continue;
         parent[getParent(u)] = getParent(v);
      }
      vector < char > arr1[n];
      for(int i = 0; i < n; i++){
         arr1[getParent(i)].push_back(s[i]);
      }
      for(int i = 0; i < n; i++){
         sort(arr1[i].rbegin(), arr1[i].rend());
      }
      for(int i = 0; i < n; i++){
         ret[i] = arr1[getParent(i)].back();
         arr1[getParent(i)].pop_back();
      }
      return ret;
   }
};
"dcab"
[[0,3],[1,2]]
"bacd"
C++ Program to Perform Addition Operation Using Bitwise Operators

Bitwise operators are used to perform bitwise operations. That implies the manipulation of bits. Some of the bitwise operators are bitwise AND, bitwise OR, bitwise XOR etc.
A program to perform addition operation using bitwise operators is given below −
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int num1, num2, carry;
   cout << "Enter first number:"<<endl;
   cin >> num1;
   cout << "Enter second number:"<<endl;
   cin >> num2;

   while (num2 != 0) {
      carry = num1 & num2;
      num1 = num1 ^ num2;
      num2 = carry << 1;
   }
   cout << "The Sum is: " << num1;
   return 0;
}
The output of the above program is as follows −
Enter first number:11
Enter second number: 5
The Sum is: 16
In the above program, the two numbers are obtained from the user. This is given below −
cout << "Enter first number:"<<endl;
cin >> num1;

cout << "Enter second number:"<<endl;
cin >> num2;
After that, addition is carried out using a while loop. It involves using the bitwise AND, bitwise XOR and left shift operators. The code snippet is given below −
while (num2 != 0) {
   carry = num1 & num2;
   num1 = num1 ^ num2;
   num2 = carry << 1;
}
Finally, the sum is displayed. This is given below −
cout << "The Sum is: " << num1;
Kth Largest Element in a Stream in Python

Suppose we want to design a class to find the kth largest element in a stream. It is the kth largest element in the sorted order, not the kth distinct element.
The KthLargest class will have a constructor which accepts an integer k and an array nums, that will contain initial elements from the stream. For each call to the method KthLargest.add, will return the element representing the kth largest element in the stream.
So, if the input is like k = 3, initial elements = [4,5,8,2], then call add(3), add(5), add(10), add(9), add(4). , then the output will be 4,5,5,8,8 respectively.
To solve this, we will follow these steps −
Define the initializer, This will take k, numsarray := nums
array := nums
Define a function add() . This will take valinsert val at the end of arraysort the arrayreturn array[size of array -k]
insert val at the end of array
sort the array
return array[size of array -k]
Let us see the following implementation to get better understanding −
 Live Demo
class KthLargest:
   def __init__(self, k, nums):
      self.array = nums
      self.k = k
   def add(self, val):
      self.array.append(val)
      self.array.sort()
      return self.array[len(self.array)-self.k]
ob = KthLargest(3, [4,5,8,2])
print(ob.add(3))
print(ob.add(5))
print(ob.add(10))
print(ob.add(9))
print(ob.add(4))
ob.add(3)
ob.add(5)
ob.add(10)
ob.add(9)
ob.add(4)
4
5
5
8
8
C++ Queue Library - front() Function

The C++ function std::queue::front() returns a reference to the first element of the queue. This element will be removed after performing  pop operation on queue.
This member function effectively calls the front member function of underlying container.
Following is the declaration for std::queue::front() function form std::queue header.
value_type& front();
const value_type& front() const;

reference& front();
const_reference& front() const;

None
Returns reference to the first element of the queue.
Constant i.e. O(1)
The following example shows the usage of std::queue::front() function.
#include <iostream>
#include <queue>

using namespace std;

int main(void) {
   queue<int> q;

   for (int i = 0; i < 5; ++i)
      q.emplace(i + 1);

   cout << "First element of queue = " << q.front() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
First element of queue = 1

 Print
 Add Notes
 Bookmark this page
How to write a jQuery selector to find links with # in href attribute?

You can try to run the following code to write a jQuery selector to find links with # in href. Here,^ is used to find links starting with # in href.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

   $('a[href^="#"]').click(function(){
      alert('Success! Selected link starting with # in href.');
   });

});
</script>
</head>
<body>

<a href="#demo" title="new" >Demo</a><br>
<a href="/cplusplus/" title="C++ Tutorial" >C++</a>

</body>
</html>
C# String Concat with examples

To concat strings in C#, use the String.Concat() method.
public static string Concat (string str1, string str2);
Above, the parameters str1 and str2 are the strings to be concatenated.
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Jack";
      string str2 = "Sparrow";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("Does String1 begins with E? = "+str1.StartsWith("E"));
      Console.WriteLine("\nString 2 = "+str2);
      Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());
      Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E"));
      Console.WriteLine("\nString 1 is equal to String 2? = {0}", str1.Equals(str2));
      Console.WriteLine("Concatenation Result = "+String.Concat(str1,str2));
   }
}
String 1 = Jack
HashCode of String 1 = 1167841345
Does String1 begins with E? = False
String 2 = Sparrow
HashCode of String 2 = -359606417
Does String2 begins with E? = False
String 1 is equal to String 2? = False
Concatenation Result = JackSparrow
Let us now see another example wherein we will use the concat() method with only a single parameter.
public static string Concat (params string[] arr);
Above, arr is the string array.
 Live Demo
using System;
public class Demo {
   public static void Main(string[] args) {
      string[] strArr = {"This", "is", "it", "!" };
      Console.WriteLine("String Array...");
      foreach(string s in strArr) {
         Console.WriteLine(s);
      }      
      Console.WriteLine("Concatenation = {0}",string.Concat(strArr));
      string str = string.Join("/", strArr);
      Console.WriteLine("Result (after joining) = " + str);
   }
}
String Array...
This
is
it
!
Concatenation = Thisisit!
Result (after joining) = This/is/it/!
How to create a JSON using Jackson Tree Model in Java?

In the Jackson library, we can use the Tree Model to represent the JSON structure and perform the CRUD operations via JsonNode. This Jackson Tree Model is useful, especially in cases where a JSON structure does not map to Java classes. We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data.
public class JsonNodeFactory extends Object implements Serializable
import java.io.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
public class JacksonTreeModelTest {
   public static void main(String args[]) throws IOException {
      JsonNodeFactory factory = new JsonNodeFactory(false);
      ObjectMapper mapper = new ObjectMapper();
      ObjectNode employee = factory.objectNode();
      employee.put("empId", 125);
      employee.put("firstName", "Raja");
      employee.put("lastName", "Ramesh");
      ArrayNode technologies = factory.arrayNode();
      technologies.add("Python").add("Java").add("SAP");
      employee.set("technologies", technologies);
      System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee));
   }
}
{
   "empId" : 125,
   "firstName" : "Raja",
   "lastName" : "Ramesh",
   "technologies" : [ "Python", "Java", "SAP" ]
}
Renaming column name in a MongoDB collection?

To rename column name in a collection, you can use $rename operator. Following is the syntax
db.yourCollectionName.update({}, {$rename: {'yourOldColumName': 'yourNewColumnName'}}, false, true);
Let us first create a collection with documents:
> db.renamingColumnNameDemo.insertOne({"StudentName":"Larry","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ee2c6d628fa4220163b9a")
}
> db.renamingColumnNameDemo.insertOne({"StudentName":"Sam","Age":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ee2d0d628fa4220163b9b")
}
> db.renamingColumnNameDemo.insertOne({"StudentName":"Robert","Age":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ee2dbd628fa4220163b9c")
}
Following is the query to display all documents from a collection with the help of find() method
> db.renamingColumnNameDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"),
   "StudentName" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"),
   "StudentName" : "Sam",
   "Age" : 26
}
{
   "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"),
   "StudentName" : "Robert",
   "Age" : 27
}
Following is the query to rename column name in a MongoDB collection
> db.renamingColumnNameDemo.update({}, {$rename: {'Age': 'StudentAge'}}, false, true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Now check the column Age has been renamed with “StudentAge”
> db.renamingColumnNameDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"),
   "StudentName" : "Larry",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"),
   "StudentName" : "Sam",
   "StudentAge" : 26
}
{
   "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"),
   "StudentName" : "Robert",
   "StudentAge" : 27
}
Get MongoDB Databases in a JavaScript Array?

To get MongoDB databases in a JavaScript array, you can use runCommand(). Following is the query to get MongoDB databases in a JavaScript array
> use admin;
switched to db admin
> allDatabasesDetails = db.runCommand({listDatabases: 1});
This will produce the following output
{
   "databases" : [
      {
         "name" : "admin",
         "sizeOnDisk" : 847872,
         "empty" : false
      },
      {
         "name" : "config",
         "sizeOnDisk" : 98304,
         "empty" : false
      },
      {
         "name" : "local",
         "sizeOnDisk" : 73728,
         "empty" : false
      },
      {
         "name" : "sample",
         "sizeOnDisk" : 1273856,
         "empty" : false
      },
      {
         "name" : "sampleDemo",
         "sizeOnDisk" : 352256,
         "empty" : false
      },
      {
         "name" : "studentSearch",
         "sizeOnDisk" : 262144,
         "empty" : false
      },
      {
         "name" : "test",
         "sizeOnDisk" : 9527296,
         "empty" : false
      }
   ],
   "totalSize" : 12435456,
   "ok" : 1
}
Following is the query to get total databases:
> allDatabaseName = []
[ ]
> for (var j in allDatabasesDetails.databases) { allDatabaseName.push(dbs.databases[j].name) }
This will produce the following output
7
PyQt5 QSpinBox - How to get the font of spin box - GeeksforGeeks

19 May, 2020
In this article we will see how we can get the font of all the text present in the spin box, in order to set the font use setFont method which takes QFont object as argument, using it with the spin box object will change the font of all the text.
In order to get the font we use font method
Syntax : spin_box.font()
Argument : It takes no argument
Return : It returns QFont object
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for widgets    def UiComponents(self):        # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting range to the spin box        self.spin.setRange(0, 999999)          # setting prefix to spin        self.spin.setPrefix("Prefix ")          # setting suffix to spin        self.spin.setSuffix(" Suffix")          # setting font to the spin box        self.spin.setFont(QFont('Arial', 12))          # creating a label        label = QLabel(self)          # making it multi line        label.setWordWrap(True)          # setting its geometry        label.setGeometry(100, 200, 200, 60)          # getting font of spin box        font = self.spin.font()          # setting text to the label        label.setText(str(font))      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to Count The Occurrences of a List Item in Python | Towards Data Science

Counting the number of occurrences of list elements in Python is definitely a fairly common task. In today’s short guide we will explore a few different ways for counting list items. More specifically, we will explore how to
count the number of occurrences of a single list item
count the occurrences of multiple list items
We will showcase how to achieve both using a specific list method or with the help of collections module.
First, let’s create an example list that we’ll reference throughout this guide in order to demonstrate a few concepts.
>>> my_lst = [1, 1, 2, 3, 1, 5, 6, 2, 3, 3]>>> my_lst[1, 1, 2, 3, 1, 5, 6, 2, 3, 3]
The first option you have when it comes to counting the number of times a particular element appears in a list, is list.count() method. For instance, in order to count how many times 1 appears in list my_lst you simply need to run the following command
>>> my_lst.count(1)3
Alternatively, you can even use the Counter class that comes with the collections module. collections.Counter class is a subclass of dict that is used to count hashable objects. Essentially, it is a collection whether the elements for which counts are observed are stored as dictionary keys and their corresponding counts are stored as dictionary values.
>>> from collections import Counter>>>>>> Counter(my_lst)[1]3
Now if you want to count the number of times multiple items appear in a given list then again, you have a couple of options for doing so.
The first option you have is to call list.count() within a for-loop. Let’s say you want to count the number of times that list elements 1, 3 and 5 appear in our list. You can do so, as shown below:
>>> lookup = [1, 3, 5]>>> [my_lst.count(e) for e in lookup][3, 3, 1]
Alternatively, you can use collections.Counter class which in my opinion is more suitable when it comes to counting the number of occurrences of multiple items.
If you want to count the number of times every single element appears in the list then you can simply create an instance of Counter.
>>> from collections import Counter>>>>>> Counter(my_lst)Counter({1: 3, 2: 2, 3: 3, 5: 1, 6: 1})
If you want to count the number of times a subset of elements appear in the list then the following command will do the trick:
>>> from collections import Counter>>>>>> lookup = [1, 3, 5]>>> all_counts = Counter(my_lst)>>> counts = {k: all_counts[k] for k in lookup}>>> counts{1: 3, 3: 3, 5: 1}
In today’s short guide we explored a couple of different ways for counting the number of occurrences of list items in Python. We showcased how to use the list method count() or the collections.Counter class in order to count the occurrences of one or multiple list items.
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
gmyrianthous.medium.com
You may also like
How to draw an oval in HTML5 canvas?

You can try to run the following code to draw an oval in HTML5 canvas −
<!DOCTYPE HTML>
<html>
   <head>
   </head>
   <body>
      <canvas id="newCanvas" width="450" height="300"></canvas>
      <script>
         // canvas

         var c = document.getElementById('newCanvas');
         var context = c.getContext('2d');
         var cX = 0;
         var cY = 0;
         var radius = 40;
         
         context.save();
         context.translate(c.width / 2, c.height / 2);
         context.scale(2, 1);
         context.beginPath();
         context.arc(cX, cY, radius, 0, 2 * Math.PI, false);
         context.restore();
         context.fillStyle = '#000000';
         context.fill();
         context.lineWidth = 2;
         context.strokeStyle = 'yellow';
         context.stroke();
      </script>
   </body>
</html>
Perl m Function

This match operator is used to match any keyword in given expression. Parentheses after initial m can be any character and will be used to delimit the regular expression statement.
Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $', which contains everything after the matched string.
Following is the simple syntax for this function −
m//

This function returns 0 on failure and 1 on success,
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$string = "The food is in the salad bar";
$string =~ m/foo/;
print "Before: $`\n";
print "Matched: $&\n";
print "After: $'\n";
When above code is executed, it produces the following result −
Before: The 
Matched: foo
After: d is in the salad bar


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
D3.js randomNormal() Function - GeeksforGeeks

29 Jul, 2020
The randomNormal() function is used to return a function that gives a random number based on Normal distribution or Gaussian distribution. 
Syntax:
d3.randomNormal(mu, sigma);
Parameters: It takes the two parameters given above and described below.
mu: It is the expected value of the number. If mu is not given then it is considered as 0.
sigma: The number is generated with a certain standard deviation called sigma.
Returns: It returns a function.
Below given are a few examples of the above function.
Example 1: When mu is given.
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width,                 initial-scale=1.0">  <title>Document</title></head><style></style><body>  <!-- Fetching from CDN of D3.js -->  <script type = "text/javascript"           src = "https://d3js.org/d3.v4.min.js">   </script>  <script>// The ouput may be different on different machines.    console.log(d3.randomNormal(10, 10)())    console.log(d3.randomNormal(10, 10)())    console.log(d3.randomNormal(10, 10)())    console.log(d3.randomNormal(10, 10)())    console.log(d3.randomNormal(10, 10)())  </script></body></html>
Output:
Example 2: When mu is not given.
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width,                  initial-scale=1.0">  <title>Document</title></head><style></style><body>  <!-- Fetching from CDN of D3.js -->  <script type = "text/javascript"           src = "https://d3js.org/d3.v4.min.js">  </script>  <script>// The ouput may be different on different machines.    console.log(d3.randomNormal(5)())    console.log(d3.randomNormal(5)())    console.log(d3.randomNormal(5)())    console.log(d3.randomNormal(5)())    console.log(d3.randomNormal(5)())    console.log(d3.randomNormal(5)())  </script></body></html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Python | Checking triangular inequality on list of lists - GeeksforGeeks

03 Mar, 2019
Given a list of lists, the task is to find whether a sublist satisfies the triangle inequality.
The triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side. In other words, a triangle is valid if sum of its two sides is greater than the third side. If three sides are a, b and c, then three conditions should be met.
a + b > c 
a + c > b 
b + c > a  

Method #1 : Using List comprehension
# Python code to find whether a sublist # satisfies the triangle inequality.  # List initializationInput = [[1, 3, 1], [4, 5, 6]]  # Sorting sublistfor elem in Input:    elem.sort()  # Using list comprehensionOutput = [(p, q, r) for p, q, r in Input if (p + q)>= r]  # Printing outputprint(Output)
[(4, 5, 6)]

 Method #2 : Using Iteration
# Python code to find whether a sublist# satisfies the triangle inequality.  # List initializationInput = [[1, 1, 3], [4, 5, 6]]  # Sorting sublist of list of listfor elem in Input:    elem.sort()  # Checking for triangular inequalityfor elem in Input:    if elem[0] + elem[1] > elem[2]:        print(elem)
[4, 5, 6]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Number of Islands in Python

Suppose we have a grid, there are few 0s and few 1s. We have to count the number of islands. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water.
Suppose the grid is like −
There are three islands.
To solve this, we will follow these steps −
There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −
if number of rows in the grid is 0, then return 0
n = row count and m := column count, and ans := 0
for i in range 0 to n – 1for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)
for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)
if grid[i, j] = 1, then ans := ans + 1
makeWater(i, j, n, m, grid)
the makeWater() will take the indices i, j, row and col count n and m, and grid
if i <0 or j < 0 or i >= n or j >= m, then return from this method
if grid[i, j] = 0, then return otherwise make grid[i, j] := 0
call makeWater(i + 1, j, n, m, grid)
call makeWater(i, j + 1, n, m, grid)
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def numIslands(self, grid):
      if len(grid) == 0:
         return 0
      n= len(grid)
      m = len(grid[0])
      ans = 0
      for i in range(n):
         for j in range(m):
            if grid[i][j] == "1":
               ans+=1
            self.make_water(i,j,n,m,grid)
      return ans
   def make_water(self,i,j,n,m,grid):
      if i<0 or j<0 or i>=n or j>=m:
         return
      if grid[i][j] == "0":
         return
      else:
         grid[i][j]="0"
      self.make_water(i+1,j,n,m,grid)
      self.make_water(i,j+1,n,m,grid)
      self.make_water(i-1,j,n,m,grid)
      self.make_water(i,j-1,n,m,grid)
ob1 = Solution()
print(ob1.numIslands([["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],
["0","0","0","1","1"]]))
[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
3
General Aptitude - GeeksforGeeks

22 Jan, 2014
Profit = Price - Cost
       = 50q - 5q2
The above function will be maximum for the values on which its first derivative becomes 0.
        50 - 10*q = 0
        50 = 10 * q
        q = 5.
The value of above expression is maximum at q = 5. 
Probability that the absorber is reliable = 0.96*0.6 + 0.72*0.4 
                                          = 0.576 + 0.288


Probability that  the absorber is from y and reliable = 
            (Probability that is made by Y)  X (Probability that it is reliable)
           = 0.4 * 0.72 
           = 0.288

The probability that randomly picked reliable absorber is from y = 
    (Probability that  the absorber is from y and reliable) / (>Probability that the absorber is reliable )
   = (0.288)/ (0.576 + 0.288) 
   =  0.334 
Let us consider below example


These eight data points have the mean (average) of 5:


When we add 7 to all numbers, mean becomes 12 so P is TRUE.

If we double all numbers mean becomes double, so R is also
TRUE.

Standard Deviation is square root of variance.
Variance is sum of squares of differences between all numbers
and means.

Deviation for above example
First, calculate the deviations of each data point from the mean, 
and square the result of each:







If we add 7 to all numbers, standard deviation won't change 
as 7 is added to mean also. So Q is FALSE.

If we double all entries, standard deviation also becomes 
double.  So S is false. 
It is given that Log(P) = (1/2)Log(Q) = (1/3)Log(R)

Let Log(P) = (1/2)Log(Q) = (1/3)Log(R) = C

Let the base of log be B

P = BC
Q = B2C
R = B3C

Which means Q2 = PR
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
SQL Query to Convert VARCHAR to INT
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
Check if a string is Isogram or not in Python

Suppose we have a string s. We have to check whether the given string is isogram or not. The isogram is a string where the occurrence of each letter is exactly one.
So, if the input is like s = "education", then the output will be True because all characters in "education" occurs exactly once.
To solve this, we will follow these steps −
char_list := a new list
for each char in word, doif char is non numeric, thenif char is in char_list, thenreturn Falseinsert char at the end of char_list
if char is non numeric, thenif char is in char_list, thenreturn Falseinsert char at the end of char_list
if char is in char_list, thenreturn False
return False
insert char at the end of char_list
return True
Let us see the following implementation to get better understanding −
 Live Demo
def solve(word):
   char_list = []
   for char in word:
      if char.isalpha():
         if char in char_list:
            return False
            char_list.append(char)
   return True
s = "education"
print(solve(s))
"education"
True
HTTP headers | Referer - GeeksforGeeks

22 Nov, 2019
The HTTP Referer header is a request-type header that identifies the address of the previous web page, which is linked to the current web page or resource being requested. The usage of this header increases the risk of privacy and security breaches on a website but it allows websites and web servers to identify where the traffic is coming from. The Referer can not be sent by the browsers if the resource is the local file or data.
Syntax:
Referer: <url>
Directives: The HTTP Referer header accepts a single directive as mentioned above and described below:
<url>: This directive is the address(partial or full) of the previous World Wide Web page which was followed by a link to the currently requested page.
Below examples illustrates the HTTP Referer header:
Examples:
In this example, geeksforgeeks.org is the address of the previous web page.Referer: https://www.geeksforgeeks.org/
Referer: https://www.geeksforgeeks.org/
In this example, google.com is the address of the previous web page.Referer: https://www.google.com/
Referer: https://www.google.com/
To check the Referer in action go to Inspect Element -> Network check the request header for Referer like below. Referer header is highlighted.Supported Browsers: The browsers are compatible with HTTP header Referer are listed below:
Google Chrome
Internet Explorer
Microsoft Edge
Firefox
Opera
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ?
File uploading in React.js
Create a Numpy array filled with all zeros | Python - GeeksforGeeks

24 Oct, 2019
In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array.
We can use Numpy.zeros() method to do this task. This method takes three parameters, discussed below –
shape : integer or sequence of integers
order  : C_contiguous or F_contiguous
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
dtype : [optional, float(byDeafult)] Data type of returned array.  

Example #1:
# Python Program to create array with all zerosimport numpy as geek   a = geek.zeros(3, dtype = int) print("Matrix a : \n", a)   b = geek.zeros([3, 3], dtype = int) print("\nMatrix b : \n", b) 
Output:
Matrix a : 
 [0 0 0]

Matrix b : 
 [[0 0 0]
 [0 0 0]
 [0 0 0]]


Example #2:
# Python Program to create array with all zerosimport numpy as geek   c = geek.zeros([5, 3]) print("\nMatrix c : \n", c)   d = geek.zeros([5, 2], dtype = float) print("\nMatrix d : \n", d) 
Output:
Matrix c : 
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

Matrix d : 
 [[ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]]


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