code-rag-bench/online-tutorials huggingface dataset:
Parsing XML with DOM APIs in Python

10 May, 2020
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as below:
<?xml version="1.0"?><company>    <name>GeeksForGeeks Company</name>    <staff id="1">        <name>Amar Pandey</name>        <salary>8.5 LPA</salary>    </staff>    <staff id="2">        <name>Akbhar Khan</name>        <salary>6.5 LPA</salary>    </staff>    <staff id="3">        <name>Anthony Walter</name>        <salary>3.2 LPA</salary>    </staff></company>
Now, let’s parse the above XML using python. The below code demonstrates the process,
from xml.dom import minidom  doc = minidom.parse("sample.xml")  # doc.getElementsByTagName returns the NodeListname = doc.getElementsByTagName("name")[0]print(name.firstChild.data)  staffs = doc.getElementsByTagName("staff")for staff in staffs:        staff_id = staff.getAttribute("id")        name = staff.getElementsByTagName("name")[0]        salary = staff.getElementsByTagName("salary")[0]        print("id:% s, name:% s, salary:% s" %              (staff_id, name.firstChild.data, salary.firstChild.data))
Output:
GeeksForGeeks Company
id:1, name: Amar Pandey, salary:8.5 LPA
id:2, name: Akbar Khan, salary:6.5 LPA
id:3, name: Anthony Walter, salary:3.2 LPA
The same can also be done using a user-defined function as shown in the code below:
from xml.dom import minidom  doc = minidom.parse("sample.xml")  # user-defined functiondef getNodeText(node):      nodelist = node.childNodes    result = []    for node in nodelist:        if node.nodeType == node.TEXT_NODE:            result.append(node.data)    return ''.join(result)  name = doc.getElementsByTagName("name")[0]print("Company Name : % s \n" % getNodeText(name))    staffs = doc.getElementsByTagName("staff")for staff in staffs:        staff_id = staff.getAttribute("id")        name = staff.getElementsByTagName("name")[0]        salary = staff.getElementsByTagName("salary")[0]        print("id:% s, name:% s, salary:% s" %              (staff_id, getNodeText(name), getNodeText(salary)))
Output:
Company Name : GeeksForGeeks Company 

id:1, name:Amar Pandey, salary:8.5 LPA
id:2, name:Akbhar Khan, salary:6.5 LPA
id:3, name:Anthony Walter, salary:3.2 LPA
Python-XML
Python
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
How to instantiate delegates in C#?

Use the new keyword to instantiate a delegate. When creating a delegate, the argument passed to the
new expression is written similar to a method call, but without the arguments to the method.
For example −
public delegate void printString(string s);
printString ps1 = new printString(WriteToScreen);
You can also instantiate a delegate using an anonymous method −
//declare
delegate void Del(string str);
Del d = delegate(string name) {
   Console.WriteLine("Notification received for: {0}", name);
};
Let us see an example that declare and instantiates a delegate −
 Live Demo
using System;

delegate int NumberChanger(int n);
namespace DelegateAppl {

   class TestDelegate {

      static int num = 10;
      public static int AddNum(int p) {
         num += p;
         return num;
      }
      public static int MultNum(int q) {
         num *= q;
         return num;
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);

         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}
Value of Num: 35
Value of Num: 175
Hangman Game in Python?

Hangman is a classic word game in which participants needs to guess as many secret words as you can before time runs out! So, it’s a nice game to learn new words, one letter at a time!
So we are going to write python script for this classic game “hangman”.
#importing the time module
import time

#welcoming the user
name = input("What is your name? ")

print("Hello, " + name, "Time to play hangman!")

print ("")

#wait for 1 second
time.sleep(1)

print ("Start guessing...")
time.sleep(0.5)

#here we set the secret
word= ("Secret")
word = word.lower()

#creates an variable with an empty value
guesses = ''

#determine the number of turns
turns = 12

# Create a while loop

#check if the turns are more than zero
while turns > 0:

   # make a counter that starts with zero
   failed = 0

   # for every character in secret_word
   for char in word:

   # see if the character is in the players guess
   if char in guesses:

      # print then out the character
      print (char, )

   else:

      # if not found, print a dash
      print ("_",)

      # and increase the failed counter with one
      failed += 1

# if failed is equal to zero

# print You Won
if failed == 0:
   print ("You won" )

# exit the script
   break

print
# ask the user go guess a character
guess = input("guess a character:")

# set the players guess to guesses
guesses += guess

# if the guess is not found in the secret word
if guess not in word:

# turns counter decreases with 1 (now 9)
turns -= 1

# print wrong
print ("Wrong")

# how many turns are left
print("You have", + turns, 'more guesses' )

# if the turns are equal to zero
   if turns == 0:

