code-rag-bench/online-tutorials huggingface dataset:
Find index of an element in a Set in C++ - GeeksforGeeks

01 Jul, 2021
Given a set S consisting of N integers and an element K, the task is to find the index of the element K in the set S. If the element is not present in S, print -1.
Examples:
Input: N = 5, S = {1, 2, 3, 4, 6} K = 6Output: 5Explanation: 6 is the 5th element in S.
Input: N = 5, S = {1, 2, 3, 4, 6}, K = 5Output:  -1  Explanation:  5 is not present in this set so we give output as -1.
Approach: Follow the steps below to solve the problem:
Initialize a variable, say index as 1, to store the index of the required element.
Traverse the set S and perform the following operations: 
If the current element is K, print Index and break out of the loop.
Otherwise, increment Index.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate index// of element in a Setint GetIndex(set<int> S, int K){     // To store the index of K    int Index = 1;     // Traverse the Set    for (auto u : S) {         if (u == K)            return Index;         Index++;    }     // If K is not present    // in the set    return -1;} // Driver Codeint main(){    // Input    set<int> S;    S.insert(1);    S.insert(6);    S.insert(2);    S.insert(3);    S.insert(4);    int K = 6;     cout << GetIndex(S, K) << endl;    return 0;}
5
 
Time Complexity: O(N)Auxiliary Space: O(1) 
trilokjain
cpp-set
STL
C++ Programs
Searching
Searching
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
C program to count a letter repeated in a sentence.

Write a program to count a letter, which is entered by the user at console. How many times that letter is repeated in a sentence need to be printed on screen by using strlen() function.
The logics we used to count a letter are as follows −
Asking the user to enter a sentence at runtime.
printf("Enter a sentence\n");
gets(str);
Asking the user to enter a letter at runtime.
printf("Enter a character to check how many times it is repeating\n");
scanf("%c",&c);
The logic to count the letter in a sentence is as follows −
for(i=0;i<strlen(str);i++){
   if(str[i]==c){
      count++;
   }
}
Finally print the count
Following is the C program to count a letter that is repeated for number of times in a sentence −
 Live Demo
#include<stdio.h>
#include<string.h>
main(){
   int i,count=0;
   char c,str[100];
   printf("Enter a sentence\n");
   gets(str);
   printf("Enter a character to check how many times it is repeating\n");
   scanf("%c",&c);
   for(i=0;i<strlen(str);i++){
      if(str[i]==c){
         count++;
      }
   }
   printf("Letter %c repeated %d times\n",c,count);
}
When the above program is executed, it produces the following output −
Enter a sentence
Here are the C Programming question and answers
Enter a character to check how many times it is repeating
n
Letter n repeated 4 times
C++ Program to Solve Travelling Salesman Problem for Unweighted Graph

Travelling Salesman Problem use to calculate the shortest route to cover all the cities and return back to the origin city. This method is use to find the shortest path to cover all the nodes of a graph.
This is the program to find shortest route of a unweighted graph.
Begin
   Define a variable vr = 4 universally.
   Declare an integer function TSP to implement Travelling salesman Problem.
   Declare a graph grph[][] as a 2D matrix and variable p to the integer datatype.
   Pass them as a parameter.
   Declare variable ver to the vector datatype.
   for (int i = 0; i < vr; i++)
      if (i != p) then
         Call push_back(i) function to store the value of all vertex except source vertex.
         Initialize m_p = INT_MAX to store minimum weight of a graph.
      do
         Declare cur_pth, k to the integer datatype.
            initialize cur_pth = 0.
            initialize k = p.
         for (int i = 0; i < ver.size(); i++)
            cur_pth += grph[k][ver[i]].
            k = ver[i].
         cur_pth += grph[k][p].
         m_p = min(m_p, cur_pth) to update the value of minimum weight.
         while (next_permutation(ver.begin(), ver.end())).
         Return m_p.
   Declare a graph grph[][] as a 2D matrix to the integer datatype.
      Initialize values of grph[][] graph.
   Declare variable p to the integer datatype.
      Initialize p = 0.
   Print “The result is: ”.
   Print the return value of TSP() function.
