code-rag-bench/online-tutorials huggingface dataset:
Tensorflow.js tf.GraphModel class .predict() Method

01 Aug, 2021
Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .predict() function is used to implement the implication in favor of input tensors.
Syntax:
predict(inputs, config?)
Parameters:  
inputs: It is the stated inputs. It is of type (tf.Tensor|tf.Tensor[]|{[name: string]: tf.Tensor}).
config: It is the stated prediction configuration in order to define the batch size as well as output node designations. Moreover, at present the batch size selection is overlooked for the graph model. It is optional and is of type object.batchSize: It is the stated batch dimension which is optional and is of type integer. In case its undefined, then the by default value will be 32.verbose: It is the stated verbosity mode whose by default value is false and is optional.
batchSize: It is the stated batch dimension which is optional and is of type integer. In case its undefined, then the by default value will be 32.
verbose: It is the stated verbosity mode whose by default value is false and is optional.
Return Value: It returns tf.Tensor|tf.Tensor[]|{[name: string]: tf.Tensor}.
Example 1: In this example, we are loading MobileNetV2 from a URL and holding a prediction with a zeros input.
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Defining tensor input elementsconst model_Url ='https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';  // Calling the loadGraphModel() methodconst mymodel = await tf.loadGraphModel(model_Url);  // Defining inputsconst inputs = tf.zeros([1, 224, 224, 3]);  // Calling predict() method and // Printing outputmymodel.predict(inputs).print();
Output:
Tensor
     [[-0.1800361, -0.4059965, 0.8190175, 
     ..., 
     -0.8953396, -1.0841646, 1.2912753],]
Example 2: In this example, we are loading MobileNetV2 from a TF Hub URL and holding a prediction with a zeros input.
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Defining tensor input elementsconst model_Url ='https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';  // Calling the loadGraphModel() methodconst model = await tf.loadGraphModel(        model_Url, {fromTFHub: true});  // Defining inputsconst inputs = tf.zeros([1, 224, 224, 3]);  // Defining batchsizeconst batchsize = 1;  // Defining verboseconst verbose = true;  // Calling predict() method and// Printing outputmodel.predict(inputs, batchsize, verbose).print();
Output:
Tensor
     [[-1.1690605, 0.0195426, 1.1962479, 
     ..., 
     -0.4825858, -0.0055641, 1.1937635],]
Reference: https://js.tensorflow.org/api/latest/#tf.GraphModel.predict
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream forEach() method in Java with examples

06 Dec, 2018
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Syntax :
void forEach(Consumer<? super T> action)

Where, Consumer is a functional interface
and T is the type of stream elements.

Note : The behavior of this operation is explicitly nondeterministic. Also, for any given element, the action may be performed at whatever time and in whatever thread the library chooses.
Example 1 : To perform print operation on each element of reversely sorted stream.
// Java code for forEach// (Consumer action) in Java 8import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a list of Integers        List<Integer> list = Arrays.asList(2, 4, 6, 8, 10);          // Using forEach(Consumer action) to        // print the elements of stream        // in reverse order        list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);    }}
10
8
6
4
2

Example 2 : To perform print operation on each element of string stream.
// Java code for forEach// (Consumer action) in Java 8import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a list of Strings        List<String> list = Arrays.asList("GFG", "Geeks",                                          "for", "GeeksforGeeks");          // Using forEach(Consumer action) to        // print the elements of stream        list.stream().forEach(System.out::println);    }}
GFG
Geeks
for
GeeksforGeeks

Example 3 : To perform print operation on each element of reversely sorted string stream.
// Java code for forEach// (Consumer action) in Java 8import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a Stream of Strings        Stream<String> stream = Stream.of("GFG", "Geeks",                                          "for", "GeeksforGeeks");          // Using forEach(Consumer action) to print        // Character at index 1 in reverse order        stream.sorted(Comparator.reverseOrder())            .flatMap(str -> Stream.of(str.charAt(1)))            .forEach(System.out::println);    }}
o
e
e
F

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java

Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream −
Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements.
Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements.
Source − Stream takes Collections, Arrays, or I/O resources as input source.
Source − Stream takes Collections, Arrays, or I/O resources as input source.
Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.
Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.
Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.
Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.
Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.
Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.
Let us now see an example −
 Live Demo