   # print "You Loose"
   print ("You Loose")
================== RESTART: C:\Python\Python361\hangman1.py ==================
What is your name? Raj
Hello, Raj Time to play hangman!

Start guessing...
_
_
_
_
_
_
guess a character:s
s
_
_
_
_
_
guess a character:h
Wrong
You have 11 more guesses
s
_
_
_
_
_
guess a character:e
s
e
_
_
e
_
guess a character:c
s
e
c
_
e
_
guess a character:r
s
e
c
r
e
_
guess a character:e
s
e
c
r
e
_
guess a character:t
s
e
c
r
e
t
You won
>>>
Batch Script - PROMPT

This batch command can be used to change or reset the cmd.exe prompt.
PROMPT [newpromptname]

@echo off 
prompt myprompt$G
The $G is the greater than sign which is added at the end of the prompt.
The prompt shown to the user will now be myprompt>
 Print
 Add Notes
 Bookmark this page
C# Program to write a number in hexadecimal format

Let’s say the following is the number −
int a = 12250;
You can work around the following ways to get a number in hexadecimal format −
{0:x}
{0:x8}
{0:X}
{0:X8}
Here is the code −
 Live Demo
using System;
class Demo {
   static void Main() {
      int a = 12250;
      Console.WriteLine("{0:x}", a);
      Console.WriteLine("{0:x8}", a);
      Console.WriteLine("{0:X}", a);
      Console.WriteLine("{0:X8}", a);
   }
}
2fda
00002fda
2FDA
00002FDA
C++ program for Finite Automata algorithm for Pattern Searching

In this article, we will be discussing a program to execute the Finite Automata algorithm for pattern searching.
We are provided with a text[0...n-1] and a pattern[0...m-1]. We have to find all the occurrences of the pattern[] in the text[].
For this we would preprocess the text[] and build a 2-d array to represent it. After that we just have to traverse between the elements of the text[] and the different states of the automata.
 Live Demo
#include<stdio.h>
#include<string.h>
#define total_chars 256
int calc_nextstate(char *pat, int M, int state, int x) {
   if (state < M && x == pat[state])
      return state+1;
   int ns, i;
   for (ns = state; ns > 0; ns--) {
      if (pat[ns-1] == x) {
         for (i = 0; i < ns-1; i++)
            if (pat[i] != pat[state-ns+1+i])
               break;
         if (i == ns-1)
            return ns;
      }
   }
   return 0;
}
//builds Finite Automata
void calc_TF(char *pat, int M, int TF[][total_chars]) {
   int state, x;
   for (state = 0; state <= M; ++state)
      for (x = 0; x < total_chars; ++x)
         TF[state][x] = calc_nextstate(pat, M, state, x);
}
//prints all occurrences of pattern in text
void calc_occur(char *pat, char *txt) {
   int M = strlen(pat);
   int N = strlen(txt);
   int TF[M+1][total_chars];
   calc_TF(pat, M, TF);
   int i, state=0;
   for (i = 0; i < N; i++){
      state = TF[state][txt[i]];
      if (state == M)
         printf ("\n Given pattern is found at the index%d",i-M+1);
   }
}
int main() {
   char *txt = "AABCDAABBDCAABADAABDABAABA";
   char *pat = "AABA";
   calc_occur(pat, txt);
   return 0;
}
Given pattern is found at the index 11
Given pattern is found at the index 22
How to print text from a list of all web elements with same class name in Selenium?

We can get the text from a list of all web elements with the same class name in Selenium webdriver. We can use any of the locators like the class name with method By.className, xpath with method By.xpath, or css with method By.cssSelector.
Let us verify a xpath expression //h2[@class='store-name'] which represents multiple elements that have the same class name as store-name. If we validate this in Console with the expression - $x("//h2[@class='store-name']"), it yields all the matching elements as shown below:
Also, since we need to obtain multiple elements, we have to use the findElements method which returns a list. We shall iterate through this list and obtain the text of the elements with getText method.
List<WebElement> m =
driver.findElements(By.xpath("//h2[@class='store-name']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ElementsSameclsname{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.justdial.com/Bangalore/Bakeries");
      // identify elements list with same class name
      List<WebElement> m = driver.findElements(By.xpath("//h2[@class='store-name']"));
      // iterate over list
      for(int i = 0; i< m.size(); i++) {
         //obtain text
         String s = m.get(i).getText();
         System.out.println("Text is: " + s);
      }
      driver.quit();
   }
}
Delete data from a collection in MongoDB using multiple conditions?