End.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
#define vr 4
int TSP(int grph[][vr], int p) // implement traveling Salesman Problem. {
   vector<int> ver; //
   for (int i = 0; i < vr; i++)
      if (i != p)
         ver.push_back(i);
         int m_p = INT_MAX; // store minimum weight of a graph
   do {
      int cur_pth = 0;
      int k = p;
      for (int i = 0; i < ver.size(); i++) {
         cur_pth += grph[k][ver[i]];
         k = ver[i];
      }
      cur_pth += grph[k][p];
      m_p = min(m_p, cur_pth); // to update the value of minimum weight
   }
   while (next_permutation(ver.begin(), ver.end()));
   return m_p;
}
int main() {
   int grph[][vr] = { { 0, 5, 10, 15 }, //values of a graph in a form of matrix
      { 5, 0, 20, 30 },
      { 10, 20, 0, 35 },
      { 15, 30, 35, 0 }
   };
   int p = 0;
   cout<< "\n The result is: "<< TSP(grph, p) << endl;
   return 0;
}
The result is: 75
TypeORM - Installation

This chapter explains about how to install TypeORM on your machine. Before moving to installation, please make sure that npm is installed. To confirm that you have npm, you can run the following command in your terminal.
npm -v

It shows the version. If it is not installed, download the latest version and install on your machine.
Let us install TypeORM locally using npm module −
npm install typeorm --save

After executing the above command, you will get a response as given below −
+ typeorm@0.2.24 
+ 
added 1 package and audited 1236 packages in 4.729s

Alternatively, to install TypeORM globally, use the below command −
npm install typeorm -g

After that, install optional package reflect-metadata using npm −
npm install reflect-metadata --save

You could see the following response −
+ reflect-metadata@0.1.13 

added 1 package and audited 1236 packages in 2.426s

Now, install another optional package. node typings using the below command −
npm install @types/node --save

You could see the following response −
+ @types/node@12.12.31 

added 1 package and audited 1236 packages in 2.167s

In this section, let us install the necessary node packages for our database.
To install MySQL or MariaDB package, use the below command −
npm install mysql --save

You could see the following response −
+ mysql@2.18.1 

added 1 package and audited 1236 packages in 4.36s

To install PostgreSQL package, use the below command −
npm install pg --save

You could see the following response −
+ pg@7.18.2 

added 1 package and audited 1236 packages in 2.863s

To install SQLite package, use the below command −
npm install sqlite3 --save

You could see the following response −
+ sqlite3@4.1.1 
added 48 packages from 45 contributors and audited 1396 packages in 7.31s

To install Microsoft SQL Server package, use the below command −
npm install mssql --save

Your screen looks similar to this,
+ mssql@6.2.0 

added 1 package and audited 1655 packages in 2.378s

To install sql.js  package, use the below command −
npm install sql.js --save

You could see the following response −
+ sql.js@1.2.1 

added 1 package and audited 1655 packages in 6.462s

To install Oracle server package, use the below command −
npm install oracledb --save

You could see the following response −
+ oracledb@4.2.0 

added 1 package and audited 1655 packages in 2.265s

To install mongodb package, use the below command −
npm install mongodb --save

You could see the following response −
+ mongodb@3.5.5 

added 1 package and audited 1655 packages in 3.716s


    19 Lectures 
     50 mins

 James Coonce
 Print
 Add Notes
 Bookmark this page
How to bold the text using CSS ? - GeeksforGeeks

30 Jun, 2021
We know that in HTML, we have <b> and <strong> tags to make the content bold. When it comes to making a piece of text bold using CSS, then also we have an appropriate property to do the same.
We will use the font-weight property of CSS to make the content bold. We have a variety of options to set the thickness level of our text.
normal : It is the normal font-weight.  It is the same as 400, the default numeric-value for boldness.
bold : It is the bold font-weight. It is the same as 700.
bolder : It sets the font-weight bolder than the parent element.
lighter : It sets the font-weight lighter than the parent element
<number>: A <number> value between 1 and 1000, inclusive (in increasing order of boldness level).
When lighter or bolder is specified, the below chart shows how the absolute font-weight of the element is determined.
Example 1: The following example demonstrates a simple text which is represented in bold using CSS font-weight property.
HTML
<!DOCTYPE html><html>    <head>        <style type="text/css">            h2 {                font-weight: 700;                color: green;            }            .text {                font-weight: bold;            }        </style>    </head>    <body>        <h2>          Welcome To Geeks for Geeks        </h2>        <p class="text">          A Computer Science portal for geeks        </p>     </body></html>
Output:
Example 2: The following example demonstrates few simple texts represented using other font-weight properties.
HTML
<!DOCTYPE html><html>    <body>        <h2 style="font-weight: bold;                   text-decoration: underline;">            Thought of the day        </h2>        <p style="font-weight: lighter;">          A good programmer is someone who          always look both ways          <span style="font-weight: 900;">            before crossing the one way road.          </span>        </p>     </body></html>
Output:
font-weight property
Supported Browser:
Google Chrome 2.0
Internet Explorer 4.0
Firefox 1.0
Opera 3.5
Safari 1.3
ysachin2314
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
C library macro - NULL()