import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("25", "10", "15", "20", "25");
      Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
      System.out.println("Collection = "+collection);
   }
}
Collection = [100, 130, 150, 20, 200, 50, 80]
Now, let us count the number of elements in the stream using the Java streams counting() method −
 Live Demo
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam");
      // count
      long count = stream.collect(Collectors.counting());
      System.out.println("Number of elements in the stream = "+count);
   }
}
Number of elements in the stream = 5
Import a module in Python

A module is basically a file which has many lines of python code that can be referred or used by other python programs. A big python program should be organized to keep different parts of the program in different modules. That helps in all aspects like debugging, enhancements and packaging the program efficiently. To use a module in any python program we should first import it to the new program. All the functions, methods etc. from this module then will be available to the new program.
Let’s create a file named profit.py which contains program for a specific calculation as shown below.
def getprofit(cp, sp):
   result = ((sp-cp)/cp)*100
   return result
Next we want to use the above function in another python program. We can then use the import function in the new program to refer to this module and its function named getprofit.
import profit

perc=profit.getprofit(350,500)
print(perc)
Running the above code gives us the following result −
42.857142857142854
We can also import only a specific method from a module instead of the entire module. For that we use the from Module import statement as shown below. In the below example we import the value of pi from math module to be used in some calculation in the program.
from math import pi

x = 30*pi
print(x)
Running the above code gives us the following result −
94.24777960769379
If we want to know the location of various inbuilt modules we can use the sys module to find out. Similarly to know the various function available in a module we can use the dir method as shown below.
import sys
import math

print(sys.path)
print(dir(math))
Running the above code gives us the following result −
[' ',
'C:\\Windows\\system32\\python38.zip',
'C:\\Python38\\DLLs',
'C:\\Python38\\lib',
'C:\\Python38',
'C:\\Python38\\lib\\site-packages']

['.....log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod',....]
How to Install Julia on MacOS? - GeeksforGeeks

02 Jul, 2020
Julia is one of the new programming languages that is becoming popular with time. It is used mainly for scientific data calculations and mathematical analysis. It is becoming popular because it has very fast execution like C and simple syntax like python. It is an open-source language with high performance.
Julia Codes can be written, compiled, and Run on multiple platforms like BBEdit on MacOS, Jupyter, etc. Many online IDE’s are also available for Julia. For using it on your own system one can install it in the following ways:
Follow the steps given below to download and install Julia from its official site:
Step 1: Open julialang.org and start downloading .dmg file for MacOS(64bit). Step 2: Start the installation from the dmg file and move the Julia file in the application folder. Step 3: Now click on Julia icon in applications, it will open terminal as follows : Step 4: Julia is installed in your system now you can run a file with the next step.
Step 5: Now to run a sample program create a Julia file on any local IDE and save it with “.jl” extension and sample code as follows:
# sample_codeprintln("Welcome to Julia")
Step 6: Run the above file as follows
Julia can also be directly installed from the terminal by following the steps given below:
Step 1: Check for pre-installed versions: Open terminal on your Mac and type the following command:
julia
Step 2: Now download Julia (latest version) by using the following command in your terminal:
brew cask install julia
It will look like this after installation. Step 3: Now run the julia command as in point 1 and it should appear as following Step 4: Now to run a sample program go through Step 5 of Method 1.
Now, your system is ready with Julia installed to function properly.
How To
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
For loop in Julia
Arrays in Julia
Julia Dictionary
Printing Output on Screen in Julia
Vectors in Julia
Python - Filter Rows with Range Elements - GeeksforGeeks