You can use remove() for this. Let us first create a collection with documents −
> db.deleteDataDemo.insertOne({_id:1,"Name":"Larry"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.deleteDataDemo.insertOne({_id:2,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.deleteDataDemo.insertOne({_id:3,"Name":"Robert"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.deleteDataDemo.insertOne({_id:4,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 4 }
> db.deleteDataDemo.insertOne({_id:5,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 5 }
> db.deleteDataDemo.insertOne({_id:6,"Name":"Sam"});
{ "acknowledged" : true, "insertedId" : 6 }
Following is the query to display all documents from a collection with the help of find() method −
> db.deleteDataDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "Larry" }
{ "_id" : 2, "Name" : "Chris" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 4, "Name" : "David" }
{ "_id" : 5, "Name" : "Carol" }
{ "_id" : 6, "Name" : "Sam" }
Following is the query to delete data from a collection in MongoDB by using multiple conditions. Here we have used two conditions i.e. _id 4 and Name David −
> db.deleteDataDemo.remove({'_id':4,'Name':"David"});
WriteResult({ "nRemoved" : 1 })
Let us check all the documents once again −
> db.deleteDataDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "Larry" }
{ "_id" : 2, "Name" : "Chris" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 5, "Name" : "Carol" }
{ "_id" : 6, "Name" : "Sam" }
The Doubly Linked List class in Javascript

Here is the complete implementation of the DoublyLinkedList Class −
class DoublyLinkedList {
   constructor() {
      this.head = null;
      this.tail = null;
      this.length = 0;
   }
   insert(data, position = this.length) {
      let node = new this.Node(data);
      // List is currently empty
      if (this.head === null) {
         this.head = node;
         this.tail = node;
         this.length++;
         return this.head;
      }
      // Insertion at head
      if (position == 0) {
         node.prev = null;
         node.next = this.head;
         this.head.prev = node;
         this.head = node;
         return this.head;
      }
      let iter = 1;
      let currNode = this.head;
      while (currNode.next != null && iter < position) {
         currNode = currNode.next; iter++;
      }
      // Make new node point to next node in list
      node.next = currNode.next;
      // Make next node's previous point to new
      node if (currNode.next != null) {
         currNode.next.prev = node;
      }
      // Make our node point to previous node
      node.prev = currNode;

      // Make previous node's next point to new node
      currNode.next = node;

      // check if inserted element was at the tail, if yes then make tail point to it
      if (this.tail.next != null) {
         this.tail = this.tail.next;
      }
      this.length++;
      return node;
   }
   remove(data, position = 0) {
      if (this.length === 0) {
         console.log("List is already empty");
         return;
      }
      this.length--;
      let currNode = this.head;
      if (position <= 0) {
         this.head = this.head.next;
         this.head.prev = null;
      } else if (position >= this.length - 1) {
         this.tail = this.tail.prev;
         this.tail.next = null;
      } else {
         let iter = 0;
         while (iter < position) {
            currNode = currNode.next;
            iter++;
         }
         currNode.next = currNode.next.next;
         currNode.next.prev = currNode;
      }
      return currNode;
   }
   display() {
      let currNode = this.head;
      while (currNode != null) {
         console.log(currNode.data + " <-> ");
         currNode = currNode.next;
      }
   }
}

DoublyLinkedList.prototype.Node = class {
   constructor(data) {
      this.data = data;
      this.next = null;
      this.prev = null;
   }
};
Firebase - Twitter Authentication

In this chapter, we will explain how to use Twitter authentication.
You can create Twitter app on this link. Once your app is created click on Keys and Access Tokens where you can find API Key and API Secret. You will need this in step 2.
In your Firebase dashboard side menu, you need to click Auth. Then open SIGN-IN-METHOD tab. Click on Twitter to enable it. You need to add API Key and API Secret from the step 1.
Then you would need to copy the callback URL and paste it in your Twitter app. You can find the Callback URL of your Twitter app when you click on the Settings tab.
In this step, we will add two buttons inside the body tag of index.html.
<button onclick = "twitterSignin()">Twitter Signin</button>
<button onclick = "twitterSignout()">Twitter Signout</button>
Now we can create functions for Twitter authentication.
var provider = new firebase.auth.TwitterAuthProvider();

function twitterSignin() {
   firebase.auth().signInWithPopup(provider)
    
  .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
		
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      console.log(error.code)
      console.log(error.message)
   });
}

function twitterSignout() {
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed!')
   });
}
When we start our app, we can sigin or signout by clicking the two buttons. The console will confirm that the authentication is successful.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Batch Script - PAUSE

This batch command prompts the user and waits for a line of input to be entered.
Pause

@echo off 
pause
The command prompt will show the message “Press any key to continue....” to the user and wait for the user’s input.
 Print
 Add Notes
 Bookmark this page
BigInteger modPow() Method in Java - GeeksforGeeks

11 Aug, 2021
Prerequisite: BigInteger BasicsThe Java.math.BigInteger.modPow() method returns a BigInteger whose value is (thisexponent mod m ). If exponent == 1, the returned value is (this mod m) and if exponent < 0, the returned value is the modular multiplicative inverse of (this-exponent). The method throws an ArithmeticException if m <= 0. 
Syntax:  
public BigInteger modPow(BigInteger exponent, BigInteger m)
Parameters: The method accepts two parameters.  
exponent: This parameter refers to the exponent.
m: This parameter refers to the modulus.
Return Value: The method returns a BigInteger object whose value is ( thisexponent mod m ). 
Exceptions:  
ArithmeticException: If (m <= 0) or the exponent is negative and this BigInteger is not relatively prime to m.
Examples: 
Input: biginteger1 = 23895 
                        exponent = 15
                        biginteger2 = 14189
Output: 344
Explanation:
result = biginteger1.modPow(exponent, biginteger2)
23895^15 % 14189 = 344

Input: biginteger1 = 6547890621
       exponent = 4532415
       biginteger2 = 76543278906
Output: 1039609179
Explanation:
6547890621^4532415 % 76543278906 = 1039609179
Below program illustrates the Java.math.BigInteger.modPow() method:  
Java
// Code to illustrate modpow() method of BigIntegerimport java.math.*;import java.util.Scanner; public class GFG {     public static void main(String[] args)    {         // Create 3 BigInteger objects        BigInteger biginteger1, biginteger2, result;         // Initializing all BigInteger Objects        biginteger1 = new BigInteger("23895");        biginteger2 = new BigInteger("14189");        BigInteger exponent = new BigInteger("15");         // Perform modPow operation on the objects and exponent        result = biginteger1.modPow(exponent, biginteger2);        String expression = biginteger1 + "^" + exponent + " % "                            + biginteger2 + " = " + result;         // Displaying the result        System.out.println(expression);    }}
23895^15 % 14189 = 344
 
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs() 
anikaseth98
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Stream In Java
Copy all files from one directory to another using Python - GeeksforGeeks

06 Sep, 2021
In this article, we will discuss how to copy all files from one directory to another using Python.
This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories.
The shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory. It is created during the copy operation execution. 
Syntax: shutil.copytree(src, dst, copy_function = copy2)
Parameter: 
src : source directory
dst : destination director
copy_function (optional): Default – copy2(). copy() method may also be used.
Returns :The newly created destination directory name
Extended support for the os package is also needed in Python to perform all the operations related to file manipulations effectively. It provides many functions to work with directories, and their corresponding files and folders contained. 
os.listdir(dir), lists all the files in the specified directory, dir, and os.path.join(a, b) is used to create a path by joining sub-paths a followed by b respectively. 
Directory in use: 
Python3
import shutilimport os # path to source directorysrc_dir = 'fol1' # path to destination directorydest_dir = 'fol2' # getting all the files in the source directoryfiles = os.listdir(src_dir) shutil.copytree(src_dir, dest_dir)
Output:
The copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method also preserving the file’s metadata. 
Syntax:
shutil.copy2(src, dst)
Parameter:
src : source directory
dst : destination director
Returns: The destination directory path 
In addition to this, the Pathlib module is also incorporated to work with filesystem paths concerned with different operating systems. The Path function in the Pathlib package is used to define concrete paths. 
Note: In this method, the files are copied to an already existing folder.
Directory in use: 
Python3
# importing required packagesfrom pathlib import Pathimport shutil # defining source and destination# pathssrc = 'source'trg = 'destination' files=os.listdir(src) # iterating over all the files in# the source directoryfor fname in files:         # copying the files to the    # destination directory    shutil.copy2(os.path.join(src,fname), trg)
Output:
varshagumber28
adnanirshad158
Picked
Python directory-program
Python-shutil
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()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How do you use a ‘for loop’ for accessing array elements in C#?

The ‘for loop’ executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
The following is our for loop.
 Live Demo
using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */
         int i,j;
         /* initialize elements of array n */
         for ( i = 0; i < 10; i++ ) {
            n[ i ] = i + 100;
         }
         /* output each array element's value */
         for (j = 0; j < 10; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         int a = n[2];
         Console.WriteLine(a);
         Console.ReadKey();
      }
   }
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
102
Now let’s say you need the third element. For that, use.
int a = n[1];
The above will give the third element i.e. 102.
File Upload Example in Python

To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a "Browse" button.
<html>
<body>
   <form enctype = "multipart/form-data" action = "save_file.py" method = "post">
   <p>File: <input type = "file" name = "filename" /></p>
   <p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
The result of this code is the following form −
Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.
Here is the script save_file.py to handle file upload −
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())
   message = 'The file "' + fn + '" was uploaded successfully'