The C library Macro NULL is the value of a null pointer constant. It may be defined as ((void*)0), 0  or 0L depending on the compiler vendor.
Following may be the declaration for NULL Macro depending on the compiler.
#define NULL ((char *)0)

or

#define NULL 0L

or

#define NULL 0
NA
NA
NA
NA
The following example shows the usage of NULL Macro.
#include <stddef.h>
#include <stdio.h>

int main () {
   FILE *fp;

   fp = fopen("file.txt", "r");
   if( fp != NULL ) {
      printf("Opend file file.txt successfully\n");
      fclose(fp);
   }

   fp = fopen("nofile.txt", "r");
   if( fp == NULL ) {
      printf("Could not open file nofile.txt\n");
   }
   
   return(0);
}
Assuming we have an existing file file.txt but nofile.txt does not exist. Let us compile and run the above program that will produce the following result −
Opend file file.txt successfully
Could not open file nofile.txt


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

CSS Text Effects
Tryit: The writing-mode property
PHP - session_set_cookie_params() Function

Sessions or session handling is a way to make the data available across various pages of a web application. The session_set_cookie_params() is used to set the session cookie parameters defined in the php.ini file
session_set_cookie_params([$array]);

array(Optional)
This an associative array which holds the values of the cookie parameters (lifetime, path, domain, secure, httponly and samesite).
This function returns a boolean value which is TRUE on success and FALSE on failure.
This function was first introduced in PHP Version 4 and works in all the later versions.
Following example demonstrates the usage of the session_set_cookie_params() function.
<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  	
         //Setting the cookie parameters
         session_set_cookie_params(30 * 60, "/", "test", );
         //Retrieving the cookie parameters
         $res = session_get_cookie_params();
         //Starting the session
         session_start();
         print_r($res);	  
      ?>
   </body>   
</html> 
One executing the above html file it will display the following message −
Array ( [lifetime] => 1800 [path] => /test [domain] => test.com [secure] => [httponly] => [samesite] => )

This is another example of this function.
<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  
         //Retrieving the cookie parameters
         $currentCookieParams = session_get_cookie_params();
         
         //Setting the cookie parameters
         $domain = '.test.com';
         session_set_cookie_params(
            $currentCookieParams["lifetime"],
            $currentCookieParams["path"],
            $domain,
            $currentCookieParams["secure"],
            $currentCookieParams["httponly"]
         );
         //Starting the session
         session_start();
      ?>
   </body>   
</html>

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
PHP | rmdir( ) Function

24 May, 2018
The rmdir() function in PHP is an inbuilt function which is used to remove an empty directory. It is mandatory for the directory to be empty, and it must have the relevant permissions which are required to delete the directory.The directory to be deleted is sent as a parameter to the rmdir() function and it returns True on success or False on failure.
Syntax:
rmdir(dirname, context)
Parameters Used:The rmdir() function in PHP accepts two parameters.
dirname : It is a mandatory parameter which specifies the directory to be deleted.context : It is an optional parameter which specifies the behavior of the stream .
dirname : It is a mandatory parameter which specifies the directory to be deleted.
context : It is an optional parameter which specifies the behavior of the stream .
Return Value:It returns True on success or False on failure.
Errors And Exception
The rmdir() function generates an E_WARNING level error on failure.opendir() must be closed before using rmdir() function else it gives permission denied error.PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed when it is in safe mode.
The rmdir() function generates an E_WARNING level error on failure.
opendir() must be closed before using rmdir() function else it gives permission denied error.
PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed when it is in safe mode.
Examples:
Input : mkdir('gfg');
        $dirname= "gfg";
        rmdir($dirname);
Output : 1

Input : $dirname = "gfg";
        if(rmdir($dirname))
        {
          echo ("$dirname successfully removed");
        }
        else
        {
          echo ("$dirname couldn't be removed"); 
        }
Output : gfg successfully removed


Below programs illustrate the rmdir() function.
Program 1
<?php// creating a directory named gfgmkdir('gfg');$dirname= "gfg";  // removing directory using rmdir()rmdir($dirname);?>
Output:
1
Program 2
<?php// creating a directory named gfg $dirname = "gfg";  // removing directory using rmdir()if(rmdir($dirname)){  echo ("$dirname successfully removed");}else{ echo ($dirname . "couldn't be removed"); }?>
Output:
gfg successfully removed
Reference:http://php.net/manual/en/function.rmdir.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Scala Queue isEmpty() method with example

