code-rag-bench/online-tutorials huggingface dataset:
Lex code to count total number of tokens

21 May, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lex in the C programming language.
Tokens: A token is a group of characters forming a basic atomic chunk of syntax i.e. token is a class of lexemes that matches a pattern. Eg – Keywords, identifier, operator, separator.
Example:
Input: int p=0, d=1, c=2;

Output: 
total no. of tokens = 13

Below is the implementation of the above explanation:
/*Lex code to count total number of tokens */  %{ int n = 0 ;  %}   // rule section%%   //count number of keywords"while"|"if"|"else" {n++;printf("\t keywords : %s", yytext);}    // count number of keywords"int"|"float" {n++;printf("\t keywords : %s", yytext);}     // count number of identifiers[a-zA-Z_][a-zA-Z0-9_]* {n++;printf("\t identifier : %s", yytext);}   // count number of operators"<="|"=="|"="|"++"|"-"|"*"|"+" {n++;printf("\t operator : %s", yytext);}  // count number of separators[(){}|, ;]    {n++;printf("\t separator : %s", yytext);}   // count number of floats[0-9]*"."[0-9]+ {n++;printf("\t float : %s", yytext);}    // count number of integers[0-9]+ {n++;printf("\t integer : %s", yytext);}                          .    ;%%       int main()   {           yylex();          printf("\n total no. of token = %d\n", n);          } 
Output:
Ravimaurya2
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
How to write Python Regular Expression find repeating digits in a number?

The following code using Python regex to find the repeating digits in given string
import re
result = re.search(r'(\d)\1{3}','54222267890' )
print result.group()
This gives the output
2222
CSS - Scrollbars

There may be a case when an element's content might be larger than the amount of space allocated to it. For example, given width and height properties do not allow enough room to accommodate the content of the element.
CSS provides a property called overflow which tells the browser what to do if the box's contents is larger than the box itself. This property can take one of the following values −
visible
Allows the content to overflow the borders of its containing element.
hidden
The content of the nested element is simply cut off at the border of the containing element and no scrollbars is visible.
scroll
The size of the containing element does not change, but the scrollbars are added to allow the user to scroll to see the content.
auto
The purpose is the same as scroll, but the scrollbar will be shown only if the content does overflow.
Here is an example −
<html>
   <head>
      <style type = "text/css">
         .scroll {
            display:block;
            border: 1px solid red;
            padding:5px;
            margin-top:5px;
            width:300px;
            height:50px;
            overflow:scroll;
         }
         .auto {
            display:block;
            border: 1px solid red;
            padding:5px;
            margin-top:5px;
            width:300px;
            height:50px;
            overflow:auto;
         }
      </style>
   </head>

   <body>
      <p>Example of scroll value:</p>
      <div class = "scroll">
         I am going to keep lot of content here just to show you how 
         scrollbars works if there is an overflow in an element box. 
         This provides your horizontal as well as vertical scrollbars.
      </div>
      <br />
      
      <p>Example of auto value:</p>
      
      <div class = "auto">
         I am going to keep lot of content here just to show you how 
         scrollbars works if there is an overflow in an element box. 
         This provides your horizontal as well as vertical scrollbars.
      </div>
   </body>
</html> 
It will produce the following result −
Example of scroll value:
Example of auto value:

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

28 Jul, 2020
Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner.
Solution: Every smart contract is owned by an address called as owner. A smart contract can know its owner’s address using sender property and its available balance using a special built-in object called msg.
Step 1: Open Remix-IDE.
Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on New option below the Solidity environment. Enter the file name as MyContract.sol and Click on the OK button.
Step 3: Enter the following Solidity Code. 
Solidity
// Solidity program to// retrieve address and// balance of ownerpragma solidity ^0.6.8;       // Creating a contractcontract MyContract{    // Private state variable    address private owner;       // Defining a constructor        constructor() public{           owner=msg.sender;    }      // Function to get     // address of owner    function getOwner(    ) public view returns (address) {            return owner;    }      // Function to return     // current balance of owner    function getBalance(    ) public view returns(uint256){        return owner.balance;    }}
Step 4:  Compile the file MyContract.sol from the Solidity Compiler tab. 
Step 5: Deploy the smart contract from the Deploy and Run Transaction tab and you will get the balance and address of the owner.
Step 6: The output below shows the address and the balance of the owner.
 