else:
   message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
Tryit Editor v3.7

Tryit: HTML table header spans 2 columns
How can we MySQL LOAD DATA INFILE statement with ‘FIELDS TERMINATED BY’ option to import data from text file into MySQL table?

‘FIELDS TERMINATED BY’ option should be used when the text file which we want to import into MySQL table is having the values which are separated by a comma(,) or maybe with any other separator like a colon(:), semicolon(;) etc. It can be understood with the help of the following example −
Suppose we are having the following data, separated by a semicolon(;), in the text file ‘A.txt’ which we want to import into a MySQL file −
100;Ram;IND;15000
120;Mohan;IND;18000
Now with the help of the following query by using the option ‘FIELDS SEPARATED BY ‘we can import the data into MySQL table −
mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee12_tbl FIELDS TERMINATED BY ';';
Query OK, 2 rows affected (0.04 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0

mysql> Select * from employee12_tbl;
+------+----------------+----------+--------+
| Id   | Name           | Country  | Salary |
+------+----------------+----------+--------+
| 100  | Ram            | IND      |  15000 |
| 120  | Mohan          | IND      |  18000 |
+------+----------------+----------+--------+
2 rows in set (0.00 sec)
Create View SQL in SAP HANA database

>Create View View_name as
Select Col1,Col2 From Table_name;
In the above SQL statement, you are creating a view that contains Col1 and Col2 from the table.
Table Name − Emp_Info
                                                                                               
To create a view, which contains only 3 columns you have to write-
>Create View View_EmpInfo As
Select Id, EmplName,Joining_Date  From Emp_Info;
This view can be used by users to get Id, EmplName, and Joining_date.
MS Project - Plan Duration Cost & Time

After assigning resources to tasks you can view the cost, duration and work required for the plan to complete.
In Gantt Chart View → View Tab → Split View group → Timeline checkbox.

You will be able to see the plan’s start and finish dates.
In the Gantt Chart view, you can also look at the project summary task, to note the duration, start and finish dates of the plan.
In the following example, Assign Resources is the project summary task (identified as Task 0). Duration=53 days, Start date: 1/5/15 and Finish Date: 3/19/15.
One can switch Project Summary Task on by following these steps −
In Gantt Chart View → Format Tab → Show/Hide → To check Project Summary Task on.

Click View tab → Data group → Tables → Cost.

Cost for each task gets rolled up into summary tasks, and then ultimately to project summary task.
Click Report Tab → View Reports group → click Resources → click Resource overview

In Resource status table which appears at the bottom, you will get a summary of resource’s earliest start dates and latest finish dates as well as remaining work.
Click Project Tab → Properties group → Project Information → in
   the new dialog box click Statistics...


    32 Lectures 
     2.5 hours 

 Pavan Lalwani

    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    102 Lectures 
     10 hours 

 Pavan Lalwani

    52 Lectures 
     4 hours 

 Pavan Lalwani

    239 Lectures 
     33 hours 

 Gowthami Swarna

    53 Lectures 
     5 hours 

 Akshay Magre
 Print
 Add Notes
 Bookmark this page
How do I define string constants in C++?

To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.
#include<iostream>
#include<string>
int main() {
const std::string MY_STRING = "Hello World!";
std::cout << MY_STRING;
return 0;
}
This will give the output −
Hello World!

Note that if you try to reassign a value to this variable it'll cause an error.
Groovy - Arithmetic Operators

The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy −
int x = 5;
x++;
x will give 6
int x = 5;
x--;
x will give 4
The following code snippet shows how the various operators can be used.
class Example { 
   static void main(String[] args) { 
      // Initializing 3 variables 
      def x = 5; 
      def y = 10; 
      def z = 8; 
		
      //Performing addition of 2 operands 
      println(x+y); 
		
      //Subtracts second operand from the first 
      println(x-y); 
		
      //Multiplication of both operands 
      println(x*y);
		
      //Division of numerator by denominator 
      println(z/x); 
		
      //Modulus Operator and remainder of after an integer/float division 
      println(z%x); 
		
      //Incremental operator 
      println(x++); 
		
      //Decrementing operator 
      println(x--);  
   } 
} 
When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above.
15 
-5 
50 
1.6 
3 
5 
6


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How can we decode a JSON object in Java?

A JSON is a lightweight, text-based and language-independent data exchange format. A JSON can represent two structured types like objects and arrays. We can decode a JSON object using JSONObject and JSONArray from json.simple API. A JSONObject works as a java.util.Map whereas JSONArray works as a java.util.List.
In the below example, we can decode a JSON object.
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONDecodingTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      String str = "[ 0 , {\"1\" : { \"2\" : {\"3\" : {\"4\" : [5, { \"6\" : { \"7\" : 8 } } ] } } }    } ]";
      try {
         Object obj = parser.parse(str);
         JSONArray array = (JSONArray)obj;
         System.out.println("2nd Array element: ");
         System.out.println(array.get(1));
         System.out.println();
         JSONObject object2 = (JSONObject) array.get(1);
         System.out.println("Field \"1\"");
         System.out.println(object2.get("1"));
         str = "{}";
         obj = parser.parse(str);
         System.out.println(obj);
         str = "[6,]";
         obj = parser.parse(str);
         System.out.println(obj);
         str = "[6,,3]";
         obj = parser.parse(str);
         System.out.println(obj);
      } catch(ParseException parseExp) {
           System.out.println("Exception position: " + parseExp.getPosition());
           System.out.println(parseExp);
      }
   }
}
2nd Array element:
{"1":{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}
{}
[6]
[6,3]
Update 'a' record with 'b' and 'b' with 'a' in a MySQL column (swap) with only 'a' and 'b' values?

For this, use a CASE statement. Let us first create a table −
mysql> create table DemoTable
(
   Value char(1)
);
Query OK, 0 rows affected (1.21 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| a     |
| b     |
| a     |
| a     |
| b     |
| a     |
| b     |
+-------+
7 rows in set (0.00 sec)
Following is the query to update 'a' record with 'b' and 'b' with 'a' −
mysql> update DemoTable set Value=case when Value='a' then 'b' else 'a' end;
Query OK, 7 rows affected (0.17 sec)
Rows matched: 7 Changed: 7 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| b     |
| a     |
| b     |
| b     |
| a     |
| b     |
| a     |
+-------+
7 rows in set (0.00 sec)
Tryit Editor v3.7

Tryit: The outline-offset property
Erlang - Funs

Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below −
F = fun (Arg1, Arg2, ... ArgN) ->
   ...
End

Where
F − This is the variable name assigned to the anonymous function.
F − This is the variable name assigned to the anonymous function.
Arg1, Arg2, ... ArgN − These are the arguments which are passed to the anonymous function.
Arg1, Arg2, ... ArgN − These are the arguments which are passed to the anonymous function.
The following example showcases how the anonymous function can be used.
-module(helloworld). 
-export([start/0]). 

start() -> 
   A = fun() -> io:fwrite("Hello") end, 
   A().
The following things need to be noted about the above program.
The anonymous function is assigned to the variable A.
The anonymous function is assigned to the variable A.
The anonymous function via the variable A().
The anonymous function via the variable A().
When we run the above program we will get the following result.
“Hello”

Another example of anonymous function is as follows, but this is with the use of parameters.
-module(helloworld). 
-export([start/0]). 

start() -> 
   A = fun(X) -> 
      io:fwrite("~p~n",[X]) 
      end, 
   A(5).
When we run the above program we will get the following result.
5

The Anonymous function have the ability to access the variables which are outside of the scope of the anonymous function. Let’s look at an example of this −
-module(helloworld). 
-export([start/0]). 

start() -> 
   B = 6, 
   A = fun(X) -> 
      io:fwrite("~p~n",[X]), 
      io:fwrite("~p~n",[B]) 
      end, 
   A(5).
The following things need to be noted about the above program.
The variable B is outside of the scope of the anonymous function.
The variable B is outside of the scope of the anonymous function.
The anonymous function can still access the variable defined in the global scope.
The anonymous function can still access the variable defined in the global scope.
When we run the above program we will get the following result.
5
6

One of the other most powerful aspects of higher order functions, is that you can define a function within a function. Let’s see an example of how we can achieve this.
-module(helloworld). 
-export([start/0]). 

start() -> 
   Adder = fun(X) -> fun(Y) -> io:fwrite("~p~n",[X + Y]) end end, 
   A = Adder(6), 
   A(10).
The following things need to be noted about the above program.
Adder is a higher order function defined as fun(X).
Adder is a higher order function defined as fun(X).
The Adder function fun(X) has a reference to another function fun(Y).
The Adder function fun(X) has a reference to another function fun(Y).
When we run the above program we will get the following result.
16

 Print
 Add Notes
 Bookmark this page
Solidity – Basics of Interface

11 May, 2022
Interfaces are the same as abstract contracts created by using an interface keyword, also known as a pure abstract contract. Interfaces do not have any definition or any state variables, constructors, or any function with implementation, they only contain function declarations i.e. functions in interfaces do not have any statements. Functions of Interface can be only of type external. They can inherit from other interfaces, but they can’t inherit from other contracts. An interface can have enum, structs which can be accessed using interface name dot notation.
Example: In the below example, the contract thisContract implements an interface InterfaceExample and implements all the interface functions.
Solidity
// Solidity program to // demonstrate the working // of the interface  pragma solidity 0.4.19;  // A simple interfaceinterface InterfaceExample{      // Functions having only     // declaration not definition    function getStr(    ) public view returns(string memory);    function setValue(      uint _num1, uint _num2) public;    function add(    ) public view returns(uint);}  // Contract that implements interfacecontract thisContract is InterfaceExample{      // Private variables    uint private num1;    uint private num2;      // Function definitions of functions     // declared inside an interface    function getStr(    ) public view returns(string memory){        return "GeeksForGeeks";    }           // Function to set the values     // of the private variables    function setValue(      uint _num1, uint _num2) public{        num1 = _num1;        num2 = _num2;    }          // Function to add 2 numbers     function add(    ) public view returns(uint){        return num1 + num2;    }      }  contract call{          //Creating an object    InterfaceExample obj;      function call() public{        obj = new thisContract();    }          // Function to print string     // value and the sum value    function getValue(    ) public returns(uint){        obj.getStr;        obj.setValue(10, 16);        return obj.add();    }}
Output : 
 
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find Windows Product Key Using PowerShell?

Windows Product key can be retrieved using PowerShell or CMD. To retrieve the product key using PowerShell, we need to query SoftwareLicesingService class and there is a property called OA3xOriginalProductKey which stores the product key.
Get-WmiObject -query `select * from SoftwareLicensingService' | Select OA3xOriginalProductKey
OA3xOriginalProductKey
----------------------
BBBBB-CSDSC-EESSR-KKIDS-AAAAA
We can also query this WMI class using cmd as shown below.
wmic path softwarelicensingservice get OA3xOriginalProductKey
Caution: It may or may not work for all the Windows OS. The above is tested in Windows 10.
Create a small-caps effect for CSS

To create a small-caps effect, use the font-variant property.
You can try to run the following code to learn how to work with font-variant property in CSS:
<html>
   <head>
   </head>
   <body>
      <p style = "font-variant:small-caps;">
         Asia, Antartica, Africa are continents
      </p>
   </body>
</html>
What is a variable, field, property in Java?

In programming to hold data members we use variables, Java you can declare three types of variables namely,
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.
In addition to these, they are referred with different names based on the usage.
Fields − Variables of a class i.e. instance variables and static variables are called fields. They can’t be abstract except this you can use any other modifier with fields.
public class Sample{
   int data = 90;
   static data = 145;
}
In general, fields with private modifier, setter and getter methods are considered as properties.
public class Sample{
   private int name;
   public String getName(){
      return this.number;
   }
   public void setName(String name){
      this.name = name;
   }
}
public class Student{
   private String name;
   private int age;
   public Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getName() {
      return this.name;
   }
   public int getAge() {
      return this.age;
   }
   public static void main(String[] args){
      Student std = new Student("Krishna", 29);
      System.out.println(std.getName());
      System.out.println(std.getAge());
   }
}
Krishna
29
How to dynamically load a Python class?

There's no available function that takes a fully qualified class name and returns the class. However we can define a function that has this functionality.
The following code is of such a function.
def get_class( s ):
    parts = s.split('.')
    module = ".".join(parts[:-1])
    n = __import__( module )
    for comp in parts[1:]:
        n = getattr(m, comp)          
    return n
One usage example of that function
import datetime
def get_class( cls ):
    parts = cls.split('.')
    module = ".".join(parts[:-1])
    m = __import__( module )
    for comp in parts[1:]:
        m = getattr(m, comp)
    return m
print get_class('datetime.datetime').now()
This gives the output
2018-01-23 14:04:09.843000
Find common values between two NumPy arrays - GeeksforGeeks

29 Aug, 2020
In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear.
Syntax: numpy.intersect1d(array1,array2)
Parameter :Two arrays.
Return :An array in which all the common element will appear.
Example 1:
Python
import numpy as np    ar1 = np.array([0, 1, 2, 3, 4])ar2 = [1, 3, 4]  # Common values between two arraysprint(np.intersect1d(ar1, ar2))
Output:
[1,3,4]

Example 2:
Python
import numpy as np    ar1 = np.array([12, 14, 15, 16, 17])ar2 = [2, 4, 5, 6, 7, 8, 9, 12]  # Common values between two arraysprint(np.intersect1d(ar1, ar2))
Output:
[12]

Python numpy-arrayManipulation
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 ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
C program to print a string without any quote in the program

This is another tricky problem. In this program, we will see how to print a string using C where no quotation marks are used.
Here we are using macro function. We are defining a macro function like
#define getString(x) #x
The getString() is a macro function. It returns x by converting it into a string. The # before x is denoting that the function will convert x into a string.
Input: Take one string without quote
Output: Print that string into console
Step 1:Take a string without quote
Step 2: Use macro function to print it into a string
Step 3: End
 Live Demo
#include<stdio.h>
#define getString(x) #x
//The # will convert x into a string
main() {
   printf(getString(Hello World));
}
Hello World
Tryit Editor v3.7

Tryit: HTML style attribute
Math Operations on BigInteger in Java

Let us apply the following operations on BigInteger using the in-built methods in Java.
Addition: add() method
Subtraction: subtract() method
Multiplication: multiply() method
Division: divide() method
Let us create three BigInteger objects.
BigInteger one = new BigInteger("98765432123456789");
BigInteger two = new BigInteger("94353687526754387");
BigInteger three = new BigInteger("96489687526737667");
Apply mathematical operations on them.
one = one.add(two);
System.out.println("Addition Operation = " + one);
one = one.multiply(two);
System.out.println("Multiplication Operation = " + one);
The following is an example −
 Live Demo
import java.math.BigInteger;
public class Main {
   public static void main(String[] args) {
      BigInteger one = new BigInteger("98765432123456789");
      BigInteger two = new BigInteger("94353687526754387");
      BigInteger three = new BigInteger("96489687526737667");
      one = one.add(two);
      System.out.println("Addition Operation = " + one);
      one = one.multiply(two);
      System.out.println("Multiplication Operation = " + one);
      two = three.subtract(two);
      System.out.println("Subtract Operation = " + two);
      two = three.divide(two);
      System.out.println("Division Operation = " + two);
   }
}
Addition Operation = 193119119650211176
Multiplication Operation = 18221501070917918273532554434429112
Subtract Operation = 2135999999983280
Division Operation = 45
Display multiple lines of text in a component’s tooltip with Java

Let’s first see how we set text in a components tooltip −
JLabel label3 = new JLabel("Password", SwingConstants.CENTER);
label3.setToolTipText("Enter Password");
To display multiple lines of text in a tooltip, use <html>. Here, we have used the HTML <br> tag for new
line and that would create multiple lines of text in the tooltip −
label3.setToolTipText("<html>" + "This will create multiple lines for the" + "<br>" + "component! Yay!" + "</html>");
The following is an example to display multiple lines of text in a component’s tooltip −
package my;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame.setDefaultLookAndFeelDecorated(true);
      JFrame frame = new JFrame("Register!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label1.setToolTipText("<html>" + "Add the id given to you" + "<br>" + "in the beginning!" + "</html>");
      label2 = new JLabel("Rank", SwingConstants.CENTER);
      label2.setToolTipText("Enter rank");
      label3 = new JLabel("Password", SwingConstants.CENTER);
      label3.setToolTipText("Enter Password");
      ToolTipManager.sharedInstance().setEnabled(false);
      JTextField emailId = new JTextField(20);
      JTextField rank = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(rank);
      frame.add(passwd);
      Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
      int width = 500;
      int height = 200;
      frame.setBounds(center.x - width / 2, center.y - height / 2, width,  height);
      frame.setVisible(true);
   }
}
The output is as follows. Here, we are displaying the multi-line tooltip text visible on mouse hover −