11 Oct, 2020
Given a Matrix, filter all the rows which contain all elements in the given number range.
Input : test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows.
Input : test_list = [[3, 2, 4, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows.  
Method #1 : Using all() + list comprehension
In this, we check for all the elements in range for presence using all() and list comprehension is used for the task of iteration of elements. 
Python3
# Python3 code to demonstrate working of# Filter Rows with Range Elements# Using all() + list comprehension  # initializing listtest_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19],              [2, 5, 10], [2, 3, 4, 5, 6, 7]]  # printing original listprint("The original list is : " + str(test_list))  # initializing rangei, j = 2, 5  # checking for presence of all elements using in operatorres = [sub for sub in test_list if all(ele in sub for ele in range(i, j + 1))]  # printing resultprint("Extracted rows : " + str(res))
Output:
The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]
Method #2 : Using filter() + lambda + all()
In this, task of filtering is done using filter() and lambda function, all() is again used to ensure all elements presence in range.
Python3
# Python3 code to demonstrate working of# Filter Rows with Range Elements# Using filter() + lambda + all()  # initializing listtest_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19],             [2, 5, 10], [2, 3, 4, 5, 6, 7]]  # printing original listprint("The original list is : " + str(test_list))  # initializing rangei, j = 2, 5  # filter() and lambda used to filter elementsres = list(filter(lambda sub: all(    ele in sub for ele in range(i, j + 1)), test_list))  # printing resultprint("Extracted rows : " + str(res))
Output:
The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Binary Search (Recursive and Iterative)
Python | Split string into list of characters
Explain Regular Expression "\w" Metacharacter in Java

The subexpression/metacharacter “\w” matches the word characters i.e. a to z and A to Z and 0 to 9.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\\w to";
      String input = "Hello how are you welcome to Tutorialspoint";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}
Number of matches: 1
Following example reads 5 string values and prints those that contain word characters −
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchWordCharacters {
   public static void main( String args[] ) {
      String regex = "\\w.*$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      System.out.println("Strings that contain word characters: ");
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}
Enter 5 input strings:
sample
test
test23
hello##
#$%&&
Strings that contain word characters:
sample
test
test23
hello##
How to define a class in Arduino?

You can define a class in Arduino just like in C, with public and private variables and methods.The example below demonstrates the definition of a Student class, which has the constructor,two methods (add_science_marks and get_roll_no) and 3 private variables, _division, _roll_no and _science_marks.
class Student
{
   public:
      Student(char division, int roll_no);
      void add_science_marks(int marks);
      int get_roll_no();
   private:
      char _division;
      int _roll_no;
      int _science_marks;
};

Student::Student(char division, int roll_no){
   _division = division;
   _roll_no = roll_no;
}

void Student::add_science_marks(int marks){
   _science_marks = marks;
}

int Student::get_roll_no(){
   return _roll_no;
}

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   Student Yash('A',26);

   Serial.print("Roll number of the student is: ");
   Serial.println(Yash.get_roll_no());
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
The class declaration in the above code could have well been within a Student.h file, and the function definitions within Student.cpp file. This way, you can define your own library in Arduino.
Word Ladder (Length of shortest chain to reach a target word) in C++

In this problem, we are given a dictionary and two words ‘start’ and ‘target’. Our task is to generate a chain (ladder) from start work to target word, the chain is created such that each word differs the other character by only one word and the word should also exist in the dictionary. The target word exists in the dictionary and also the length of all words is the same. The program will return the length of the shortest path from start to target.
Let’s take an example to understand the problem,
Dictionary = {‘HEAL’, ‘HATE’, ‘HEAT’, ‘TEAT’, ‘THAT’, ‘WHAT’ , ‘HAIL’ ‘THAE’}
Start = ‘HELL’
Target = ‘THAE’
6
HELL - HEAL - HEAT - TEAT - THAT - THAE
To solve this problem, we will do Breadth-first search of the dictionary. Now, step by step find all elements that are one letter away from the previous character. And create a ladder from start to target.
Program to show the implementation of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int wordLadder(string start, string target, set<string>& dictionary) {
   if (dictionary.find(target) == dictionary.end())
   return 0;
   int level = 0, wordlength = start.size();
   queue<string> ladder;
   ladder.push(start);
   while (!ladder.empty()) {
      ++level;
      int sizeOfLadder = ladder.size();
      for (int i = 0; i < sizeOfLadder; ++i) {
         string word = ladder.front();
         ladder.pop();
         for (int pos = 0; pos < wordlength; ++pos) {
            char orig_char = word[pos];
            for (char c = 'a'; c <= 'z'; ++c) {
               word[pos] = c;
               if (word == target)
                  return level + 1;
               if (dictionary.find(word) == dictionary.end())
                  continue;
               dictionary.erase(word);
               ladder.push(word);
            }
            word[pos] = orig_char;
         }
      }
   }
   return 0;
}
int main() {
   set<string> dictionary;
   dictionary.insert("heal");
   dictionary.insert("heat");
   dictionary.insert("teat");
   dictionary.insert("that");
   dictionary.insert("what");
   dictionary.insert("thae");
   dictionary.insert("hlle");
   string start = "hell";
   string target = "thae";
   cout<<"Length of shortest chain from '"<<start<<"' to '"<<target<<"' is: "<<wordLadder(start, target, dictionary);
   return 0;
}
Length of shortest chain from 'hell' to 'thae' is: 6
How to initialize a dictionary to an empty dictionary in C#?

To initialize a dictionary to an empty dictionary, use the Clear() method. It clears the dictionary and forms it as empty.
dict.Clear();
After that, use the Dictionary count property to check whether the list is empty or not −
if (dict.Count == 0) {
   Console.WriteLine("Dictionary is empty!");
}
Let us see the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {

         var dict = new Dictionary < string, string > ();
         dict.Clear();
         if (dict.Count == 0) {
            Console.WriteLine("Dictionary is empty!");
         }
      }
   }
}
Dictionary is empty!
How to clear console in C language? - GeeksforGeeks