BlockChain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Dynamic Arrays and its Operations in Solidity
Steps to Execute Solidity Smart Contract using Remix IDE
Solidity - View and Pure Functions
Solidity - Error Handling
Solidity - Types
Solidity - Functions
What are Events in Solidity?
Solidity - Libraries
Flutter and Blockchain - Hello World Dapp
Random Number Generator in Solidity using keccak256
C++ Program to Display Prime Numbers Between Two Intervals Using Functions

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are 2, 3, 5, 7, 11, 13 ,17 etc.
There can be many prime numbers between two intervals. For example, the prime numbers between the intervals 5 and 20 are 5, 7, 11, 13, 17 and 19.
The program to find and display the prime numbers between two intervals is given as follows.
 Live Demo
#include <iostream>
using namespace std;
void primeNumbers (int lbound, int ubound) {
   int flag, i;
   while (lbound <= ubound) {
      flag = 0;
      for(i = 2; i <= lbound/2; i++) {
         if(lbound % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0)
      cout<<lbound<<" ";
      lbound++;
   }
}
int main() {
   int lowerbound = 20, upperbound = 50;
   cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
   primeNumbers(lowerbound,upperbound);
   return 0;
}
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
In the above program, the function main() contains only the cout object and the function call to the function primeNumbers() with upperbound and lowerbound as arguments. This can be seen in the following code snippet.
cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
primeNumbers(lowerbound,upperbound);
In the function primeNumbers(), each number from lbound to ubound is tested to see if it is prime or not. If it is a prime number, it is displayed. This is done using a while loop.
In the while loop, initial value of flag=0. If the number is not prime, then the value of flag is set to 1 in the for loop. After the end of the for loop, if flag is still 0, then the number is prime and it is displayed. This can be observed from the following code snippet.
while (lbound <= ubound) {
   flag = 0;
   for(i = 2; i <= lbound/2; i++) {
      if(lbound % i == 0) {
         flag = 1;
         break;
      }
   }
   if (flag == 0)
   cout<<lbound<<" ";
   lbound++;
}
Mean Shift Clustering Algorithm Example In Python | by Cory Maklin | Towards Data Science

Mean Shift is a hierarchical clustering algorithm. In contrast to supervised machine learning algorithms, clustering attempts to group data without having first been train on labeled data. Clustering is used in a wide variety of applications such as search engines, academic rankings and medicine. As opposed to K-Means, when using Mean Shift, you don’t need to know the number of categories (clusters) beforehand. The downside to Mean Shift is that it is computationally expensive — O(n2).
Define a window (bandwidth of the kernel) and place the window on a data point
Define a window (bandwidth of the kernel) and place the window on a data point
2. Calculate the mean for all the points in the window
3. Move the center of the window to the location of the mean
4. Repeat steps 2 and 3 until there is convergence
Let’s take a look at how we could go about labeling the data using the Mean Shift algorithm in python.
import numpy as npimport pandas as pdfrom sklearn.cluster import MeanShiftfrom sklearn.datasets.samples_generator import make_blobsfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D
We generate our own data using the make_blobs method.
clusters = [[1,1,1],[5,5,5],[3,10,10]]X, _ = make_blobs(n_samples = 150, centers = clusters, cluster_std = 0.60)
After training the model, we store the coordinates for the cluster centers.
ms = MeanShift()ms.fit(X)cluster_centers = ms.cluster_centers_
Finally, we plot the data points and centroids in a 3D graph.
fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.scatter(X[:,0], X[:,1], X[:,2], marker='o')ax.scatter(cluster_centers[:,0], cluster_centers[:,1], cluster_centers[:,2], marker='x', color='red', s=300, linewidth=5, zorder=10)plt.show()
getopt() function in C to parse command line arguments

The getopt() is one of the built-in C function that are used for taking the command line options. The syntax of this function is like below −
getopt(int argc, char *const argv[], const char *optstring)
The opstring is a list of characters. Each of them representing a single character option.
This function returns many values. These are like below −
If the option takes a value, then that value will be pointed by optarg.
It will return -1, when no more options to proces
Returns ‘?’ to show that this is an unrecognized option, it stores it to optopt.
Sometimes some options need some value, If the option is present but the values are not there, then also it will return ‘?’. We can use ‘:’ as the first character of the optstring, so in that time, it will return ‘:’ instead of ‘?’ if no value is given.
#include <stdio.h>
#include <unistd.h>

main(int argc, char *argv[]) {
   int option;
   // put ':' at the starting of the string so compiler can distinguish between '?' and ':'
   while((option = getopt(argc, argv, ":if:lrx")) != -1){ //get option from the getopt() method
      switch(option){
         //For option i, r, l, print that these are options
         case 'i':
         case 'l':
         case 'r':
            printf("Given Option: %c\n", option);
            break;
         case 'f': //here f is used for some file name
            printf("Given File: %s\n", optarg);
            break;
         case ':':
            printf("option needs a value\n");
            break;
         case '?': //used for some unknown options
            printf("unknown option: %c\n", optopt);
            break;
      }
   }
   for(; optind < argc; optind++){ //when some extra arguments are passed
      printf("Given extra arguments: %s\n", argv[optind]);
   }
}
Given Option: i
Given File: test_file.c
Given Option: l
Given Option: r
Given extra arguments: hello
How do I add a simple onClick event handler to an HTML5 canvas element?

The elements that are drawn in canvas element have no representation. Their only representation is the pixels they use and their color. Drawing to a canvas element means drawing a bitmap in immediate mode. To get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and determine which element was clicked. This requires storing the element’s width and height.
To add a click event to your canvas element, use the below-given code
canvas.addEventListener('click', function() { }, false);
To determine what element was clicked, use the following code snippet −
var e = document.getElementById('myCanvas'),
   elemLeft = e.offsetLeft,
   elemTop = e.offsetTop,
   context = e.getContext('2d'),
   elements = [];

// event listener for click event
e.addEventListener('click', function(event) {
   var xVal = event.pageX - elemLeft,
   yVal = event.pageY - elemTop;
   console.log(xVal, yVal);
   elements.forEach(function(ele) {
      if (yVal > ele.top && yVal < ele.top + ele.height && xVal > ele.left && xVal < ele.left + ele.width) {
         alert(‘element clicked');
      }
   });
}, false);
elements.push({
   colour: '#1C2128’,
   width: 250,
   height: 200,
   top: 30,
   left: 20
});
elements.forEach(function(ele) {
   context.fillStyle = element.colour;
   context.fillRect(ele.left, ele.top, ele.width, ele.height);
});
time.Unix() Function in Golang with Examples

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Unix() function in Go language is used to yield the local time which is related to the stated Unix time from January 1, 1970, in UTC. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func Unix(sec int64, nsec int64) Time

Here, “sec” is seconds which is of type int64 and “nsec” is nanoseconds which is also of type int64.
Note: It is reasonable to permit “nsec” outside the range [0, 999999999]. However, not every “sec” values have a equivalent time value and one analogous value is 1<<63-1, which is the largest int64 value.
Return value: It returns the local time which is equivalent to the stated Unix time from January 1, 1970 in UTC.
Example 1:
// Golang program to illustrate the usage of// time.Unix() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling Unix method with 275 seconds    // and zero nanoseconds and also    // printing output    fmt.Println(time.Unix(275, 0).UTC())      // Calling Unix method with 0 seconds and    // 566 nanoseconds and also printing    // output    fmt.Println(time.Unix(0, 566).UTC())      // Calling Unix method with 456 seconds and    // -67 nanoseconds and also printing    // output    fmt.Println(time.Unix(456, -67).UTC())}
Output:
1970-01-01 00:04:35 +0000 UTC
1970-01-01 00:00:00.000000566 +0000 UTC
1970-01-01 00:07:35.999999933 +0000 UTC

Example 2:
// Golang program to illustrate the usage of// time.Unix() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling Unix method with 2e1 seconds    // and zero nanoseconds and also    // printing output    fmt.Println(time.Unix(2e1, 0).UTC())      // Calling Unix method with 0 seconds and    // 1e13 nanoseconds and also printing    // output    fmt.Println(time.Unix(0, 1e13).UTC())      // Calling Unix method with 1e1 seconds and    // -1e15 nanoseconds and also printing    // output    fmt.Println(time.Unix(1e1, -1e15).UTC())}
Output:
1970-01-01 00:00:20 +0000 UTC
1970-01-01 02:46:40 +0000 UTC
1969-12-20 10:13:30 +0000 UTC

Here, the parameters of the Unix() method stated in the above code have values that contain a constant “e” which is converted in usual range while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
Python Program for ShellSort

16 Jun, 2022
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h\’th element is sorted. 
Python
# Python program for implementation of Shell Sort def shellSort(arr):     # Start with a big gap, then reduce the gap    n = len(arr)    gap = n/2     # Do a gapped insertion sort for this gap size.    # The first gap elements a[0..gap-1] are already in gapped    # order keep adding one more element until the entire array    # is gap sorted    while gap > 0:         for i in range(gap,n):             # add a[i] to the elements that have been gap sorted            # save a[i] in temp and make a hole at position i            temp = arr[i]             # shift earlier gap-sorted elements up until the correct            # location for a[i] is found            j = i            while  j >= gap and arr[j-gap] >temp:                arr[j] = arr[j-gap]                j -= gap             # put temp (the original a[i]) in its correct location            arr[j] = temp        gap /= 2  # Driver code to test abovearr = [ 12, 34, 54, 2, 3] n = len(arr)print ("Array before sorting:")for i in range(n):    print(arr[i]), shellSort(arr) print ("\nArray after sorting:")for i in range(n):    print(arr[i]), # This code is contributed by Mohit Kumra
Output:
Array before sorting:
12 34 54 2 3 
Array after sorting:
2 3 12 34 54
Time Complexity: O(n2)
Auxiliary Space: O(1)
Please refer complete article on ShellSort for more details!
chandramauliguptach
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Multiple Sets Intersection

02 Feb, 2021
In this article given List of sets, the task is to write a Python program to perform their intersection.
Examples:
Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
Output : {3, 5}
Explanation : 3 and 5 is present in all the sets.
Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 4}]
Output : {5}
Explanation : 5 is present in all the sets.
Method #1 : Using intersection() + * operator
In this, we perform tasks of getting intersection using intersection() and * operator is used to pack all the sets together.
Python3
# Python3 code to demonstrate working of# Multiple Sets Intersection# Using intersection() + * operator  # initializing listtest_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]  # printing original listprint("The original list is : " + str(test_list))  # getting all sets intersection using intersection()res = set.intersection(*test_list)  # printing resultprint("Intersected Sets : " + str(res))
Output:
The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}
Method #2 : Using reduce() + and_ operator
In this, we perform task of intersection using and_ operator and reduce() does the task of getting all the sets packed together for required operation.
Python3
# Python3 code to demonstrate working of# Multiple Sets Intersection# Using reduce() + and_ operatorfrom operator import and_from functools import reduce  # initializing listtest_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]  # printing original listprint("The original list is : " + str(test_list))  # getting all sets intersection using and_ operatorres = set(reduce(and_, test_list))  # printing resultprint("Intersected Sets : " + str(res))
Output:
The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}
Python set-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
Solidity - Assembly