29 Oct, 2019
The isEmpty() is utilized to check if the queue is empty or not.
Method Definition: def isEmpty: Boolean
Return Type: It returns true if the queue is empty or else it returns false.
Example #1:
// Scala program of isEmpty() // method   // Import Queue  import scala.collection.mutable._  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a queue         val q1 = Queue(1, 3, 2, 7, 6, 5)                   // Print the queue        println(q1)                  // Applying isEmpty method         val result = q1.isEmpty                  // Display output        print("The queue is empty: " + result)              } } 
Queue(1, 3, 2, 7, 6, 5)
The queue is empty: false

Example #2:
// Scala program of isEmpty() // method   // Import Queue  import scala.collection.mutable._  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a queue         val q1 = Queue()                   // Print the queue        println(q1)                  // Applying isEmpty method         val result = q1.isEmpty                  // Display output        print("The queue is empty: " + result)              } } 
Queue()
The queue is empty: true

Scala
scala-collection
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Scala
Comments In Scala
Scala List max() method with example
Scala | Traits
Scala | Functions - Basics
Hello World in Scala
Scala | Case Class and Case Object
Scala | Sealed Trait
Scala | Option
Scala | Closures
PriorityQueue comparator() Method in Java

20 Jun, 2021
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.Syntax: 
comp_set = (PriorityQueue)Priority_Queue.comparator()
Parameters: The method does not take any parameters.Return Value: The method returns the comparator used to order the elements of the queue in a specific order. It returns a Null value if the queue follows the default or natural ordering pattern.Below programs illustrate the java.util.PriorityQueue.comparator() method: Program 1: When using natural ordering of the elements:  
Java
// Java code to illustrate comparator()import java.util.*; public class Priority_Queue_Demo {    public static void main(String[] args)    {         // Creating an empty Priority_Queue        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();         // Adding elements to the queue        queue.add(20);        queue.add(24);        queue.add(30);        queue.add(35);        queue.add(45);        queue.add(50);         System.out.println("Priority queue values are: " + queue);         // Creating a comparator        Comparator comp = queue.comparator();         // Displaying the comparator values        System.out.println("Since the Comparator value is: " + comp);        System.out.println("it follows natural ordering");    }}
Priority queue values are: [20, 24, 30, 35, 45, 50]
Since the Comparator value is: null
it follows natural ordering
 
Program 2: When using a specific comparator.  
Java
// Java code to illustrate the use of comparator()import java.util.Comparator;import java.util.PriorityQueue; class The_Comparator implements Comparator<String> {    public int compare(String str1, String str2)    {        String first_Str;        String second_Str;        first_Str = str1;        second_Str = str2;        return second_Str.compareTo(first_Str);    }} public class Priority_Queue_Demo {    public static void main(String[] args)    {        PriorityQueue<String> queue = new        PriorityQueue<String>(new The_Comparator());         queue.add("G");        queue.add("E");        queue.add("E");        queue.add("K");        queue.add("S");        queue.add("4");                  System.out.println("The elements with the highest priority element at front of queue"                           + "order:");        while(!queue.isEmpty()){          System.out.print(" "+queue.poll());        }    }}
The elements with the highest priority element at front of queueorder:
 S K G E E 4
utkarshkalia
adityalata
sooda367
Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if Binary representation is Palindrome in Python

11 May, 2022
Given an integer ‘n’, write a Python function that returns true if binary representation of x is palindrome else return false. Examples:
Input : n = 9
Output : True
Binary representation of n=9 is 1001 which 
is palindrome as well.

Input : n = 10
Output : False
Binary representation of n=10 is 1010 which 
is not palindrome.
We have existing solution for this problem please refer Check if binary representation of a number is palindrome link. We can solve this problem in python very quickly. Approach is very simple,
Convert given number into it’s binary representation using bin(num) function.Now reverse binary representation string of number and compare it with original binary represented string, if both are equal that means binary representation of number is palindrome else not. 
Convert given number into it’s binary representation using bin(num) function.
Now reverse binary representation string of number and compare it with original binary represented string, if both are equal that means binary representation of number is palindrome else not.
 