28 Oct, 2020
It is one of the basic need a program may required i.e clear the console during execution time.There is function named clrscr() which is included in conio.h and is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX.So what should we use there? There are two more ways to clear console: 
By Using system(“clear”)By using a regex “\e[1;1H\e[2J”
By Using system(“clear”)
By using a regex “\e[1;1H\e[2J”
Now question arises which should we use and why: Using regex is a better way.The reason is its faster execution. By using regex we can perform clear screen operation very fastly in comparison to using system(“clear”). Below c program will demonstrate how fast regex is then the system(“clear”) The system(“clear”) is included in stdlib.h and also work only in linux system to use this in window use system(“cls”). 
C
// C program for clearing console and// comparing two different methods#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){    int i = 0;    double time_taken;    clock_t t1, t2;     // a loop for showing geeks for geeks    // repeating by clearing console using    // system("clear")     // Noting start time    t1 = clock();    for (i; i < 10000; i++)    {        system("clear");        printf("geeks for geeks %d\n", i);    }     // Calculating total time taken by    // system("clear")    t1 = clock() - t1;     i = 0;    // Noting start time of regex    t2 = clock();    for (i; i < 10000; i++)    {        printf("\e[1;1H\e[2J");        printf("geeks for geeks %d\n", i);    }     // calculating total time taken by regex    t2 = clock() - t2;     // printing taken by both    printf("Time taken by system\(\"clear\") %f\n",           ((double)t1) / CLOCKS_PER_SEC);    printf("Time taken regex %f",           ((double)t2) / CLOCKS_PER_SEC);     return 0;}
Output:
geeks for geeks 9999
Time taken by system("clear") 0.934388
Time taken by regex 0.000001

NOTE:The output time may differ but the difference in both time will always be large.And also run this program only in your system’s console not here. 
nidhi_biet
Akanksha_Rai
sidharthkanwaria
c-input-output
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
UDP Server-Client implementation in C
Understanding "extern" keyword in C
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
How to split a string in C/C++, Python and Java?
Create a Pandas DataFrame from List of Dicts - GeeksforGeeks

17 Dec, 2018
Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object.
Pandas DataFrame can be created in multiple ways. Let’s discuss how to create a Pandas DataFrame from List of Dicts.
Code #1:
# Python code demonstrate how to create  # Pandas DataFrame by lists of dicts. import pandas as pd     # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},        {'Geeks':10, 'For': 20, 'geeks': 30}]     # Creates DataFrame. df = pd.DataFrame(data)     # Print the data df 
Output:
 
Code #2: With index
# Python code demonstrate how to create  # Pandas DataFrame by lists of dicts. import pandas as pd     # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},        {'Geeks':10, 'For': 20, 'geeks': 30}]     # Creates DataFrame. df = pd.DataFrame(data, index =['ind1', 'ind2'])     # Print the data df 
Output: 
Code #3: With index and columns
# Python code demonstrate how to create  # Pandas DataFrame by lists of dicts. import pandas as pd     # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},        {'Geeks':10, 'For': 20, 'geeks': 30}]     # With two column indices, values same  # as dictionary keys df1 = pd.DataFrame(data, index =['ind1', 'ind2'],                      columns =['Geeks', 'For'])      # With two column indices with  # one index with other name df2 = pd.DataFrame(data, index =['indx', 'indy'])      # print for first data frame print (df1, "\n")      # Print for second DataFrame. print (df2) 
Output:
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
How can CONCAT() function be used with MySQL WHERE clause?

Suppose from the table ‘Student’ we want to concatenate the values of columns, ‘Name’, ‘Address’ and ‘Columns’, based on the condition that is also a concatenation of values from columns, ’Name’, ‘Subject’, provided in WHERE clause with the help of CONCAT() function. We can use the following query to give the output −
mysql> Select CONCAT(Name, ' ', 'Resident of', ' ', Address,' ','is',' ', 'Studying',' ', Subject)AS 'Detail of Student' from Student WHERE CONCAT(Name, Subject) = "AaravHistory";
+----------------------------------------------+
| Detail of Student                            |
+----------------------------------------------+
| Aarav Resident of Mumbai is Studying History |
+----------------------------------------------+
1 row in set (0.00 sec)
SQL Query to convert NUMERIC to NVARCHAR - GeeksforGeeks

15 May, 2021
Here we will see, how to convert NUMERIC data to NVARCHAR data in a MS SQL Server’s database table using the CAST(), CONVERT() and FORMAT() functions.
We will be creating a person table in a database called “geeks”.
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE person(
id INT IDENTITY(1,1) PRIMARY KEY,
name VARCHAR(30) NOT NULL,
weight NUMERIC(10,5) NOT NULL);
--Here NUMERIC(10,5) says there should be total 10 digits given that 5 digits would be 
--to the right of the decimal point.
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS person;
Use the below statement to add data to the person table:
INSERT INTO person
VALUES
('Yogesh Vaishnav', 62.5),
('Vishal Vishwakarma', 70),
('Ashish Yadav', 69),
('Ajit Yadav', 71.9);
To verify the contents of the table use the below statement:
SELECT * FROM person;
Now let’s convert NUMBERIC values to NVARCHAR using three different methods.
Using the CONVERT() function:
Syntax: SELECT CONVERT(<DATA_TYPE>, <VALUE>);
--DATA_TYPE is the type we want to convert to.
--VALUE is the value we want to convert into DATA_TYPE.
Example:
SELECT 'Weight of Yogesh Vaishnav is ' + CONVERT(NVARCHAR(20), weight)
AS person_weight
FROM person
WHERE name = 'Yogesh Vaishnav';
As you can see that there are total 5 digits to the right side of the decimal point as discussed above.
Using the CAST() function:
Syntax: SELECT CAST(<VALUE> AS <DATA_TYPE>);
--DATA_TYPE is the type we want to convert to.
--VALUE is the value we want to convert into DATA_TYPE
Example:
SELECT 'Weight of Ajit Yadav is ' + CAST(weight as NVARCHAR(20))
AS person_weight
FROM person
WHERE name = 'Ajit Yadav';
Using the FORMAT() function:
Although FORMAT() function is useful for formatting datetime and not converting one type into another, but still can be used to convert(or here format) float value into an STR value.
Syntax: SELECT FORMAT(<VALUE> , 'actual_format';
--actual_format is the format we want to achieve in a string form.
--VALUE is the value we want to format according to the actual_format.
Example:
SELECT 'Weight of Ashish Yadav is ' + FORMAT(weight, '') --'' denotes no formating
--i.e simply convert it to a string of characters.
AS person_weight
FROM person
WHERE name = 'Ashish Yadav';
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
Decimal.Negate() Method in C# - GeeksforGeeks

30 Jan, 2019
This method is used to get the result of multiplying the specified Decimal value by negative one.
Syntax: public static decimal Negate (decimal a);
Parameter:a: This parameter specifies the decimal which will be converted.
Return Value: A decimal number with the value of a, but the opposite sign. But zero, if a is zero.
Below programs illustrate the use of Decimal.Negate(Decimal) Method:
Example 1: When a is positive
// C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring the decimal variable        Decimal a = 127.97m;          // using Negate() method;        Decimal value = Decimal.Negate(a);          // Display the negative value        Console.WriteLine("The negative value "+                             "is : {0}", value);    }}
The negative value is : -127.97

Example 2: When a is negative
// C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring the decimal variable        Decimal a = -12.39m;          // using Negate() method;        Decimal value = Decimal.Negate(a);          // Display the value after        // using negate method        Console.WriteLine("The value is : {0}",                                        value);    }}
The value is : 12.39

Example 3: If a is zero.
// C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring the decimal variable        Decimal a = 0.00m;          // using Negate() method;        Decimal value = Decimal.Negate(a);          // Display the Negate value        Console.WriteLine("The Negate value "+                           "is : {0}", value);    }}
The Negate value is : 0.00

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.negate?view=netframework-4.7.2
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Delegates
Introduction to .NET Framework
C# Dictionary with examples
Difference between Ref and Out keywords in C#
Partial Classes in C#
Extension Method in C#
Top 50 C# Interview Questions & Answers
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
Different ways to sort an array in descending order in C#
Lambda Expressions in C#
Binary Tree Inorder Traversal in Python

Suppose we have a binary tree. We have to traverse this tree using the inorder traversal scheme without using recursion. So if the tree is like
Then the traversal will be [2,5,7,10,15,20]
To solve this, we will follow these steps −
Create two array res and stack, set curr := root
Run one infinite loopwhile current is not nullpush curr into a stack, and set curr := left of currwhen the length of stack = 0, then return resnode := popped element from the stackinsert a value of node into rescurr := right of curr
while current is not nullpush curr into a stack, and set curr := left of curr
push curr into a stack, and set curr := left of curr
when the length of stack = 0, then return res
node := popped element from the stack
insert a value of node into res
curr := right of curr
Let us see the following implementation to get a better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         temp.left = TreeNode(data)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         temp.right = TreeNode(data)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def inorderTraversal(self, root):
      res, stack = [], []
      current = root
      while True:
         while current:
            stack.append(current)
            current = current.left
         if len(stack) == 0:
            return res
         node = stack[-1]
         stack.pop(len(stack)-1)
         if node.data != None:
            res.append(node.data)
         current = node.right
      return res
ob1 = Solution()
root = make_tree([10,5,15,2,7,None,20])
print(ob1.inorderTraversal(root))
[10,5,15,2,7,null,20]
[2,5,7,10,15,20]
How to run a JAR file through command prompt in java?

For packaging of class files Java provides a file format known as JAR (Java Archive). Typically, a JAR file contains .class files, images, text files, libraries that are required to execute the application or, library.
This file format is used to distribute application software and libraries in Java. All the predefined libraries are available in this format.
If you have any library in this format to use it In your application either you need to place it in the current (or, lib) folder of the project or, you need to set the class path for that particular JAR file.
Java provides jar command to work with jar files if you execute it in the command prompt you will get the execution syntax and options of this command as shown below −
C:\>jar
Usage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
   -c create new archive
   -t list table of contents for archive
   -x extract named (or all) files from archive
   -u update existing archive
   -v generate verbose output on standard output
   -f specify archive file name
   -m include manifest information from specified manifest file
   -n perform Pack200 normalization after creating a new archive
   -e specify application entry point for stand-alone application bundled into an executable jar file
   -0 store only; use no ZIP compression
   -P preserve leading '/' (absolute path) and ".." (parent directory) components from file names
   -M do not create a manifest file for the entries
   -i generate index information for the specified jar files
   -C change to the specified directory and include the following file
You can create a JAR file using by executing this command with the options c, v, f Following is the syntax to create a JAR file using command prompt −
jar cvf jar_file_name output_path
Create a java file with name Sample.java in the path D:/example, copy and paste the following program in it −
public class Sample {
   public static void main(String args[]){
      System.out.println("Hi welcome to Tutorialspoint");
   }
}
Compile the above program using the javac command as −
javac Example.java
If your program gets executed without errors .class file will be generated in the current folder. Now, create a jar file for the generated class as −
C:\Sample>jar cvf sample.jar *.class
added manifest
adding: Sample.class(in = 434) (out= 302) (deflated 30%)
Once you execute a JAR file is generated with the specified name.
You can also create JAR files using IDE’s. To create a JAR file using eclipse follow the procedure given below −
Open eclipse, create a project in it as −
Open eclipse, create a project in it as −
Right Click on the project folder and select the Export option as −
Right Click on the project folder and select the Export option as −
Under the Java category select JAR file.
Under the Java category select JAR file.
Click on Next.
Click on Next.
Enter the JAR file name and folder.
Enter the JAR file name and folder.
Click on Finish.
Click on Finish.
Python selenium browser driver.back().

We can navigate back in the browser with Selenium webdriver. There are multiple ways to achieve this. The back() method is used to move back to the prior browser page. This method only is applicable if we jump from webpage to another.
We can also move back in the browser with the help of a Javascript Executor in Selenium. It has the execute_script() method which allows Selenium to run Javascript commands. We have to execute the Javascript command window.history.go(-1) to go back to the previous page.
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch a webpage
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
print("Current Page title: " + driver.title)
#launch another webpage
driver.get("https://www.tutorialspoint.com/questions/index.php")
print("Current Page title: " + driver.title)
#back to previous page with back()
driver.back()
print("Current Page title after back: " + driver.title)
Code Implementation with Javascript Executor.
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch a webpage
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
print("Current Page title: " + driver.title)
#launch another webpage
driver.get("https://www.tutorialspoint.com/questions/index.php")
print("Current Page title: " + driver.title)
#back to previous page with execute_script()
driver.execute_script("window.history.go(-1)")
print("Current Page title after back: " + driver.title)
YACC program to recognize strings of { anb | n≥5 }

07 May, 2019
Problem: Write YACC program to recognize strings of { anb | n≥5 }
Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc.
Examples:
Input: ab
Output: invalid string

Input: aaaaab
Output: valid string

Input: aabb
Output: invalid string

Input: aaaaaaab
Output: valid string

Input: aaaaaabb
Output: invalid string 
Lexical Analyzer Source Code:
%{   /* Definition section */  #include "y.tab.h" %}  /* Rule Section */ %%[aA] {return A;}[bB] {return B;}\n {return NL;}.   {return yytext[0];} %%  int yywrap()  {    return 1;  } 
Parser Source Code:
%{   /* Definition section */  #include<stdio.h>  #include<stdlib.h> %}  %token A B NL  /* Rule Section */%%stmt: A A A A A S B NL {printf("valid string\n");             exit(0);};S: S A|;%%  int yyerror(char *msg) {  printf("invalid string\n");  exit(0); }    //driver code main() {  printf("enter the string\n");  yyparse(); }
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Issues in the design of a code generator
Peephole Optimization in Compiler Design
Code Optimization in Compiler Design
Type Checking in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Difference between Compiler and Interpreter
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Introduction of Compiler Design
Runtime Environments in Compiler Design
Print numbers in matrix diagonal pattern in C Program.

The task is to print the matrix of n x n of the diagonal pattern.
If n is 3 then to print a matrix in Diagonal pattern is −
So the output will be like −
Input: 3
Output:
   1 2 4
   3 5 7
   6 8 9
Input: 4
Output:
   1 2 4  7
   3 5 8 11
   6 9 12 14
   10 13 15 16
The problem suggests we have to give a number n and generate a matrix of n x n and then we have to traverse the matrix in a diagonal pattern and store the values in a separate matrix.
But this will increase the complexity of our code, so we will −
Create a matrix of size N X N which will store the pattern before printing.
Create a matrix of size N X N which will store the pattern before printing.
Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal.
Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal.
Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal.
Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal.
int printdiagonal(int n)
START
STEP 1: DECLARE int mat[n][n], i, j, k, d=1, m
STEP 2: LOOP FOR i = 0 AND i < n AND i++
   ASSIGN j AS i AND k AS 0
   LOOP FOR j = I AND j >= 0 AND j--
      ASSIGN mat[k][j] AS d
      INCREMENT d AND k BY 1
   END LOOP
END LOOP
STEP 3: LOOP FOR k = 1 AND k < n AND k++
   ASSIGN i AND m EQUALS TO k
   LOOP FOR j = n-1 AND j >= m AND j--
      ASSIGN mat[i][j] AS d;
      INCREMENT d AND i WITH 1
   END FOR
END FOR
STEP 4: LOOP FOR i = 0 AND i < n AND i++
   LOOP FOR j = 0 AND j < n AND j++
      PRINT mat[i][j]
   END FOR
   PRINT NEWLINE
END FOR
STOP
#include <stdio.h>
int printdiagonal(int n){
   int mat[n][n], i, j, k, d=1, m;
   for ( i = 0; i < n; i++){
      j = i;
      k = 0;
      for ( j = i; j >= 0; j--){
         mat[k][j] = d;
         d++;
         k++;
      }
   }
   for ( k = 1; k < n; k++){
      i = m = k;
      for ( j = n-1; j >= m; j--){
         mat[i][j] = d;
         d++;
         i++;
      }
   }
   for ( i = 0; i < n; i++){
      for(j = 0; j < n; j++){
         printf("%d ", mat[i][j] );
      }
      printf("\n");
   }
}
int main(int argc, char const *argv[]){
   int n = 3;
   printdiagonal(n);
   return 0;
}
If we run the above program then it will generate the following output −
1 2 4
3 5 7
6 8 9
strings.ToValidUTF8() Function in Golang With Examples

17 May, 2020
strings.ToValidUTF8() Function in Golang is used to returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.
Syntax:
func ToValidUTF8(str, rep string) string

Here, str is string which may contain invalid UTF-8 and rep is the replacement string.
Return Value: It returns the replaced string.
Example 1:
// Golang program to show the usage// of strings.ToValidUTF8() Functionpackage main  // importing fmt and stringsimport (    "fmt"    "strings")  // calling main methodfunc main() {      // There is no invalid UTF-8 character    // present, so the same string returned    fmt.Print(strings.ToValidUTF8("This is GeeksForGeeks", " "))}
Output:
This is GeeksForGeeks

Example 2:
// Golang program to show the usage// of strings.ToValidUTF8() Functionpackage main  // importing fmt and stringsimport (    "fmt"    "strings")  // calling main methodfunc main() {      // Invalid UTF-8 '\xc5' replaced by 'For'    fmt.Print(strings.ToValidUTF8("Geeks\xc5Geeks", "For"))}
Output:
GeeksForGeeks

Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Structures in Golang
Strings in Golang
Go Variables
time.Parse() Function in Golang With Examples
Class and Object in Golang
How to use WebView in Android

04 Jan, 2022
public class WebView 
extends AbsoluteLayout 
implements 
    ViewTreeObserver.OnGlobalFocusChangeListener, 
    ViewGroup.OnHierarchyChangeListener

WebView is a view that display web pages inside the application. It is used to turn the application into a web application.
Class Hierarchy :
java.lang.Object
   ↳  android.view.View
        ↳  android.view.ViewGroup
             ↳  android.widget.AbsoluteLayout
                  ↳  android.webkit.WebView

MainActivity.java
Java
package com.example.hp.webview;  import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.webkit.WebView;import android.webkit.WebViewClient;  public class MainActivity extends AppCompatActivity {      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                  // Binding MainActivity.java with         // activity_main.xml file        setContentView(R.layout.activity_main);                  // Find the WebView by its unique ID        WebView w = (WebView) findViewById(R.id.web);                  // loading http://www.google.com url in the the WebView.        w.loadUrl("http://www.google.com");                  // this will enable the javascript.        w.getSettings().setJavaScriptEnabled(true);                  // WebViewClient allows you to handle         // onPageFinished and override Url loading.        w.setWebViewClient(new WebViewClient());              }}
 activity_main.xml
In the xml file only use of WebView is made inside RelativeLayout.
xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.hp.webview.MainActivity">      <WebView        <!-- covers 368dp width as required. -->        android:layout_width="368dp"                  <!-- unique ID of WebView -->        android:id="@+id/web"                  <!-- covers 495dp height as required. -->        android:layout_height="495dp"                  tools:layout_editor_absoluteX="8dp"        tools:layout_editor_absoluteY="8dp" /></RelativeLayout>
In AndroidManifest.xml, one needs to include below permission, in order to access internet:
"uses-permission android:name="android.permission.INTERNET"

prachisoda1234
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.