Solidity provides an option to use assembly language to write inline assembly within Solidity source code. We can also write a standalone assembly code which then be converted to bytecode. Standalone Assembly is an intermediate language for a Solidity compiler and it converts the Solidity code into a Standalone Assembly and then to byte code. We can used the same language used in Inline Assembly to write code in a Standalone assembly.
Inline assembly code can be interleaved within Solidity code base to have more fine-grain control over EVM and is used especially while writing the library functions.
An assembly code is written under assembly { ... }  block. 
Try the following code to understand how a Library works in Solidity.
pragma solidity ^0.5.0;

library Sum {   
   function sumUsingInlineAssembly(uint[] memory _data) public pure returns (uint o_sum) {
      for (uint i = 0; i < _data.length; ++i) {
         assembly {
            o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20))))
         }
      }
   }
}
contract Test {
   uint[] data;
   
   constructor() public {
      data.push(1);
      data.push(2);
      data.push(3);
      data.push(4);
      data.push(5);
   }
   function sum() external view returns(uint){      
      return Sum.sumUsingInlineAssembly(data);
   }
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 15


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Clojure - If/do Expression

The ‘if-do’ expression in Clojure is used to allow multiple expressions to be executed for each branch of the ‘if’ statement. We have seen in the classic ‘if’ statement in Clojure that you can just have two statements, one which is executed for the true part and the other which is for the false part. But the ‘if-do’ expression allows you to use multiple expressions. Following is the general form of the ‘if-do’ expression.
if(condition) (
   statement #1
   statement #1.1
)

(
   statement #2
   statement #2.1
)

Following is an example of a ‘for if-do’ statement.
(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example [] (
   if (= 2 2)
      (do(println "Both the values are equal")
         (println "true"))
      (do(println "Both the values are not equal")
         (println "false"))))
(Example)
In the above example, the ‘if’ condition is used to evaluate whether the values of 2 and 2 are equal. If they are, then it will print the value of “Values are equal” and in addition we are printing the value of “true”, else it will print the value of “Values are not equal” and the value of “false”.
The above code produces the following output.
Both the values are equal
true

 Print
 Add Notes
 Bookmark this page
Python | Convert an array to an ordinary list with the same items

21 Nov, 2018
Prerequisite : Array in Python
Python program to convert an array to an ordinary list with the same items.
Examples:
Input : array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Output :[1, 3, 5, 3, 7, 1, 9, 3]
Explanation: the array with elements [1, 3, 5, 3, 
7, 1, 9, 3] are converted into list with the 
same elements.

Input :array('k', [45, 23, 56, 12])
Output :[45, 23, 56, 12]
Explanation: the array with elements [45, 23, 56, 
12] are converted into list with the same elements.

Approach to the problem:We want to convert an array into an ordinary list with the same items. For doing so we need to use a function
// This function tolist() converts the array into a list.
arrayname.tolist()
from array import *def array_list(array_num):    num_list = array_num.tolist() # list    print(num_list)  # driver codearray_num = array('i', [45,34,67]) # arrayarray_list(array_num)
Output:
[45, 34, 67]

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
C++ Program to Implement Set_Union in STL

The union of two sets is created by the elements that are present in either one of the sets, or in both. Elements from the second set that has the same element in the first set are not copied to the resulting set.
Common set operations are −
Set Union
Set Intersection
Symmetric Set Difference or Exclusive-OR
Set Difference or Subtraction
Begin
   Declare set vector v and iterator st.
   Initialize st= set_union (set1, set1 + n, set2, set2 +n, v.begin()))
   Print the elements.