Note : We can use other approach of checking a string is palindrome or not. 
Python
# Function to check if binary representation of# a number is palindrome or not def binarypalindrome(num):      # convert number into binary     binary = bin(num)      # skip first two characters of string     # because bin function appends '0b' as     # prefix in binary representation of     # a number     binary = binary[2:]      # now reverse binary string and compare     # it with original     return binary == binary[-1::-1] # Driver programif __name__ == "__main__":    num = 9    print binarypalindrome(num)
Output:
True
surinderdawra388
base-conversion
palindrome
Python
Python Programs
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Duck Typing in Python

31 Dec, 2019
Duck Typing is a type system used in dynamic languages. For example, Python, Perl, Ruby, PHP, Javascript, etc. where the type or the class of an object is less important than the method it defines. Using Duck Typing, we do not check types at all. Instead, we check for the presence of a given method or attribute.
The name Duck Typing comes from the phrase:
“If it looks like a duck and quacks like a duck, it’s a duck”
Example:
# Python program to demonstrate# duck typing  class Specialstring:    def __len__(self):        return 21  # Driver's codeif __name__ == "__main__":      string = Specialstring()    print(len(string))
Output:
21
In this case, we call method len() gives the return value from __len__ method. Here __len__ method defines the property of the class Specialstring
The object’s type itself is not significant in this we do not declare the argument in method prototypes. This means that compilers can not do type-checking. Therefore, what really matters is if the object has particular attributes at run time. Duck typing is hence implemented by dynamic languages. But now some of the static languages like Haskell also supports it. But, Java/C# doesn’t have this ability yet.
Example: Now, lets look demonstrates how an object be used in any other circumstances until it is not supported.
# Python program to demonstrate# duck typing    class Bird:    def fly(self):        print("fly with wings")  class Airplane:    def fly(self):        print("fly with fuel")  class Fish:    def swim(self):        print("fish swim in sea")  # Attributes having same name are# considered as duck typingfor obj in Bird(), Airplane(), Fish():    obj.fly()
Output:
fly with wings
fly with fuel

Traceback (most recent call last):
  File "/home/854855e5570b9ce4a9e984209b6a1c21.py", line 20, in 
    obj.fly()
AttributeError: 'Fish' object has no attribute 'fly'

In this example, we can see a class supports some method we can modify it or give them new functionality. Duck-typing emphasis what the object can really do, rather than what the object is.
python-utility
Python
Technical Scripter
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
Python OOPs Concepts
Introduction To PYTHON
Static Variables in Java with Examples

30 Sep, 2019
When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
Important points for static variables:
We can create static variables at class-level only. See here
static block and static variables are executed in order they are present in a program.
Below is the java program to demonstrate that static block and static variables are executed in the order they are present in a program.
// Java program to demonstrate execution// of static blocks and variables  class Test {      // static variable    static int a = m1();      // static block    static    {        System.out.println("Inside static block");    }      // static method    static int m1()    {        System.out.println("from m1");        return 20;    }      // static method(main !!)    public static void main(String[] args)    {        System.out.println("Value of a : " + a);        System.out.println("from main");    }}
from m1
Inside static block
Value of a : 20
from main

Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get visitors country from their IP in PHP ?

29 May, 2019
Overview: To obtain the details like country, continent, city, etc of the visitor, first we need to get the IP of the visitor. The IP address can be obtained with the help of superglobal $_SERVER in PHP. Finally, with the use of API geoPlugin, we can obtain information about the IP address i.e. visitor of the website.
Step 1: Getting the visitor’s IP address.$_SERVER is a PHP Superglobals variable which holds information about headers, IP, script details, etc. Elements like REMOTE_ADDR, HTTP_X_REAL_IP, HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR can be used to get the IP from this super global.
Example: This example obtain the IP of the visitors.
<?php// PHP code to extract IP   function getVisIpAddr() {          if (!empty($_SERVER['HTTP_CLIENT_IP'])) {        return $_SERVER['HTTP_CLIENT_IP'];    }    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {        return $_SERVER['HTTP_X_FORWARDED_FOR'];    }    else {        return $_SERVER['REMOTE_ADDR'];    }}  // Store the IP address$vis_ip = getVisIPAddr();  // Display the IP addressecho $vis_ip;   ?>
Note: In case of CloudFlare, one may need to use elements like HTTP_X_REAL_IP to obtain the IP address.
Step 2: Use API to get the details of the visitor’s IP: Here, we are going to use the geoPlugin API to get the details of the visitor. The api will deliver a json object, which can convert to a PHP variable.
<?php// PHP code to obtain country, city, // continent, etc using IP Address  $ip = '52.25.109.230';  // Use JSON encoded string and converts// it into a PHP variable$ipdat = @json_decode(file_get_contents(    "http://www.geoplugin.net/json.gp?ip=" . $ip));   echo 'Country Name: ' . $ipdat->geoplugin_countryName . "\n";echo 'City Name: ' . $ipdat->geoplugin_city . "\n";echo 'Continent Name: ' . $ipdat->geoplugin_continentName . "\n";echo 'Latitude: ' . $ipdat->geoplugin_latitude . "\n";echo 'Longitude: ' . $ipdat->geoplugin_longitude . "\n";echo 'Currency Symbol: ' . $ipdat->geoplugin_currencySymbol . "\n";echo 'Currency Code: ' . $ipdat->geoplugin_currencyCode . "\n";echo 'Timezone: ' . $ipdat->geoplugin_timezone;   ?>
Output:
Country Name:    United States
City Name:       Boardman
Continent Name:  North America
Latitude:        45.8491
Longitude:       -119.7143
Currency Symbol: $
Currency Code:   USD
Timezone:        America/Los_Angeles

Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL query to remove special characters from column values?

