code-rag-bench/online-tutorials huggingface dataset:
Output of C++ Program | Set 14

28 Sep, 2018
Predict the output of following C++ program.
Difficulty Level: Rookie
Question 1
#include <iostream>using namespace std;  class A{    int id;public:    A (int i) { id = i; }    void print () { cout << id << endl; }};  int main(){    A a[2];    a[0].print();    a[1].print();    return 0;}
There is a compilation error in line “A a[2]”. There is no default constructor in class A. When we write our own parameterzied constructor or copy constructor, compiler doesn’t create the default constructor (See this Gfact). We can fix the error, either by creating a default constructor in class A, or by using the following syntax to initialize array member using parameterzied constructor.
 // Initialize a[0] with value 10 and a[1] with 20 
 A a[2] = { A(10),  A(20) } 
Question 2
#include <iostream>using namespace std;  class A{    int id;    static int count;public:    A()    {        count++;        id = count;        cout << "constructor called " << id << endl;    }    ~A()    {        cout << "destructor called " << id << endl;    }};  int A::count = 0;  int main(){    A a[2];    return 0;}
Output:
constructor called 1
constructor called 2
destructor called 2
destructor called 1

In the above program, object a[0] is created first, but the object a[1] is destroyed first. Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object. For example, consider the following code snippet.
A a;
B b(a);
In the above code, the object ‘b’ (which is created after ‘a’), may use some members of ‘a’ internally. So destruction of ‘a’ before ‘b’ may create problems. Therefore, object ‘b’ must be destroyed before ‘a’.
Question 3
#include <iostream>using namespace std;  class A{   int aid;public:   A(int x)   { aid = x; }   void print()   { cout << "A::aid = " <<aid; }};  class B{    int bid;public:    static A a;    B (int i) { bid = i; }};  int main(){  B b(10);  b.a.print();  return 0;}
Compiler Error: undefined reference to `B::a’The class B has a static member ‘a’. Since member ‘a’ is static, it must be defined outside the class. Class A doesn’t have Default constructor, so we must pass a value in definition also. Adding a line “A B::a(10);” will make the program work.
The following program works fine and produces the output as “A::aid = 10”
#include <iostream>using namespace std;  class A{   int aid;public:   A(int x)   { aid = x; }   void print()   { cout << "A::aid = " <<aid; }};  class B{    int bid;public:    static A a;    B (int i) { bid = i; }};  A B::a(10);  int main(){  B b(10);  b.a.print();  return 0;}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
CPP-Output
C++
Program Output
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB query to find matching documents given an array with values?

For specific documents, use MongoDB $in. Let us create a collection with documents −
> db.demo511.insertOne({"ListOfProject":["Library Management System","Hospital
Management System"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88473a987b6e0e9d18f585")
}
> db.demo511.insertOne({"ListOfProject":["Online Web Tracking","Library Management
System"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884751987b6e0e9d18f586")
}
> db.demo511.insertOne({"ListOfProject":["Online Shopping Cart","Hospital Management
System"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884776987b6e0e9d18f587")
}
Display all documents from a collection with the help of find() method −
> db.demo511.find();
This will produce the following output −
{ "_id" : ObjectId("5e88473a987b6e0e9d18f585"), "ListOfProject" : [ "Library Management
System", "Hospital Management System" ] }
{ "_id" : ObjectId("5e884751987b6e0e9d18f586"), "ListOfProject" : [ "Online Web Tracking",
"Library Management System" ] }
{ "_id" : ObjectId("5e884776987b6e0e9d18f587"), "ListOfProject" : [ "Online Shopping Cart",
"Hospital Management System" ] }
Following is the query to finding matching documents −
> db.demo511.find({ "ListOfProject":{$in:["Hospital Management System","Online Shopping Cart"]}});
This will produce the following output −
{ "_id" : ObjectId("5e88473a987b6e0e9d18f585"), "ListOfProject" : [ "Library Management
System", "Hospital Management System" ] }
{ "_id" : ObjectId("5e884776987b6e0e9d18f587"), "ListOfProject" : [ "Online Shopping Cart",
"Hospital Management System" ] }
SQL | CREATE DOMAIN

07 Sep, 2018
Used in : Postgre sqlCREATE DOMAIN creates a new domain. A domain is essentially a data type with optional constraints (restrictions on the allowed set of values). The user who defines a domain becomes its owner.
Domains are useful for abstracting common constraints on fields into a single location for maintenance. For example, several tables might contain email address columns, all requiring the same CHECK constraint to verify the address syntax. Define a domain rather than setting up each table’s constraint individually.
Examples:
CREATE DOMAIN CPI_DATA AS REAL CHECK
(value >= 0 AND value <= 10);

Now CPI_DATA domain is create so, we can use this domain anywhere in any table of database as below :
CREATE TABLE student(
sid char(9) PRIMARY KEY,
name varchar(30),
cpi CPI_DATA
);

Every time cpi_data will check the constraint, when you add data in student table.
Example 1 :
Insert into student values (201501408,Raj,7.5); 
This will not violate the property of cpi. 

Example 2 :
Insert into student values (201501188,Dhaval,12); 
ERROR. This will violate the property of cpi. 

This article is contributed by Dhavalkumar Prajapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Umesh Bhat
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
Java Program to get the prime numbers with BigInteger type

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller
natural numbers. Here, we have the BigInteger type, which has operations for modular arithmetic, GCD
calculation, primality testing, prime generation, etc.
At first, we have set the value to 0 and then considered a while loop. Since 0 and 1 aren’t prime
numbers, we will be generating prime numbers after that:
int val = 0;
System.out.println("Prime Numbers...");
while (true) {
   // conditions
}
Under while, we have set the following two condition. On increment, when the value of val become
greater than 1 i.e.2, it goes under the second if condition. Inside that, we have used the isProbablePrime() method to generate prime numbers:
while (true) {
   if (val > 50) {
      break;
   }
   if (val > 1) {
      if (new BigInteger(val+"").isProbablePrime(val / 2)) {
         System.out.println(val);
      }
   }
}
import java.math.BigInteger;
public class Demo {
   public static void main(String[] args) {
      int val = 0;
      System.out.println("Prime Numbers...");
      while (true) {
         if (val > 50) {
            break;
         }
         if (val > 1) {
            if (new BigInteger(val+"").isProbablePrime(val / 2)) {
               System.out.println(val);
            }
         }
         val++;
      }
   }
}
Prime Numbers...
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
C++ Program to Implement String Matching Using Vectors

This is another string matching method. In this approach, we are searching for a substring using vectors.
In C++ we can create vectors easily using the standard library. We are taking the main string and the string that will be searched as a vector, then searching it into the main string. When one match is found the function returns the address, and removes it from the main string. So in the next iteration, it starts from location 0 and searches again.
For multiple occurrences, we are using loops and repeatedly searching for the match, and return the position.
Input: Main String: “ABAAABCDBBABCDDEBCABC”, Pattern “ABC”
Output: Pattern found at position: 4
Pattern found at position: 10
Pattern found at position: 18
Input − The main text and the substring.
Output − location where patterns are found
Begin
   p := starting point of the main string
   while r is not at the end of substr and p is not at the end of main, do
      r := starting of substr
      while item at position p & r are not same, and p in main, do
         p := p + 1
         i := i + 1
      done
      q := p
      while item at pos p & r are same, and r in substr and p in main, do
         p := p + 1
         i := i + 1
         r := r + 1
      done
      if r exceeds the substr, then
         delete first occurrence of substr from main
         return the position where substr is found

      if p exceeds main string, then
         return 0
         q := q + 1
         p := q
   done
End
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void take_string(vector<char> &string){
   char c;
   while(true){
      c = getchar();
      if(c == '\n'){
         break;
      }
      string.push_back(c);
   }
}

void display(vector<char> string){
   for(int i = 0; i<string.size(); i++){
      cout << string[i];
   }
}

int match_string(vector<char>& main, vector<char> substr){
   vector<char>::iterator p,q, r;
   int i = 0;

   p = main.begin();

   while (r <= substr.end() && p <= main.end()){
      r = substr.begin();
      while (*p != *r && p < main.end()){
         p++;
         i++;
      }
      q = p;

      while (*p == *r && r <= substr.end() && p<=main.end()){
         p++;
         i++;
         r++;
      }

      if (r >= substr.end()){
         main.erase(main.begin(), q + 1);
         return (i - substr.size() + 1);
      }

      if (p >= main.end())
         return 0;
         p = ++q;
   }
}
Enter main String: C++ is programming language. It is object oriented language
Enter substring to find: language

Match found at Position = 20
Match found at Position = 52
How to Get Market Data from the NYSE in Less than 3 Lines (Python). | by Sajid Lhessani | Towards Data Science

Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
In this article, you will learn to get the stock market data such as price, volume and fundamental data using Python packages. (In less than 3 lines of code)
First of all, before to start, you will need to have installed a Python 3 version and the following packages:
Pandas
Pandas_datareader
DateTime
If any of these packages are not already installed, you can use the pip command as shown below.
pip install pandas-datareaderpip install DateTime
Once you have ensured that the following packages are installed, we can start.
If you already have experience with Python, you can jump to step III. Step I and II will consist of importing data and converting to dateformat.
The first step will consist of importing the necessary packages.
You will start by importing your packages previously installed by using the following lines of code:
From pandas_datareader library, I am going to import data and wb module only.
Once we are set up let’s pursue to the next step.
Now that libraries are imported, the second step will consist of converting your dates in a DateTime format.
This step is not mandatory if you already have converted your dates previously. However, if you did not, I recommend you to use the lines of codes below:
You will notice, that concerning the end date, I intentionally used my end date as today. It is one of the advantages of the DateTime module. It will continuously, keep your Jupyter notebook with the latest date.
For instance, if you re-run your Kernel in 3 months, your data frame and graphs will be updated with the latest market data.
Once you have set-up your start and end date, we can now import markets data.
Now that we converted the start and end date in the right format. We are going to use Tesla as an example to set up our import.
Pandas DataReader API will need 4 mandatory arguments in this order:
Tickers
Specific API (Yahoo, AlphaVantage, sooq ...)
Start date
End date
And potentially an API key
For our case, the ticker will be TSLA, the API gonna be Yahoo and the start and end date have been defined above (04 Feb 2020 until today). As a quick reminder, Tesla ticker is TSLA.
So let’s try this combination by using the lines of code below:
And let’s check the output ...
Boom !!!
You got your market data with the volume, highest price, lowest price, open price and the Adj close.
I hope you enjoyed this article if you have any question or using a different way, comment below.
Sajid Lhessani
(1) Learn algorithmic trading in one day:
Lua - repeat...until Loop

Unlike the for and while loops, which test the loop condition at the top of the loop, the repeat...until loop in Lua programming language checks its condition at the bottom of the loop.
A repeat...until loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
The syntax of a repeat...until loop in Lua programming language is as follows −
repeat
   statement(s)
until( condition )

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute(s) once before the condition is tested.
If the condition is false, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the  given condition becomes true.
--[ local variable definition --]
a = 10

--[ repeat loop execution --]
repeat
   print("value of a:", a)
   a = a + 1
until( a > 15 )
When you build and execute the above program, it produces the following result −
value of a:	10
value of a:	11
value of a:	12
value of a:	13
value of a:	14
value of a:	15


    12 Lectures 
     2 hours 

 Manish Gupta

    80 Lectures 
     3 hours 

 Sanjeev Mittal

    54 Lectures 
     3.5 hours 

 Mehmet GOKTEPE
 Print
 Add Notes
 Bookmark this page
Check if list is strictly increasing in Python

Given a list, we may need to check for the sequence of its elements. In this article we will find out if the elements present in the list are in a strictly increasing order. Below programs achieve that objective.
In this approach we first slice each element compare its value to the next element that is sliced. If all such comparisons hold true then we conclude the list is strictly in increasing order.
 Live Demo
listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
# Apply all and range
if (all(i < j for i, j in zip(listA, listA[1:]))):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
# Checking again
listB = [11,23,21,51,67]
print("Given list : ",listB)
# Apply all and range
if (all(i < j for i, j in zip(listB, listB[1:]))):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
Running the above code gives us the following result −
Given list : [11, 23, 42, 51, 67]
Yes, List is sorted.
Given list : [11, 23, 21, 51, 67]
No, List is not sorted.
The makes an iterator that computes the function using arguments obtained from the iterable. We zip the list of elements after slicing them one by one and then taking through the less than equal to operator. Please note we have used strings instead of numbers in the below exmaples.
 Live Demo
import operator
import itertools

listA = ['Mon','Tue','Sun']
#Given list
print("Given list : ",listA)
# Apply all and range
if all(itertools.starmap(operator.le,
   zip(listA, listA[1:]))):
print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
# Checking again
listB = ['Mon','Sun','Tue']
print("Given list : ",listB)
# Apply all and range
if all(itertools.starmap(operator.le,
   zip(listB, listB[1:]))):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Sun']
No, List is not sorted.
Given list : ['Mon', 'Sun', 'Tue']
Yes, List is sorted.
jQuery | first() with Examples - GeeksforGeeks

12 Jan, 2022
The first() is an inbuilt function in jQuery which is used to select the first element from the specified elements. Syntax:  
$(selector).first()
Here selector is the main class of all the elements.Parameters: It does not accept any parameter.Return value: It returns the first element out of the selected elements.jQuery code to show the working of this function: Code #1:  
html
<html> <head>    <script src="https://ajax.googleapis.com/ajax/libs/               jquery/3.3.1/jquery.min.js"></script>    <script>        $(document).ready(function() {            $("div").first().css("background-color",                                  "lightgreen");        });    </script></head> <body>     <h1>Welcome to GeeksforGeeks !!!</h1>    <div style="border: 1px solid green;">        <p>This is the first statement.</p>    </div>    <br>     <div style="border: 1px solid green;">        <p>This is the second statement.</p>    </div>    <br>     <div style="border: 1px solid green;">        <p>This is the third statement.</p>    </div>    <br></body> </html>
In the above code, the background-color of the first “div” element get changed. Output:  
Here, you can also choose by selecting “id” or “class” of the selected element. Code #2:  
html
<html> <head>    <script src="https://ajax.googleapis.com/ajax/libs/                 jquery/3.3.1/jquery.min.js"></script>    <script>        $(document).ready(function() {            $(".main").first().css("background-color",                                     "lightgreen");        });    </script></head> <body>     <h1>Welcome to GeeksforGeeks !!!</h1>    <div style="border: 1px solid green;">        <p>This is the first statement.</p>    </div>    <br>     <div class="main" style="border: 1px solid green;">        <p>This is second statement.</p>    </div>    <br>     <div class="main" style="border: 1px solid green;">        <p>This is the third statement.</p>    </div>    <br></body> </html>
In the above code the elements with first “main” class get highlighted. Output:  
 
adnanirshad158
jQuery-Traversing
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 calculate the number of days between two dates in javascript?
File uploading in React.js
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
Difference between sizeof(int *) and sizeof(int) in C/C++

19 Oct, 2020
sizeof() is commonly used operator in the C or C++. It is a compile-time unary operator that can be used to compute the size of its operand. The result of sizeof() is of unsigned integral type which is usually denoted by size_t. This operator can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as structure, union etc.
int means a variable whose datatype is integer.sizeof(int) returns the number of bytes used to store an integer.
int* means a pointer to a variable whose datatype is integer.sizeof(int*) returns the number of bytes used to store a pointer.
Since the sizeof operator returns the size of the datatype or the parameter we pass to it. So, the value it should return after passing a variable of (int *) to it:
Since int* points to an address location as it is a pointer to a variable, So, the sizeof(int*) simply implies the value of the memory location on the machine, and, memory Locations themselves are 4-byte to 8-byte integer values.
On a 32-bit Machine, sizeof(int*) will return a value 4 because the address value of memory location on a 32-bit machine is 4-byte integers.
Similarly, on a 64-bit machine it will return a value of 8 as on a 64-bit machine the address of a memory location are 8-byte integers.
Now, the value it should return after passing a variable of (int) to it:
Since int in an integer type variable. So, the sizeof(int) simply implies the value of size of an integer.
Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.
Below is the illustration of sizeof operator on 64-bit machine:
C
C++
// C program to illustrate the// sizeof operator#include <stdio.h>  // Driver codeint main(){    // Print the sizeof integer    printf("Size of (int) = %lu"           " bytes\n",           sizeof(int));      // Print the size of (int*)    printf("Size of (int*) = %lu"           " bytes\n",           sizeof(int*));      return 0;}
// C program to illustrate the// sizeof operator#include "bits/stdc++.h"using namespace std;  // Driver Codeint main(){    // Print the sizeof integer    cout << "Size of (int) = "         << sizeof(int) << " bytes\n";      // Print the size of (int*)    cout << "Size of (int *) = "         << sizeof(int*) << " bytes\n";      return 0;}
Size of (int) = 4 bytes
Size of (int*) = 8 bytes

C Basics
C-Operators
cpp-operator
Articles
C Language
C++
C++ Programs
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity
SQL Interview Questions
Understanding "extern" keyword in C
SQL | Views
std::sort() in C++ STL
Bitwise Operators in C/C++
Arrays in C/C++
Substring in C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Python Tweepy – Getting the ID of a user

18 Jun, 2020
In this article we will see how we can get the ID of a user. ID is the unique identification marker of the twitter account. ID is given to the user by Twitter, the user can not select or change their own ID.
In order to get the ID we have to do the following :
Identify the user screen name of the profile.Get the User object of the profile using the get_user() method and the user name.From this object, fetch the id or id_str attribute present in it.
Identify the user screen name of the profile.
Get the User object of the profile using the get_user() method and the user name.
From this object, fetch the id or id_str attribute present in it.
Example 1: Consider the following profile :The screen name of the above mentioned profile is geeksforgeeks.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the screen name of the userscreen_name = "geeksforgeeks"  # fetching the useruser = api.get_user(screen_name)  # fetching the IDID = user.id_str  print("The ID of the user is : " + ID)
Output :
The ID of the user is : 57741058

Example 2: Consider the following profile :The screen name of the above mentioned profile is PracticeGfG.
# the screen name of the userscreen_name = "PracticeGfG"  # fetching the useruser = api.get_user(screen_name)  # fetching the IDID = user.id_str  print("The ID of the user is : " + ID)
Output :
The ID of the user is : 4802800777

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Apache Pig - Limit Operator

The LIMIT operator is used to get a limited number of tuples from a relation.
Given below is the syntax of the LIMIT operator.
grunt> Result = LIMIT Relation_name required number of tuples;

Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.
student_details.txt
001,Rajiv,Reddy,21,9848022337,Hyderabad
002,siddarth,Battacharya,22,9848022338,Kolkata
003,Rajesh,Khanna,22,9848022339,Delhi 
004,Preethi,Agarwal,21,9848022330,Pune 
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar 
006,Archana,Mishra,23,9848022335,Chennai 
007,Komal,Nayak,24,9848022334,trivendram 
008,Bharathi,Nambiayar,24,9848022333,Chennai

And we have loaded this file into Pig with the relation name student_details as shown below.
grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')
   as (id:int, firstname:chararray, lastname:chararray,age:int, phone:chararray, city:chararray);
Now, let’s sort the relation in descending order based on the age of the student and store it into another relation named limit_data using the ORDER BY operator as shown below.
grunt> limit_data = LIMIT student_details 4; 
Verify the relation limit_data using the DUMP operator as shown below.
grunt> Dump limit_data; 
It will produce the following output, displaying the contents of the relation limit_data as follows.
Output of Python Programs | (Dictionary)

04 Oct, 2018
Prerequisite: DictionaryNote: Output of all these programs is tested on Python31.What is the output of the following of code?
a = {i: i * i for i in range(6)}print (a)
Options:a) Dictionary comprehension doesn’t existb) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Ans. (d)
Explanation: The above piece of code written in curly braces generate the whole Dictionary.2.What is the output of the following of code?
a ={}a.fromkeys(['a', 'b', 'c', 'd'], 98)print (a)
Options:a) Syntax errorb) {‘a’:98, ‘b’:98, ‘c’:98, ‘d’:98}c) {}d) {‘a’:None, ‘b’:None, ‘c’:None.’d’:None}
Ans. (c)

Explanation:fromkeys() create a new dictionary with keys from list given to it as an argument and set values of the key, the default value given in it as an argument.Input:
a ={}dict = a.fromkeys(['a', 'b', 'c', 'd'], 98)print (a)print (dict)
Output:
{}
{'d': 98, 'b': 98, 'a': 98, 'c': 98}

3.What is the output of the following of code?
dict ={}print (all(dict))
Options:a) { }b) Falsec) Trued) An exception is thrown
Ans.(c)

Explanation:The all() method returns:
True – If all elements in an iterable are true ot iterable is empty.
False – If any element in an iterable is false.
Input:
a = {}b = a.fromkeys([1, False, 3], 'True')print (all(a))print (all(b))
Output:
True
False

4.What is the output of the following of code?
a = {'geeks' : 1, 'gfg' : 2}b = {'geeks' : 2, 'gfg' : 1}print (a == b) 
a) Trueb) Falsec) Errord) None
Ans. (b)

Explanation:If two dictionary are same it returns true, otherwise it returns false.
5.Which of these about a dictionary is false?a) The values of a dictionary can be accessed using keysb) The keys of a dictionary can be accessed using valuesc) Dictionaries may or may not be orderedd) None of the above
Ans.(b)

Explanation: The values of a dictionary can be accessed using keys but the keys of a dictionary can’t be accessed using values.
python-dict
Python-Output
Program Output
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Output of C Programs | Set 2
Different ways to copy a string in C/C++
Output of C Programs | Set 3
Output of C++ Program | Set 1
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
HTML <a> target Attribute

The target attribute of the <a> element is used to set where the linked document will open. You can set the document to open in a new window, same frame, parent frame, etc.
Following is the syntax −
<a target="_blank|_self|_parent|_top| frame">
Here, _blank is used to open the linked document in new window or tab, _self opens the linked document in the same frame as it was clicked, _parent opens the document in the parent frame, _top opens the linked document in the entire body of the window, frame opens the linked document in a named frame.
Let us now see an example to implement target attribute in <a> element −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Learning is Fun</h2>
   <p><strong>Note −</strong> The links will open in new window.</p>
   <p><a href="https −//www.tutorialspoint.com/tutorialslibrary.htm" target="_blank">Tutorials Library</a><br>
   <a href="https −//www.tutorialspoint.com/programming_examples/" target="_blank">Codes</a><br>
   <a href="https −//www.tutorialspoint.com/computer_glossary.htm" target="_blank">Computer Glossary</a>
<br>
</body>
</html>
This will produce the following output. The below links will open in new window −
In the above example, we have set the target in the target attribute −
<a href="https −//www.tutorialspoint.com/tutorialslibrary.htm" target="_blank"> Tutorials Library </a>
The attribute set above has value _blank, which opens the link in the href attribute in a new window −
target="_blank"
Python - HTTP Server

Python standard library comes with a in-built webserver which can be invoked for simple web client server communication. The port number can be assigned programmatically
and the web server is accessed through this port. Though it is not a full featured web server which can parse many kinds of file, it can parse simple static html files
and serve them by responding them with required response codes. 
The below program starts a simple web server and opens it up at port 8001. The successful running of the server is indicated by the response code of 200 as shown in the program output.
import SimpleHTTPServer
import SocketServer

PORT = 8001

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
When we run the above program, we get the following output −
serving at port 8001
127.0.0.1 - - [14/Jun/2018 08:34:22] "GET / HTTP/1.1" 200 -

If we decide to make the python server as a local host serving only the local host, then we can use the following programm to do that.
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler


HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
When we run the above program, we get the following output −
Serving HTTP on 127.0.0.1 port 8000 ...
C# program to check if a string contains any special character

To check if a string contains any special character, you need to use the following method −
Char.IsLetterOrDigit
Use it inside for loop and check or the string that has special characters.
Let us say our string is −
string str = "Amit$#%";
Now convert the string into character array −
str.ToCharArray();
With that, use a for loop and to check for each character using the isLetterOrDigit() method.
Let us see the complete code.
Live Demo
using System;
namespace Demo {
   class myApplication {
      static void Main(string[] args) {
         string str = "Amit$#%";
         char[] one = str.ToCharArray();
         char[] two = new char[one.Length];
         int c = 0;
         for (int i = 0; i < one.Length; i++) {
            if (!Char.IsLetterOrDigit(one[i])) {
               two[c] = one[i];
               c++;
            }
         }
         Array.Resize(ref two, c);
         Console.WriteLine("Following are the special characters:");
         foreach(var items in two) {
            Console.WriteLine(items);
         }
         Console.ReadLine();
      }
   }
}
Following are the special characters:
$
#
%
GATE CS 1996 - GeeksforGeeks

22 Nov, 2021
Case 1: Exactly one dice has 6 facing up and other dice can have any number from 1,2,3,4,5 facing up. There will be 5*2=10 such occurrences.
Case 2: Both of the dices having 6 coming up. Only one possible case exists for the same.
 f'(x0) = (f(x0+h) - f(x0))/h

f''(x0) = (f'(x0) - f'(x0-h))/h

         =[ ((f(x0+h) - f(x0))/h )- (( f'(x0) - f'(x0-h))/h)]/h

         =[ f(x0+h)-2f(x0)+f(x0-h)] /h^2

Following are the possibilities for a system of linear equations:
(i)  If matrix A and augmented matrix [AB]  have same  rank, then the system has solutions otherwise there is no solution.
(ii) If matrix A and augmented matrix [AB]  have same  rank which is equal to the no. of variables, then the system has unique  solutions and if B is zero vector then the system have only a trivial solution. 
(iii) If matrix A and augmented matrix [AB]  have same  rank which is less than the number of variables, then the system has infinite solutions. 
Therefore, option (C) is false because if m=n and B is non-zero vector, then it is not necessary that system has a unique solutions , because m is the number of equations ( quantity ) and not the number of linearly independent equations ( quality ).
(00)*(ε+0)
= (00)*.ε+ (00)*.0 
= (00)* + (00)*0 
= 0* 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
SDE SHEET - A Complete Guide for SDE Preparation
7 Highest Paying Programming Languages For Freelancers in 2022
DSA Sheet by Love Babbar
How to Create a Shell Script in linux
How To Convert Numpy Array To Tensor?
7 Best React Project Ideas For Beginners in 2022
Java Program to fill an array of characters from user input

For user input, use the Scanner class with System.in. After getting the input, convert it to character array −
char[] a = s.next().toCharArray();
Now, display it until the length of the character array i.e. number of elements input by the user −
for (int i = 0; i < a.length; i++) {
   System.out.println(a[i]);
}
To fill an array of characters from user input, use Scanner class.
import java.util.Scanner;
public class Demo {
   public static void main(String args[]) {
      Scanner s = new Scanner(System.in);
      System.out.println("First add some characters...");
      char[] a = s.next().toCharArray();
      System.out.println("Elements = ");
      for (int i = 0; i < a.length; i++) 
         System.out.println(a[i]);
   }
}
Now, enter some input −
RSTUVWXYZ
After entering, you need to run the program to get the following output −
First add some characters...
Elements entered =
R
S
T
U
V
W
X
Y
Z
Python String partition() Method

19 Aug, 2021
Python String partition() method splits the string at the first occurrence of the separator and returns a tuple containing the part before the separator, separator, and the part after the separator. Here separator is a string that is given as the argument. 
Syntax: 
string.partition(separator)
Parameters: 
The partition() method takes a separator(a string) as the argument that separates the string at its first occurrence.
Returns: 
Returns a tuple that contains the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string. Returns a tuple that contains the string itself and two empty strings if the separator parameter is not found. 
Python3
string = "pawan is a good"  # 'is' separator is foundprint(string.partition('is '))  # 'not' separator is not foundprint(string.partition('bad '))  string = "pawan is a good, isn't it"  # splits at first occurrence of 'is'print(string.partition('is'))
Output: 
('pawan ', 'is ', 'a good')
('pawan is a good', '', '')
('pawan ', 'is', " a good, isn't it")
Python3
string = "geeks is a good"  # 'is' separator is foundprint(string.partition('is '))  # 'not' separator is not foundprint(string.partition('bad '))  string = "geeks is a good, isn't it"  # splits at first occurrence of 'is'print(string.partition('is'))
Output: 
('geeks ', 'is ', 'a good')
('geeks is a good', '', '')
('geeks ', 'is', " a good, isn't it")
nidhi_biet
AmiyaRanjanRout
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Function as a Field in Golang Structure

13 Aug, 2019
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. As we know that in Go language function is also a user-defined type so, you are allowed to create a function field in the Go structure. You can also create a function field in the Go structure using an anonymous function as shown in Example 2.
Syntax:
type function_name func()
type strcut_name struct{
  var_name  function_name
}

Let us discuss this concept with the help of the examples:
Example 1:
// Go program to illustrate the function// as a field in Go structurepackage main  import "fmt"  // Finalsalary of function typetype Finalsalary func(int, int) int  // Creating structuretype Author struct {    name      string    language  string    Marticles int    Pay       int      // Function as a field    salary Finalsalary}  // Main methodfunc main() {      // Initializing the fields    // of the structure    result := Author{        name:      "Sonia",        language:  "Java",        Marticles: 120,        Pay:       500,        salary: func(Ma int, pay int) int {            return Ma * pay        },    }      // Display values    fmt.Println("Author's Name: ", result.name)    fmt.Println("Language: ", result.language)    fmt.Println("Total number of articles published in May: ", result.Marticles)    fmt.Println("Per article pay: ", result.Pay)    fmt.Println("Total salary: ", result.salary(result.Marticles, result.Pay))}
Output:
Author's Name:  Sonia
Language:  Java
Total number of articles published in May:  120
Per article pay:  500
Total salary:  60000

Example 2:
// Go program to illustrate the function// as a field in Go structure// Using anonymous functionpackage main  import "fmt"  // Creating structuretype Author struct {    name      string    language  string    Tarticles int    Particles int    Pending   func(int, int) int}  // Main methodfunc main() {      // Initializing the fields    // of the structure    result := Author{        name:      "Sonia",        language:  "Java",        Tarticles: 340,        Particles: 259,        Pending: func(Ta int, Pa int) int {            return Ta - Pa        },    }      // Display values    fmt.Println("Author's Name: ", result.name)    fmt.Println("Language: ", result.language)    fmt.Println("Total number of articles: ", result.Tarticles)          fmt.Println("Total number of published articles: ",                                      result.Particles)          fmt.Println("Pending articles: ", result.Pending(result.Tarticles,                                                   result.Particles))}
Output:
Author's Name:  Sonia
Language:  Java
Total number of articles:  340
Total number of published articles:  259
Pending articles:  81

Go-Functions
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ipcrm command in Linux with examples

22 May, 2019
ipcrm command in Linux is used to remove some IPC(Inter-Process Communication) resources. It eliminates the IPC objects and their associated data structure form the system. One must be a creator or superuser or the owner of the object in order to remove these objects. There are three types of System V IPC objects i.e. semaphores, shared memory, and message queues.
Note: When all the currently attached processes will remove the object from their virtual address space then only shared memory object can be removed.
Syntax:
ipcrm [options]
or
ipcrm {shm|msg|sem} id...
Options:
-a, –all [shm] [msg] [sem] : Remove all resources. When an option argument is provided, the removal is performed only for the specified resource types.
-M, –shmem-key shmkey : Remove the shared memory segment created with shmkey after the last detach is performed.
-m, –shmem-id shmid : Remove the shared memory segment identified by shmid after the last detach is performed.
-Q, –queue-key msgkey : Remove the message queue created with msgkey.
-q, –queue-id msgid : Remove the message queue identified by msgid.
-S, –semaphore-key semkey : Remove the semaphore created with semkey.
-s, –semaphore-id semid : Remove the semaphore identified by semid.
-V, –version : Display version information and exit.
-h, –help : Display help text and exit.
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Program to print its own name as output

04 Nov, 2019
Ever thought about writing a script which prints its own name when you execute it. It’s pretty simple. You must have noticed programs in which the main function is written like this
int main(int argc, char** argv)
and you must have wondered what these 2 arguments mean.
Well the first one argc is the number of arguments passed in to your program.
The second one argv is the array which holds the names of all the arguments passed into your program.
Along with those arguments there is an extra piece of information stored in the array first cell of that array i.e. argv[0] which is the full path of the file containing the code.
To print the name of the program all we need to do is to slice the filename out of that path.
Implementation
Below is the python implementation of the idea discussed above. Let’s suppose the name of the script is print_my_name.
# Python program to prints it own name upon executionimport sys  def main():    program = sys.argv[0] # argv[0] contains the full path of the file      # rfind() finds the last index of backslash    # since in a file path the filename comes after the last '\'    index = program.rfind("\\") + 1      # slicing the filename out of the file path    program = program[index:]    print("Program Name: % s" % program)  # executes mainif __name__ == "__main__":    main()
Output: print_my_name.py
Note: The output will vary when you run it on GeeksforGeeks online compiler.
This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java program to implement bubble sort

Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large datasets as its average and worst case complexity is of Ο(n2) where n is the number of items.
Live Demo
public class BubbleSort {
   static void bubbleSort(int[] arr) {
      int n = arr.length;
      int temp = 0;

      for(int i = 0; i < n; i++) {
         for(int j=1; j < (n-i); j++) {
            if(arr[j-1] > arr[j]) {
               temp = arr[j-1];
               arr[j-1] = arr[j];
               arr[j] = temp;
            }
         }
      }
   }
   public static void main(String[] args) {
      int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      System.out.println("Array Before Bubble Sort");

      for(int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
      bubbleSort(arr);
      System.out.println("Array After Bubble Sort");

      for(int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
   }
}
Array Before Bubble Sort
2 5 -2 6 -3 8 0 -7 -9 4
Array After Bubble Sort
-9 -7 -3 -2 0 2 4 5 6 8
An element inside another element in JavaScript?

The element inside an element is nothing but for instance a span element inside a div element. Javascript has provided .contains() method to find out whether an element contains another element. This method actually returns true if the condition is satisfied else returns false. 
node.contains(node);
In the following example, a span element is inside a div element. Therefore ".contains()" method has returned true on the execution of the code and displayed the result in the output.
Live Demo
<html>
<body>
<div id="div">
<p>There is a <span id="span"><b>span</b></span> element inside me.</p>
</div>
<p id = "contain"></p>
<script>
   var span = document.getElementById("span");
   var div = document.getElementById("div").contains(span);
   document.getElementById("contain").innerHTML = div;
</script>
</body>
</html>
There is a span element inside of me.

true
The CSS scale() Function

The scale() function in CSS is used to define a transformation that resizes an element on the 2D plane. Set the amount of scaling in each direction as the parameter of the scale() function.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.translate_img {
   transform: translate(100px, 10%);
}
.scale_img {
   transform: scale(1.2);
   background-color: yellow;
}
</style>
</head>
<body>
<h1>Learn</h1>
<img class="translate_img" src=
"https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png"
alt="MongoDB">
<img class="scale_img" src=
"https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png"
alt="MongoDB">
</body>
</html>
Let us now see another example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.translate_img {
   transform: translate(100px, 10%);
}
.scale_img {
   transform: scale(0.3);
}
</style>
</head>
<body>
<h1>Learn</h1>
<img class="translate_img" src=
"https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png"
alt="MongoDB">
<img class="scale_img" src=
"https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png"
alt="MongoDB">
</body>
</html>