End.
 Live Demo
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
   int set1[] = {5,6,7,8,9,10};
   int set2[] = {1,2,3,4,6,7};
   vector<int> v(10);
   vector<int>::iterator st;
   sort (set1, set1 + 6);
   sort (set2, set2 + 6);
   st = set_union(set1, set1 + 6, set2, set2 + 6, v.begin());
   v.resize(st - v.begin());
   cout<<"The union between the sets has "<< (v.size())<< " elements: "<<endl;
   for (st = v.begin(); st != v.end(); ++st)
      cout<< *st<<" ";
   cout <<endl;
   return 0;
}
The union between the sets has 10 elements:
1 2 3 4 5 6 7 8 9 10
Difference between Int16 and UInt16 in C# - GeeksforGeeks

26 May, 2020
Int16: This Struct is used to represents 16-bit signed integer. The Int16 can store both types of values including negative and positive between the ranges of -32768 to +32767.
Example :
C#
// C# program to show the// difference between Int16// and UInt16  using System;using System.Text;  publicclass GFG {    // Main Method  static void Main(string[] args) {      // printing minimum & maximum values    Console.WriteLine("Minimum value of Int16: "                       + Int16.MinValue);    Console.WriteLine("Maximum value of Int16: "                       + Int16.MaxValue);    Console.WriteLine();      // Int16 array    Int16[] arr1 = {-3, 0, 1, 3, 7};      foreach (Int16 i in arr1)    {       Console.WriteLine(i);    }  }}
Output:
Minimum value of Int16: -32768
Maximum value of Int16: 32767