Let us first create a table −
mysql> create table DemoTable
-> (
-> StudentId varchar(100)
-> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('STU#123');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('STU#567');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('STU#98494');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| STU#123   |
| STU#567   |
| STU#98494 |
+-----------+
3 rows in set (0.00 sec)
Following is the query to remove special characters −
mysql> update DemoTable
-> set StudentId=replace(StudentId,'#','');
Query OK, 3 rows affected (0.13 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| STU123    |
| STU567    |
| STU98494  |
+-----------+
3 rows in set (0.00 sec)
How to check if string or a substring of string starts with substring in Python?

Python has a method startswith(string) in the String class. This method accepts a prefix string that you want to search and is called on a string object. You can call this method in the following way:
>>> 'hello world'.startswith('hell')
True
>>> "Harry Potter".startswith("Harr")
True
>>> 'hello world'.startswith('nope')
False
There is another way to find if a string ends with a given prefix. You can use re.search('^' + prefix, string) from the re module(regular expression) to do so. Regex interprets ^ as start of line, so if you want to search for a prefix, you need to do the following:
>>> import re
>>> bool(re.search('^hell', 'hello world'))
True
>>> bool(re.search('^Harr', 'Harry Potter'))
True
>>> bool(re.search('^nope', 'hello world'))
False
Find the first repeated word in a string in Python using Dictionary - GeeksforGeeks

23 Nov, 2020
Prerequisite : Dictionary data structure
Given a string, Find the 1st repeated word in a string.Examples:
Input : "Ravi had been saying that he had been there"
Output : had
 
Input : "Ravi had been saying that"
Output : No Repetition

Input : "he had had he"
Output : he

We have existing solution for this problem please refer Find the first repeated word in a string link. We can solve this problem quickly in python using Dictionary data structure. Approach is simple,
First split given string separated by space.Now convert list of words into dictionary using collections.Counter(iterator) method. Dictionary contains words as key and it’s frequency as value.Now traverse list of words again and check which first word has frequency greater than 1.
First split given string separated by space.
Now convert list of words into dictionary using collections.Counter(iterator) method. Dictionary contains words as key and it’s frequency as value.
Now traverse list of words again and check which first word has frequency greater than 1.
# Function to Find the first repeated word in a string from collections import Counter   def firstRepeat(input):           # first split given string separated by space     # into words     words = input.split(' ')           # now convert list of words into dictionary     dict = Counter(words)       # traverse list of words and check which first word     # has frequency > 1     for key in words:         if dict[key]>1:             print (key)             return  # Driver program if __name__ == "__main__":     input = 'Ravi had been saying that he had been there'    firstRepeat(input) 
Output:
had

Python dictionary-programs
Python string-programs
python-dict
python-string
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
Python | numpy.busday_count() method - GeeksforGeeks

03 Oct, 2019
With the help of numpy.busday_count() method, we can get the value of all the valid days from starting date to ending date excluding ending date by using numpy.busday_count() method.
Syntax : numpy.busday_count(start_date, end_date)
Return : Return the valid date count.
Example #1 :In this example we can see that by using numpy.busday_count() method, we are able to get the count of valid days between starting date and ending date.
# import numpyimport numpy as np  # using numpy.busday_count() methodgfg = np.busday_count('2019-09', '2019-10')  print(gfg)
Output :
21
Example #2 :
import numpy as np  # using numpy.busday_count() methodgfg = np.busday_count('2019-09', '2019-10', weekmask ='Sat')  print(gfg)
Output :
4
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
What are __FILE__, __LINE__, and __FUNCTION__ in C++

Here we will see what are the __FILE, __LINE__ and __FUNCTION__ in C++.
This macro is used to get the path of the current file. This is useful when we want to generate log files. The following code will explain its functionality.
#include<iostream>
using namespace std;
int errorLog (const char* file, const std::string& msg){
   cerr << "[" << file << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FILE__, msg )
main() {
   LOG("This is a dummy error");
}
[D:\Misc C and C++ Questions\test_prog.cpp] This is a dummy error
This macro can find the current line number in source file. This line number is an integer value. When log statements are generating then __LINE__ plays some useful role. See the following example to get the idea.>
#include<iostream>
using namespace std;
int errorLog (int line, const std::string& msg){
   cerr << "[" << line << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __LINE__, msg )
main() {
   LOG("This is a dummy error");
}
[12] This is a dummy error
This macro can return the current function. When log statements are generating then __FUNCTION__ plays some useful role. See the following example to get the idea.
long double rintl(long double argument)
#include<iostream>
using namespace std;
int errorLog (const char* func, const std::string& msg){
   cerr << "[" << func << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FUNCTION__, msg )
void TestFunction(){
   LOG("Send from Function");
}
main() {
   TestFunction();
   LOG("This is a dummy error");
}
[TestFunction] Send from Function
[main] This is a dummy error
top command in Linux with Examples

19 May, 2022
top command is used to show the Linux processes. It provides a dynamic real-time view of the running system. Usually, this command shows the summary information of the system and the list of processes or threads which are currently managed by the Linux Kernel. As soon as you will run this command it will open an interactive command mode where the top half portion will contain the statistics of processes and resource usage. And Lower half contains a list of the currently running processes. Pressing q will simply exit the command mode.  Here,
PID: Shows task’s unique process id.
PR: The process’s priority. The lower the number, the higher the priority.
VIRT: Total virtual memory used by the task.
USER: User name of owner of task.
%CPU: Represents the CPU usage.
TIME+: CPU Time, the same as ‘TIME’, but reflecting more granularity through hundredths of a second.
SHR: Represents the Shared Memory size (kb) used by a task.
NI: Represents a Nice Value of task. A Negative nice value implies higher priority, and positive Nice value means lower priority.
%MEM: Shows the Memory usage of task.
RES: How much physical RAM the process is using, measured in kilobytes.
COMMAND: The name of the command that started the process.
Examples: 1) Exit Top Command After Specific repetition: Top output keep refreshing until you press ‘q‘. With below command top command will automatically exit after 10 number of repetition.
top -n 10
2) Display Specific User Process
top -u paras
Z 3) Highlight Running Process in Top: Press ‘z‘ option in running top command will display running process in color which may help you to identified running process easily Z 4) Shows Absolute Path of Processes: Press ‘c‘ option in running top command, it will display absolute path of running pro Z 5) Kill running process: You can kill a process after finding PID of process by pressing ‘k‘ option in running top command without exiting from top window as shown below. 6) Sort by CPU Utilisation: Press (Shift+P) to sort processes as per CPU utilization. 7) Shows top command syntax:
top -h 
 8) Batch Mode : Send output from top to file or any other programs.