-3
0
1
3
7

UInt16: This Struct is used to represents 16-bit unsigned integer. The UInt16 can store only positive value only which ranges from 0 to 65535.
Example :
C#
// C# program to show the // difference between Int16 // and UInt16  using System;using System.Text;  public class GFG{          // Main Method    static void Main(string[] args)    {          // printing minimum & maximum values        Console.WriteLine("Minimum value of UInt16: "                          + UInt16.MinValue);        Console.WriteLine("Maximum value of UInt16: "                          + UInt16.MaxValue);        Console.WriteLine();                  // Int16 array        UInt16[] arr1 = { 13, 0, 1, 3, 7};                  foreach (UInt16 i in arr1)        {            Console.WriteLine(i);        }    }}
Output:
Minimum value of UInt16: 0
Maximum value of UInt16: 65535

13
0
1
3
7

Differences between Int16 and UInt16in C#
Sr.No
INT16
UINT16
1.
2.
3.
4.
5.
 6.
 Syntax to declare the Int16 :
Int16 variable_name;

  Syntax to declare the UInt16 :
UInt16 variable_name;

CSharp-Int16-Struct
CSharp-UInt16-Struct
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | Constructors
Extension Method in C#
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
cut - Unix, Linux Command

cut - To divide a file into several parts (columns)
cut [OPTION]... [FILE]...
cur writes to standard output selected parts of each line of each input file, or standard input if no files are given or for a file name of '-'.
Let's have a sample file sample.txt
$ cat sample.txt
1;2;3;4;5;6;7;8;9

To Parse out column 2 from a semicolon (;) delimited file:
$ cat sample.txt | cut -d \; -f 2 > output.txt
$ cat output.txt
2


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Update array in MongoDB document by variable index?

To update array in MongoDB document by variable index, use the below syntax. Here, yourIndexValue in the index value, where yourIndexVariableName is the variable name for index −
var yourIndexVariableName= yourIndexValue,
anyVariableName= { "$set": {} };
yourVariableName["$set"]["yourFieldName."+yourIndexVariableName] = "yourValue";
db.yourCollectionName.update({ "_id":  yourObjectId}, yourVariableName);
Let us first create a collection with documents −
> db.updateByVariableDemo.insertOne({"StudentSubjects":["MySQL","Java","SQL Server","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd553c37924bb85b3f4893a")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateByVariableDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd553c37924bb85b3f4893a"),
   "StudentSubjects" : [
      "MySQL",
      "Java",
      "SQL Server",
      "PL/SQL"
   ]
}
Following is the query to update array in MongoDB document by variable index −
> var indexValue = 1,
... valueToUpdate= { "$set": {} };
> valueToUpdate["$set"]["StudentSubjects."+indexValue] = "MongoDB";
MongoDB
> db.updateByVariableDemo.update({ "_id":  ObjectId("5cd553c37924bb85b3f4893a") }, valueToUpdate)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the documents once again −
> db.updateByVariableDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd553c37924bb85b3f4893a"),
   "StudentSubjects" : [
      "MySQL",
      "MongoDB",
      "SQL Server",
      "PL/SQL"
   ]
}
How are files extracted from a tar file using Python?

You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.
import tarfile
my_tar = tarfile.open('my_tar.tar.gz')
my_tar.extractall('./my_folder') # specify which folder to extract to
my_tar.close()
This will extract the my_tar.tar.gz file's contents to my_folder.
You can also extract individual files from the tar using extract(filename, path).
import tarfile
my_tar = tarfile.open('my_tar.tar.gz')
my_tar.extract('hello.txt','./my_folder')
my_tar.close()
wxPython TreeCtrl - GeeksforGeeks

08 Jul, 2020
In this article we are going to learn about and TreeCtrl and how can we add TreeCtrl to our window. A tree control presents information as a hierarchy, with items that may be expanded to show further items. Items in a tree control are referenced by wx.TreeItemId handles, which may be tested for validity by calling wx.TreeItemId.IsOk .
We will use TreeCtrl() constructor to create TreeCtrl.
Syntax: wx.TreeCtrl.TreeCtrl(parent, id=ID_ANY, pos=DefaultPosition, size=DefaultSize, style=TR_DEFAULT_STYLE, validator=DefaultValidator, name=TreeCtrlNameStr)
Parameters
Code Example:
import wx  class MainFrame(wx.Frame):      def __init__(self):        wx.Frame.__init__(self, parent = None, title ='TreeCtrl Demo')          # tree control        self.tree = wx.TreeCtrl(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize)          # add root to tree        self.root = self.tree.AddRoot('Root ')        # add item to root        self.tree.AppendItem(self.root, 'Child')        # expand tree        self.tree.Expand(self.root)          # show frame        self.Show()    if __name__ == '__main__':    app = wx.App(redirect = False)    frame = MainFrame()    app.MainLoop()
Output Window:
Python wxPython-TreeCtrl
Python-gui
Python-wxPython
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to Install iPython on MacOS? - GeeksforGeeks

21 Sep, 2021
In this article, we will learn how to install iPython in Python on MacOS.
IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.
Follow the below steps to install the iPython package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install iPython using pip3.
pip3 install ipython 
Follow the below steps to install iPython package on macOS using the setup.py file:
Step 1: Download the latest source package of iPython for python3 from here.
curl https://files.pythonhosted.org/packages/46/80/3942535e9c1025d4b379c447a0606bfbe140b25dc331d34910cf2f5e76c0/ipython-7.27.0.tar.gz > ipython.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf ipython.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd ipython-7.27.0
python3 setup.py install
Enter ipython in the terminal to verify if the installation has been done properly:
ipython
If there is any error then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
Ruby | Enumerable find() function - GeeksforGeeks

05 Dec, 2019
The find() of enumerable is an inbuilt method in Ruby returns the first element which satisfies the given condition in the block. If there is no block, then it returns the enumerator itself.
Syntax: block.find { |obj| block }
Parameters: The function takes the block according to which the first which satisfies is to be returned.
Return Value: It returns the first element which satisfies the block or the enumerator instead.
Example 1:
# Ruby program for find method in Enumerable  # Initializeenu = (1..50)  # returns first element enu.find { |el|  el % 2 == 0 && el % 9 == 0}
Output:
18