top -b
9) Secure Mode : Use top in Secure mode.
top -s
10) Command Line : The below command starts top with last closed state.
Top -c
11) Delay time : It tells delay time between screen updates.
Top -d seconds.tenths
ankkerbintang18
gowthamreddyuppunuri
pritammukherjeejoey786
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
VHDL code for AND and OR Logic Gates

21 Jun, 2022
Prerequisite – Introduction of Logic Gates 
Design and implement the AND and OR logic gates using VHDL (VHSIC Hardware Description Language) programming language. 
Different Types of VHDL Modelling Styles 
The architecture of VHDL code is written in three different coding styles :
Dataflow Modelling Behavioral ModellingStructural Modelling
Dataflow Modelling 
Behavioral Modelling
Structural Modelling
1. Logic Development for AND Gate: The AND logic gate can be realized as follows –
 
The truth table for AND Gate is:
Implementation of Dataflow Modelling – Below is the implementation of the above logic in the VHDL language (Dataflow Modelling).
-- VHDL Code for AND gate

-- Header file declaration

library IEEE;
use IEEE.std_logic_1164.all;

-- Entity declaration

entity andGate is

    port(A : in std_logic;      -- AND gate input
         B : in std_logic;      -- AND gate input
         Y : out std_logic);    -- AND gate output