Example 2:
# Ruby program for find method in Enumerable  # Initializeenu = (1..50)  # returns enumeratorenu.find
Output:
Enumerator: 1..50:find

Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array collect() operation
Ruby Integer odd? function with example
Ruby | Enumerator each_with_index function
Method Overloading In Ruby
Ruby on Rails Introduction
Ruby | Array class last() function
Ruby | Numeric abs() function
Ruby | Array zip() function
Ruby | Symbol Class
Ruby | reverse! function
Ruby | Hash delete() function - GeeksforGeeks

07 Jan, 2020
delete() is an Hash class method which deletes the key-value pair and returns the value from hash whose key is equal to key.
Syntax: Hash.delete()
Parameter: Hash array
Return: value from hash whose key is equal to deleted key.
Example #1:
# Ruby code for delete() method  # declaring Hash valuea = { "a" => 100, "b" => 200 }  # declaring Hash valueb = {"a" => 100}    puts "delete   a : #{a.delete("a") }\n\n"  puts "delete   b : #{b.delete("a") }\n\n"
Output :
delete   a : 100

delete   b : 100


Example #2:
# Ruby code for delete  () method  # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200}  puts "delete   c : #{c.delete("b") }\n\n"  puts "delete   c : #{c.delete("xy"){ |el| "#{el} not found" } }\n\n"
Output :
delete   c : 200

delete   c : xy not found


Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | push() function
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Python | Concatenate two lists element-wise - GeeksforGeeks

28 Jan, 2019
Sometimes we come across this type of problem in which we require to leave each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + zip()List comprehension does the task of concatenating the similar index elements. The task of zip function is concatenating the resultant string into a single list and return list.
# Python3 code to demonstrate # interlist element concatenation# using list comprehension + zip()  # initializing lists  test_list1 = ["Geeksfor", "i", "be"]test_list2 = ['Geeks', 's', 'st']  # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # using list comprehension + zip()# interlist element concatenationres = [i + j for i, j in zip(test_list1, test_list2)]  # printing result print ("The list after element concatenation is : " +  str(res))
The original list 1 is : ['Geeksfor', 'i', 'be']
The original list 2 is : ['Geeks', 's', 'st']
The list after element concatenation is : ['GeeksforGeeks', 'is', 'best']

 Method #2 : Using map() + lambda + zip()The task of mapping each index element with each other is performed by map function in this method and the functionality of addition is performed by lambda function. This method works only in Python2.
# Python code to demonstrate # interlist element concatenation# using map() + lambda + zip()  # initializing lists  test_list1 = ["Geeksfor", "i", "be"]test_list2 = ['Geeks', 's', 'st']  # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # using map() + lambda + zip()# interlist element concatenationres = list(map(lambda(i, j): i + j, zip(test_list1, test_list2)))  # printing result print ("The list after element concatenation is : " +  str(res))
The original list 1 is : ['Geeksfor', 'i', 'be']
The original list 2 is : ['Geeks', 's', 'st']
The list after element concatenation is : ['GeeksforGeeks', 'is', 'best']

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
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 iterate over OrderedDict in Python? - GeeksforGeeks

24 Jan, 2021
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. 
Explanation: 
Input : original_dict = { ‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4 }
Output: a 1 b 2 c 3 d 4
Input: original_dict = {‘sayantan’:9, ‘sanjoy’:7, ‘suresh’:5, ‘rony’:2}
Output: sayantan 9 sanjoy 7 suresh 5 rony 2
Steps to perform iteration through Ordereddict in python : 
Import the ordereddict from collection in python.
Take the input of the ordereddict.
Iterate through the ordereddict in either of the two approaches given below:
Approach #1
Iterating through the ordereddict and printing the value.
Python3
# Python code to implement iteration# over the ordereddict  # import required modulesfrom collections import OrderedDict  # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})  # iterating over the ordereddictfor key, value in od.items():    print(key, value)
Output : 
a 1
b 2
c 3
d 4
The above code can also be written as – 
Python3
# Python code to implement iteration# over the ordereddict  # import required modulesfrom collections import OrderedDict  # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})  # iterating over the ordereddictfor item in od.items():    print(*item)
Output : 
a 1
b 2
c 3
d 4
Approach #2
Iterating through the enumerate objects and printing the value. The enumerate() method is a method in which it adds a counter to the iterable object and returns the value in the form of an enumerate object. 
Python3
# Python code to implement iteration# over the ordereddict  # import required modulesfrom collections import OrderedDict  # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})  # iterating through the enumerate objectsfor i, (key, value) in enumerate(od.items()):    print(key, value)
Output:
a 1
b 2
c 3
d 4
Picked
Python collections-module
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 | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Convert a Character to the String in C# - GeeksforGeeks