end andGate;

-- Dataflow Modelling Style
-- Architecture definition

architecture andLogic of andGate is

 begin
    
    Y <= A AND B;

end andLogic; 
2. Logic Development for OR Gate: The OR logic gate can be realized as follows –
  
The truth table for OR Gate is:
Implementation of Dataflow Modelling – Below is the implementation of the above logic in the VHDL language (Dataflow Modelling).
-- VHDL Code for OR gate

-- Header file declaration

library IEEE;
use IEEE.std_logic_1164.all;

-- Entity declaration

entity orGate is

    port(A : in std_logic;      -- OR gate input
         B : in std_logic;      -- OR gate input
         Y : out std_logic);    -- OR gate output

end orGate;

-- Dataflow Modelling Style
-- Architecture definition

architecture orLogic of orGate is

 begin
    
    Y <= A OR B;

end orLogic;
rjrachit2468
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shift Registers in Digital Logic
IEEE Standard 754 Floating Point Numbers
Flip-flop types, their Conversion and Applications
Counters in Digital Logic
Encoder in Digital Logic
Encoders and Decoders in Digital Logic
Full Subtractor in Digital Logic
Multiplexers in Digital Logic
Introduction to memory and memory units
Half Adder in Digital Logic
Find an element in array such that sum of left array is equal to sum of right array using c++

Suppose we have an array A, it has n elements. Our task is to divide the array A into two subarrays, such that the sum of each subarray will be the same. Suppose the array A = [2, 3, 4, 1, 4, 5], The output is 1, so subarrays before 1 and after 1 are taken. [2, 3, 4], and [4, 5].
To solve this problem, we will calculate the whole array except for the first element in right_sum. Consider that is the partitioning element. We will traverse from left to right. Subtracting an element from right_sum and adding an element to left_sum, we take the point when right_sum = left_sum.
 Live Demo
#include<iostream>
using namespace std;
int getPartitionElement(int arr[], int size) {
   int right = 0, left = 0;
   for (int i = 1; i < size; i++)
      right += arr[i];
      for (int i = 0, j = 1; j < size; i++, j++) {
         right -= arr[j];
         left += arr[i];
         if (left == right)
            return arr[i + 1];
      }
   return -1;
}
int main() {
   int arr[] = { 2, 3, 4, 1, 4, 5 };
   int size = sizeof(arr) / sizeof(arr[0]);
   cout << "Partition element: " << getPartitionElement(arr, size);
}
Partition element: 1
Create PySpark DataFrame from list of tuples - GeeksforGeeks

30 May, 2021
In this article, we are going to discuss the creation of a Pyspark dataframe from a list of tuples. 
To do this, we will use the createDataFrame() method from pyspark. This method creates a dataframe from RDD, list or Pandas Dataframe. Here data will be the list of tuples and columns will be a list of column names.
Syntax:
dataframe = spark.createDataFrame(data, columns)
Example 1:
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list of tuples of college datadata = [("sravan", "IT", 80),        ("jyothika", "CSE", 85),        ("harsha", "ECE", 60),        ("thanmai", "IT", 65),        ("durga", "IT", 91)]  # giving column names of dataframecolumns = ["Name", "Branch", "Percentage"]  # creating a dataframedataframe = spark.createDataFrame(data, columns)  # show data framedataframe.show()
Output:
Example 2:
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list of tuples of plants datadata = [("mango", "AP", "Guntur"),        ("mango", "AP", "Chittor"),        ("sugar cane", "AP", "amaravathi"),        ("paddy", "TS", "adilabad"),        ("wheat", "AP", "nellore")]  # giving column names of dataframecolumns = ["Crop Name", "State", "District"]  # creating a dataframedataframe = spark.createDataFrame(data, columns)  # show data framedataframe.show()
Output:
Example 3:
Python code to count the records (tuples) in the list
Python3
# importing moduleimport pyspark  # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  #list of tuples of plants datadata = [("mango", "AP", "Guntur"),        ("mango", "AP", "Chittor"),        ("sugar cane", "AP", "amaravathi"),        ("paddy", "TS", "adilabad"),        ("wheat", "AP", "nellore")]  # giving column names of dataframecolumns = ["Crop Name", "State", "District"]  # creating a dataframe dataframe = spark.createDataFrame(data, columns)  #count records in the listdataframe.count()
Output:
5
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python