26 May, 2020
Given a character, the task is to character to the string in C#.
Examples:
Input :  X = 'a'
Output : string S = "a"

Input :  X = 'A'
Output : string S = "A"

Approach: The idea is to use ToString() method, the argument is the character and it returns string converting Unicode character to the string.
// convert the character x
// to string s
public string ToString(IFormatProvider provider);

C#
// C# program to character to the stringusing System;  public class GFG{          static string getString(char x)     {        // Char.ToString() is a System.Char         // struct method which is used         // to convert the value of this        // instance to its equivalent        // string representation        string str = x.ToString();                  return str;    }        static void Main(string[] args)    {        char chr = 'A';        Console.WriteLine("Type of "+ chr +" : " + chr.GetType());                  string str = getString(chr);        Console.WriteLine("Type of "+ str +" : " + str.GetType());      }}
Output:
Type of A : System.Char
Type of A : System.String

CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
Explain JSON format in PowerShell.

Javascript Object Notation (JSON) is the light-weight structure which is easy to read by human and simple to parse and understand by machine. Although the name contains the Javascript, both Javascript and JSON are different and they have syntax and structure is different as well.
You can get more information about JSON
https://www.json.org/json-en.html
Its basic structure is Key-Value pair but both are separated by a colon ‘:’. It has an almost similar structure as a hashtable, PSCustomObjecct. For example,
{
   "Name": "Albert Don"
}
If you have multiple Key-Value pairs, you can separate them with a comma. For example,
{
   "Name": "Albert Don",
   "City": "New York",
   "SSID": 17728839
}
Save the above file with the extension .json. We will first use the ConvertFrom-Json command to get the output in the table format. There is another command to convert the file/output into JSON using ConvertTo-Json command.
PS E:\scripts\Powershell> Get-Content .\test.json | ConvertFrom-Json
Name          City       SSID
----          ----       ----
Albert Don    New York 17728839
If you have more than one set of Key-Value pairs then you need to declare them inside array Syntax - [] and need to separate each set with the comma (,).
[
   {
      "Name": "Albert Don",
      "City": "New York",
      "SSID": 17728839
   },
   {
      "Name":"John Carter",
      "City":"Ohio",
      "SSID":224544
   },
   {
      "Name":"Milly Lucas",
      "City":"Netherlands",
      "SSID":44903
   }
]
PS E:\scripts\Powershell> Get-Content .\test.json | ConvertFrom-Json
Name       City       SSID
----       ----       ----
Albert Don New York 17728839
John Carter Ohio 224544
Milly Lucas Netherlands 44903
You can convert the output table to the Json format using Convertto-Json cmdlet. See the example below.
Get-Service | Select Name, DisplayName, Status,StartType | Select –First 3
| ConvertTo-Json
PS E:\scripts\Powershell> Get-
Service | Select Name, DisplayName, Status,StartType | Select -
First 3 | ConvertTo-Json
[
   {
      "Name": "AarSvc_69f5c",
      "DisplayName": "Agent Activation Runtime_69f5c",
      "Status": 1,
      "StartType": 3
   },
   {
      "Name": "AdobeARMservice",
      "DisplayName": "Adobe Acrobat Update Service",
      "Status": 4,
      "StartType": 2
   },
   {
      "Name": "AdobeFlashPlayerUpdateSvc",
      "DisplayName": "Adobe Flash Player Update Service",
      "Status": 1,
      "StartType": 3
   }
]
In the above example, individual services are split into a set of arrays.
Java Program to replace one specific character with another

Use the replace() method to replace a specific character with another. Let’s say the following is our string and here we are replacing a whitespace with a $ character.
String str1 = "Orange is the new Black!";
Now, use the replace() method to replace a character with $
str1.replace(' ', '$');
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str1 = "Orange is the new Black!";
      System.out.println("String: "+str1);
      String str2 = str1.replace(' ', '$');
      System.out.println("Updated string: "+str2);
   }
}
String: Orange is the new Black!
Updated string: Orange$is$the$new$Black!