code-rag-bench/online-tutorials huggingface dataset:
How to reset selected file with input tag file type in Angular 9?

30 Jun, 2020
To reset the selected file with input tag file type, we can implement a method which on invocation will clear the selected file.
Approach:
Set the id of your input using ‘#’ to make it readable  inside the component.
Now in the component we can use ViewChild directive to read the value of the input from the HTML view.
For that, import ViewChild from @angular/core.
import { ViewChild } from '@angular/core';
ViewChild allows you to set a reference variable to your input, using that you can clear the value of input.
After clearing the value of input using the reference variable, the selected file will be reset.
Example:
We will create a similar scenario, there will be an input field and the task will be to create a button which on click will reset the selected file.
Javascript
import { Component,ViewChild,ElementRef } from '@angular/core';  @Component({  selector: 'app-root',  template: `  <div style="text-align: center;">  <h1>    {{title}}  </h1>  <input #takeInput type="file" name="filename">      <!--After clicking this button the file should be reset.-->      <button (click)="reset()">Clear</button>  </div>  `,  styleUrls: []})export class AppComponent {  title = 'Tutorial';   // ViewChild is used to access the input element.    @ViewChild('takeInput', {static: false})    // this InputVar is a reference to our input.    InputVar: ElementRef;    reset()   {    // We will clear the value of the input // field using the reference variable.      this.InputVar.nativeElement.value = "";  }}
Output:
After selecting the file:
After pressing clear button:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to scroll a specific DIV using Selenium WebDriver with Java?

We can scroll a specific DIV using Selenium webdriver. Selenium cannot handle scrolling directly. It takes the help of the Javascript Executor to do scrolling action to a specific DIV.
First of all we have to identify the specific DIV up to which we have to scroll to with the help of xpath or css locator. Next we shall take the help of the Javascript Executor to run the Javascript commands. The method executeScript is used to execute Javascript commands in Selenium. We have to use the scrollIntoView method in Javascript and pass true as an argument to the method.
WebElement m=driver.findElement(By.xpath("//div[@class='slick-track']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", m);
Code Implementation.
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 org.openqa.selenium.JavascriptExecutor;
public class ScrollToDiv{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//div[@class='slick-track']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", m);
      Thread.sleep(800);
      driver.quit();
   }
}
Batch Script - FORMAT

This batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk.
format [drive]

Where drive is the drive which needs to be formatted.
@echo off 
format D:\
With the above command, D drive will be formatted.
 Print
 Add Notes
 Bookmark this page
C++ Program to Calculate Power of a Number

The power of a number can be calculated as x^y where x is the number and y is its power.
For example.
Let’s say, x = 2 and y = 10
   x^y =1024
   Here, x^y is 2^10



Power of a number can be calculated using recursive and non-recursive programs. Each of these are given as follows.
The program to find the power of a number using a non-recursive program is given as follows −
 Live Demo
#include<iostream>
using namespace std;
int power(int x, int y) {
   int i,power=1;
   if(y == 0)
   return 1;
   for(i=1;i<=y;i++)
   power=power*x;
   return power;
}
int main() {
   int x = 3;
   int y = 4;
   cout<<"x = "<<x<<endl;;
   cout<<"y = "<<y<<endl;
   cout<<"x^y = "<<power(x,y);
   return 0;
}
x = 3
y = 4
x^y = 81
In the above program, the function power() is used to calculate the power of a number. It is a non-recursive function. In the function, a for loop is used which runs from 1 to y. For each iteration of the loop, x is multiplied with power.
So, x is multiplied with itself y times and the result is stored in power. This leads to x^y being stored in power. Then power is returned to the main() function.
The following code snippet demonstrates this −
int power(int x, int y) {
   int i, power = 1;
   if(y==0)
   return 1;
   for(i=1;i<=y;i++)
   power = power*x;
   return power;
}
In main(), the values of x, y and x^y are displayed. This is shown in the code snippet given below −
cout<<"x = "<<x<<endl;;
cout<<"y = "<<y<<endl;
cout<<"x^y = "<<power(x,y);
The program to find the power of a number using a recursive program is given as follows.
 Live Demo
#include<iostream>
using namespace std;
int power(int x, int y) {
   if (y == 0)
   return 1;
   else if (y%2 == 0)
   return power(x, y/2)*power(x, y/2);
   else
   return x*power(x, y/2)*power(x, y/2);
}
int main() {
   int x = 3;
   int y = 4;
   cout<<"x = "<<x<<endl;;
   cout<<"y = "<<y<<endl;
   cout<<"x^y = "<<power(x,y);
   return 0;
}
x = 3
y = 4
x^y = 81
In the above program, power() is a recursive function. If the value of y is 0, it returns 1. If y is even, it recursively calls itself with the values x and y/2 and returns power(x, y/2)*power(x, y/2). If y is odd, it recursively calls itself with the values x and y/2 and returns x*power(x, y/2)*power(x, y/2). This is demonstrated by the following code snippet.
int power(int x, int y) {
   if (y == 0)
   return 1;
   else if (y%2 == 0)
   return power(x, y/2)*power(x, y/2);
   else
   return x*power(x, y/2)*power(x, y/2);
}
In main(), the values of x, y and x^y are displayed. This is shown in the code snippet given below.
cout<<"x = "<<x<<endl;;
cout<<"y = "<<y<<endl;
cout<<"x^y = "<<power(x,y);
Python | Pandas.pivot_table()

28 Sep, 2018
pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc=’mean’, fill_value=None, margins=False, dropna=True, margins_name=’All’) create a spreadsheet-style pivot table as a DataFrame.
Levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.
Parameters:
data : DataFramevalues : column to aggregate, optionalindex: column, Grouper, array, or list of the previouscolumns: column, Grouper, array, or list of the previous
aggfunc: function, list of functions, dict, default numpy.mean-> If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names.-> If dict is passed, the key is column to aggregate and value is function or list of functions
fill_value[scalar, default None] : Value to replace missing values withmargins[boolean, default False] : Add all row / columns (e.g. for subtotal / grand totals)dropna[boolean, default True] : Do not include columns whose entries are all NaNmargins_name[string, default ‘All’] : Name of the row / column that will contain the totals when margins is True.
Returns: DataFrame
Code:
# Create a simple dataframe   # importing pandas as pdimport pandas as pdimport numpy as np   # creating a dataframedf = pd.DataFrame({'A': ['John', 'Boby', 'Mina', 'Peter', 'Nicky'],      'B': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'],      'C': [27, 23, 21, 23, 24]})   df
 
# Simplest pivot table must have a dataframe# and an index/list of index.table = pd.pivot_table(df, index =['A', 'B'])  table
 
# Creates a pivot table dataframetable = pd.pivot_table(df, values ='A', index =['B', 'C'],                         columns =['B'], aggfunc = np.sum)  table
Python pandas-basics
Python pandas-dataFrame
Python-pandas
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Network Layer - GeeksforGeeks

02 Dec, 2021
See http://www.geeksforgeeks.org/computer-networks-set-2/
See Question 3 of http://www.geeksforgeeks.org/computer-networks-set-3/
[S1] The computational overhead in link state protocols 
     is higher than in distance vector protocols.
[S2] A distance vector protocol (with split horizon) 
     avoids persistent routing loops, but not a link
     state protocol.
[S3] After a topology change, a link state protocol 
     will converge faster than a distance vector
     protocol.
Link-state:
Every node collects complete graph structure
Each computes shortest paths from it
Each generates own routing table

Distance-vector
No one has copy of graph
Nodes construct their own tables iteratively
Each sends information about its table to neighbors 
[S1] The computational overhead in link state protocols 
     is higher than in distance vector protocols.
[S2] A distance vector protocol (with split horizon) 
     avoids persistent routing loops, but not a link
     state protocol.
[S3] After a topology change, a link state protocol 
     will converge faster than a distance vector
     protocol.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
PostgreSQL – List Indexes

22 Jul, 2021
In PostgreSQL, we use the pr_indexes view to list the indexes of a database. PostgreSQL does not provide a command like SHOW INDEXES to list the index information of a table or database. If you use psql to access the PostgreSQL database, you can use the \d command to view the index information for a table.
The pg_indexes view allows you to access useful information on each index in the PostgreSQL database. The pg_indexes view consists of five columns:
schemaname: stores the name of the schema that contains tables and indexes.
tablename: stores name of the table to which the index belongs.
indexname: stores name of the index.
tablespace: stores name of the tablespace that contains indexes.
indexdef: stores index definition command in the form of CREATE INDEX statement.
Example 1:
The following statement lists all indexes of the schema public in the current database:
SELECT
    tablename,
    indexname,
    indexdef
FROM
    pg_indexes
WHERE
    schemaname = 'public'
ORDER BY
    tablename,
    indexname;
Output:
Example 2:
The following statement lists all the indexes for the customer table, you use the following statement:
SELECT
    indexname,
    indexdef
FROM
    pg_indexes
WHERE
    tablename = 'customer';
Output:
The below syntax is used to list all the indexes of a table using psql command:
Syntax: \d table_name;
Example 1:
Here we will list all the indexes of the customer table of the sample database as shown below:
\d customer;
Output:
Example 2:
Here we will list all the indexes of the film table of the sample database as shown below:
\d film;
Output:
rajeev0719singh
postgreSQL-indexes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Sub queries in From Clause

11 Apr, 2022
From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied.  
Sub queries in the from clause are supported by most of the SQL implementations.
The correlation variables from the relations in from clause cannot be used in the sub-queries in the from clause.
Syntax: 
 
SELECT column1, column2 FROM 
(SELECT column_x  as C1, column_y FROM table WHERE PREDICATE_X)
as table2, table1
WHERE PREDICATE;
Note: The sub-query in the from clause is evaluated first and then the results of evaluation are stored in a new temporary relation. Next, the outer query is evaluated, selecting only those tuples from the temporary relation that satisfies the predicate in the where clause of the outer query. 
 
Query
Example 1: Find all professors whose salary is greater than the average budget of all the departments. 
Instructor relation:  
Department relation:  
Query:  
select I.ID, I.NAME, I.DEPARTMENT, I.SALARY from
(select avg(BUDGET) as averageBudget from DEPARTMENT) as BUDGET, Instructor as I
where I.SALARY > BUDGET.averageBudget;
Output  
Explanation: The average budget of all departments from the department relation is 70000. Erik and Smith are the only instructors in the instructor relation whose salary is more than 70000 and therefore are present in the output relation. 
 
Dharmesh Singh 2
19eucs091
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Fluttertoast in Flutter

20 Jun, 2022
Fluttertoast is used to create a toast message by writing only one line of code. Below are some steps to create a Fluttertoast in Flutter. Basically here, we are creating a new Flutter application using a command prompt.
Delete the default code from the main.dart file and write your own code.
Now, add fluttertoast in dependencies of the pubspec.yaml file:
Some Properties of showToast:
msg: toast message.
toastLength: Duration of toast
backgroundColor: Background color to be shown.
textColor: Text color to be shown.
fontSize: Font size of toast message.
Example: main.dart
Dart
import 'package:flutter/material.dart';import 'package:fluttertoast/fluttertoast.dart'; void main() {  runApp(const MyApp());} class MyApp extends StatelessWidget {  const MyApp({Key? key}) : super(key: key); // This widget is the// root of your application.  @override  Widget build(BuildContext context) {    return MaterialApp(      title: "Flutter Demo",      theme: ThemeData(        primarySwatch: Colors.blue,      ),      debugShowCheckedModeBanner: false,      home: const MyHomePage(),    );  }} class MyHomePage extends StatefulWidget {  const MyHomePage({Key? key}) : super(key: key);   @override// ignore: library_private_types_in_public_api  _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> {  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: const Text("GeeksforGeeks"),        backgroundColor: Colors.green,      ),      body: Center(        child: TextButton(          onPressed: () {            Fluttertoast.showToast(              msg: 'GeeksforGeeks',              backgroundColor: Colors.grey,            );          },          child: Container(            padding: const EdgeInsets.all(14),            color: Colors.green,            child: const Text(              'Show Toast',              style: TextStyle(color: Colors.white),            ),          ),        ),         // FlatButton is deprecated. Use TextButton instead.         // child: FlatButton(        //   color: Colors.blue,        //   onPressed: () {        //     Fluttertoast.showToast(        //       msg: "GeeksforGeeks",        //       backgroundColor: Colors.grey,        //       // fontSize: 25        //       // gravity: ToastGravity.TOP,        //       // textColor: Colors.pink        //     );        //   },        //   child:        //       const Text("Show toast", style: TextStyle(color: Colors.white)),        // ),      ),    );  }}
Output:
If the font size is set to 25 the design changes as follows:
If the font size is set to 25 and gravity is set to  ToastGravity.TOP the design changes as follows:
If the font size is set to 25 and gravity is set to ToastGravity.TOP and text color is set to pink the design changes as follows:
ankit_kumar_
android
Flutter
Flutter UI-components
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove particular element from tuple list

28 Aug, 2019
Since the advent of popularity of Python in data analysis, we have list of tuples as a container in many of our problems. Sometimes, while data preprocessing, we might have a problem in which we need to completely remove a particular element from a list of tuple. Let’s discuss a way in which this task can be performed.
Method : Using list comprehensionThis task can be used using brute force manner using loop, but a better alternative shorthand would be an approach which could perform this task in one line. List comprehension can help us achieve it and hence it’s recommended to use this method to perform this task. This just checks for element and removes if it’s the selected element.
# Python3 code to demonstrate working of# Remove particular element from tuple list# using list comprehension  # initialize listtest_list = [(5, 6, 7), (7, 2, 4, 6), (6, 6, 7), (6, 10, 8)]  # printing original listprint("The original list is : " + str(test_list))  # declaring remove elementN = 6  # Remove particular element from tuple list# using list comprehensionres = [tuple(ele for ele in sub if ele != N) for sub in test_list]  # printing resultprint("The Tuple List after removal of element : " + str(res))
The original list is : [(5, 6, 7), (7, 2, 4, 6), (6, 6, 7), (6, 10, 8)]
The Tuple List after removal of element : [(5, 7), (7, 2, 4), (7, ), (10, 8)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Get sum of last K list items using slice

12 Jul, 2021
Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last K elements and do its summation. Let’s discuss certain solution to perform this task.Method #1 : Using list slicing + sum() This problem can be performed in 1 line rather than using a loop using the list slicing functionality provided by Python and then using sum(). Minus operator specifies slicing to be done from rear end. 
Python3
# Python3 code to demonstrate# Inverse K slice Sum# using list slicing + sum() # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 5 # Inverse K slice Sum# using list slicing + sum()res = sum(test_list[-K:]) # print resultprint("The last K elements sum of list is : " + str(res))
The original list : [4, 5, 2, 6, 7, 8, 10]
The last K elements sum of list is : 33
 
 Method #2 : Using islice() + reversed() + sum() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end and then sum() can be employed to perform summation. 
Python3
# Python3 code to demonstrate# Inverse K slice Sum# using islice() + reversed() + sum()from itertools import islice # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 5 # using islice() + reversed() + sum()# Inverse K slice Sumres = list(islice(reversed(test_list), 0, K))res.reverse()res = sum(res) # print resultprint("The last K elements sum of list are : " + str(res))
The original list : [4, 5, 2, 6, 7, 8, 10]
The last K elements sum of list is : 33
 
ruhelaa48
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Filter Non-None dictionary Keys

23 Jan, 2020
Many times, while working with dictionaries, we wish to get keys for a non-null keys. This finds application in Machine Learning in which we have to feed data with no none values. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopIn this we just run a loop for all the keys and check for values, if its not None, we append into a list which stores keys of all Non None keys.
# Python3 code to demonstrate working of# Non-None dictionary Keys# Using loop  # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using loop# Non-None dictionary Keysres = []for ele in test_dict:    if test_dict[ele] is not None :        res.append(ele)  # printing result print("Non-None keys list : " + str(res))
The original dictionary is : {'for': 2, 'CS': None, 'Gfg': 1}
Non-None keys list : ['for', 'Gfg']

 
Method #2 : Using dictionary comprehensionThis task can also be performed using dictionary comprehension. In this, we perform similar operation as above method, just as a shorthand.
# Python3 code to demonstrate working of# Non-None dictionary Keys# Using dictionary comprehension  # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Non-None dictionary Keys# Using dictionary comprehensionres = list({ele for ele in test_dict if test_dict[ele]})  # printing result print("Non-None keys list : " + str(res))
The original dictionary is : {'for': 2, 'CS': None, 'Gfg': 1}
Non-None keys list : ['for', 'Gfg']

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Fractal Trees in Python

Fractal patterns are all around us in nature. Like a small branch taken out of the leaf of a fern leaf resembles the leaf itself. Or a pebble often resembles the shape of a mountain! So this idea of a repetition of small pattern to generate a large pattern is known as a fractal tree. In python programming we can also generate fractal trees by using various modules available.
This module provides us with the required functions to generate the fractal trees. Here we first defines the screen layout size and then define the deepness up to which the patterns will repeat themselves. Recursion has a big role here as we are going to repeat the same pattern again and again up to a certain depth.
import pygame, math

pygame.init()
screen = pygame.display.set_mode((750, 650))
pygame.display.set_caption("Fractal Tree")
display = pygame.display.get_surface()

def drawTree(a, b, pos, deepness):
if deepness:
c = a + int(math.cos(math.radians(pos)) * deepness * 10.0)
d = b + int(math.sin(math.radians(pos)) * deepness * 10.0)
pygame.draw.line(display, (127,255,0), (a, b), (c, d), 1)
drawTree(c, d, pos - 25, deepness - 1)
drawTree(c, d, pos + 25, deepness- 1)

def process(event):
if event.type == pygame.QUIT:
exit(0)

drawTree(370, 650, -90, 10)
pygame.display.flip()
while True:
process(pygame.event.wait())
Running the above code gives us the following result:
Using turtle module we can follow a similar approach. Here the turtle program starts drawing the branches of the tree as repeated pattern by just changing the direction of the drawing. We define the angles at which the function will repeat itself and then we get the complete tree.
import turtle
def tree(Length,n):
   if Length > 10:
      n.forward(Length)
      n.right(25)
      tree(Length-15,n)
      n.left(50)
      tree(Length-15,n)
      n.right(25)
      n.backward(Length)

def function():
   n = turtle.Turtle()
   data = turtle.Screen()
   n.left(90)
   n.up()
   n.backward(100)
   n.down()
   n.color("green")
   tree(85,n)
   data.exitonclick()

function()
Running the above code gives us the following result:
Image processing with Scikit-image in Python - GeeksforGeeks

14 Jan, 2022
scikit-image is an image processing Python package that works with NumPy arrays which is a collection of algorithms for image processing. Let’s discuss how to deal with images into set of information and it’s some application in the real world. Important features of scikit-image :  
Simple and efficient tools for image processing and computer vision techniques. Accessible to everybody and reusable in various contexts. Built on the top of NumPy, SciPy, and matplotlib. Open source, commercially usable – BSD license.
Note : Before installing scikit-image, ensure that NumPy and SciPy are pre-installed. Now, the easiest way to install scikit-image is using pip :  
pip install -U scikit-image
  Most functions of skimage are found within submodules. Images are represented as NumPy arrays, for example 2-D arrays for grayscale 2-D images.Code #1 :  
Python3
# Python3 program to process# images using scikit-image # importing data from skimagefrom skimage import data camera = data.camera() # An image with 512 rows# and 512 columnstype(camera) print(camera.shape)
Output :  
numpy.ndarray
(512, 512)
  Code #2 : skimage.data submodule provides a set of functions returning example images.  
Python
# Python3 program to process# images using scikit-image # importing filters and# data from skimagefrom skimage import filtersfrom skimage import data # Predefined function to fetch datacoins = data.coins() # way to find thresholdthreshold_value = filters.threshold_otsu(coins) print(threshold_value)
Output :  
107
  Code #3 : Load own images as NumPy arrays from image files.  
Python
# Python3 program to process# images using scikit-imageimport os # importing io from skimageimport skimagefrom skimage import io # way to load car image from filefile = os.path.join(skimage.data_dir, 'cc.jpg')  cars = io.imread(file) # way to show the input imageio.imshow(cars)io.show()
Output :  
Applications :  
Analysis of Medical images.
Classification of images for detection.
 
rkbhola5
Image-Processing
python-modules
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Apex - SOSL

Every business or application has search functionality as one of the basic requirements. For this, Salesforce.com provides two major approaches using SOSL and SOQL. Let us discuss the SOSL approach in detail in this chapter.
Searching the text string across the object and across the field will be done by using SOSL. This is Salesforce Object Search Language. It has the capability of searching a particular string across multiple objects.
SOSL statements evaluate to a list of sObjects, wherein, each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query.
Consider a business case wherein, we need to develop a program which can search a specified string. Suppose, we need to search for string 'ABC' in the Customer Name field of Invoice object. The code goes as follows −
First, you have to create a single record in Invoice object with Customer name as 'ABC' so that we can get valid result when searched.
// Program To Search the given string in all Object
// List to hold the returned results of sObject generic type
List<list<SObject>> invoiceSearchList = new List<List<SObject>>();

// SOSL query which will search for 'ABC' string in Customer Name field of Invoice Object
invoiceSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice_c
   (Id,APEX_Customer_r.Name)];

// Returned result will be printed
System.debug('Search Result '+invoiceSearchList);

// Now suppose, you would like to search string 'ABC' in two objects,
// that is Invoice and Account. Then for this query goes like this:

// Program To Search the given string in Invoice and Account object,
// you could specify more objects if you want, create an Account with Name as ABC.

// List to hold the returned results of sObject generic type
List<List<SObject>> invoiceAndSearchList = new List<List<SObject>>();

// SOSL query which will search for 'ABC' string in Invoice and in Account object's fields
invoiceAndSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice__c
   (Id,APEX_Customer__r.Name), Account];

// Returned result will be printed
System.debug('Search Result '+invoiceAndSearchList);

// This list will hold the returned results for Invoice Object
APEX_Invoice__c [] searchedInvoice = ((List<APEX_Invoice_c>)invoiceAndSearchList[0]);

// This list will hold the returned results for Account Object
Account [] searchedAccount = ((List<Account>)invoiceAndSearchList[1]);
System.debug('Value of searchedInvoice'+searchedInvoice+'Value of searchedAccount'
   + searchedAccount);
This is almost the same as SOQL. You can use this to fetch the object records from one object only at a time. You can write nested queries and also fetch the records from parent or child object on which you are querying now.
We will explore SOQL in the next chapter.

    14 Lectures 
     2 hours 

 Vijay Thapa

    7 Lectures 
     2 hours 

 Uplatz

    29 Lectures 
     6 hours 

 Ramnarayan Ramakrishnan

    49 Lectures 
     3 hours 

 Ali Saleh Ali

    10 Lectures 
     4 hours 

 Soham Ghosh

    48 Lectures 
     4.5 hours 

 GUHARAJANM
 Print
 Add Notes
 Bookmark this page
How to use Wait-Process in Powershell?

Wait-Process cmdlet in PowerShell is used to wait for the process to stop before the execution moves on to the next step.
We have a snipping tool application running and we need to wait for the process to stop first and then move on to the next step.
PS C:\> Get-Process SnippingTool | Select Name,Id,CPU
Name          Id    CPU
----          --    ---
SnippingTool  7440   2.0625
To wait for the process to stop first we will use the Wait-Process command. You can provide ProcessName or ID.
Write-Output "Waiting for the Process to Stop"
Wait-Process -Name 'SnippingTool'
Write-Output 'Snipping tool Process is stopped'
PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
Once the process is stopped,
PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
Snipping tool Process is stopped
If the desired process can’t stop, the execution waits forever. You can also provide the timeout parameter in seconds so if the process can’t stop in the mentioned time, it will throw an error.
Write-Output "Waiting for the Process to Stop"
Wait-Process -Name 'SnippingTool' -Timeout 5
Write-Output 'Snipping tool Process is stopped'
PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
CloseError: (System.Diagnostics....cess (SnippingTool):Process) [Wait-Process],
TimeoutException
Snipping tool Process is stopped
In such instance we can use the change the ErrorAction setting to Stop.
Write-Output "Waiting for the Process to Stop"
Wait-Process -Name 'SnippingTool' -Timeout 5 -ErrorAction Stop
Write-Output 'Snipping tool Process is stopped'
PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
CloseError: (System.Diagnostics....cess (SnippingTool):Process) [Wait-Process],
TimeoutException
How to Create Stacked area plot using Plotly in Python? - GeeksforGeeks

10 Jul, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. 
A stacked area chart is the amplification of a basic area chart to display the enlargement of the value of several groups on the same graphic. The values of each group are displayed on top of each other. This is the best chart to be used to show the distribution of categories as parts of a whole area where the cumulative total is unnecessary. It can be created by passing the stackgroup  parameter  in the scatter() method of graph_objects class
Example 1:
Python3
import plotly.graph_objects as pximport numpy    # creating random data through randomint # function of numpy.random np.random.seed(42)  random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100)  x = ['A', 'B', 'C', 'D']  plot = px.Figure()  plot.add_trace(go.Scatter(    name = 'Data 1',    x = x,    y = [100, 200, 500, 673],    stackgroup='one'   ))  plot.add_trace(go.Scatter(    name = 'Data 2',    x = x,    y = [56, 123, 982, 213],    stackgroup='one'   ))  plot.show()
Output:
Example 2:
Python3
import plotly.graph_objects as goimport numpy     plot = go.Figure(data=[go.Scatter(    x = np.random.randn(1000),    y = np.random.randn(1000),    stackgroup='one'),                       go.Scatter(    x = np.random.randn(10),    y = np.random.randn(50),    stackgroup='one')])                   plot.show()
Output:
Example 3:
Python3
import plotly.graph_objects as goimport plotly.express as pximport numpy    df = px.data.iris()  plot = go.Figure(data=[go.Scatter(    x = df['sepal_width'],    y = df['sepal_length'],    stackgroup='one'),                       go.Scatter(    x = df['petal_width'],    y = df['petal_length'],    stackgroup='one')])                   plot.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Python Dictionary
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Batch Script - Overview

Batch Script is incorporated to automate command sequences which are repetitive in nature. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one’s life at the shell easier and more productive. In most organizations, Batch Script is incorporated in some way or the other to automate stuff.
Some of the features of Batch Script are −
Can read inputs from users so that it can be processed further.
Can read inputs from users so that it can be processed further.
Has control structures such as for, if, while, switch for better automating and scripting.
Has control structures such as for, if, while, switch for better automating and scripting.
Supports advanced features such as Functions and Arrays.
Supports advanced features such as Functions and Arrays.
Supports regular expressions.
Supports regular expressions.
Can include other programming codes such as Perl.
Can include other programming codes such as Perl.
Some of the common uses of Batch Script are −
Setting up servers for different purposes.
Setting up servers for different purposes.
Automating housekeeping activities such as deleting unwanted files or log files.
Automating housekeeping activities such as deleting unwanted files or log files.
Automating the deployment of applications from one environment to another.
Automating the deployment of applications from one environment to another.
Installing programs on various machines at once.
Installing programs on various machines at once.
Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe.
Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In such case, the full path name must be used unless the file's path is in the path environment. Following is a simple example of a Batch Script. This Batch Script when run deletes all files in the current directory.
:: Deletes All files in the Current Directory With Prompts and Warnings
::(Hidden, System, and Read-Only Files are Not Affected)
:: @ECHO OFF
DEL . DR

 Print
 Add Notes
 Bookmark this page
PHP 7 - Null Coalescing Operator

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<?php
   // fetch the value of $_GET['user'] and returns 'not passed'
   // if username is not passed
   $username = $_GET['username'] ?? 'not passed';
   print($username);
   print("<br/>");

   // Equivalent code using ternary operator
   $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
   print($username);
   print("<br/>");
   // Chaining ?? operation
   $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
   print($username);
?>
It produces the following browser output −
not passed
not passed
not passed


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

function Car(props) {
  return <h2>I am a { props.brand }!</h2>;
}

const myElement = <Car brand="Ford" />;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
SQL Query to find All Sundays Between Two Dates - GeeksforGeeks

07 Apr, 2021
To find all the Sundays in between two days using SQL Language, we will be using the “Date Functions” defined in SQL. Apart from these we will be using CTE ( View) idea too.
Basic idea: 
So basically we are given two days, and we are required to list all Sundays between these two days. 
Thinking a little we got the idea that we can check all the dates between the two boundary dates given for Sundays. Also SQL Date functions do provide one such method to implement this idea:
DATENAME(interval_part, Date)
This function return the name of the part of the date specified in arguments.
For eg : 
DATENAME(month, '18/11/2001' ) 
This call to the function would return November.
Hence we can match the name of day represented by any date with sunday. If it is sunday than we select it otherwise rejects it.
Now the left over part is to create a table which contains a column of all the dates between the two given dates, so that we can perform our check over them.
This can be done using the idea that we can increment the day part of date by 1 over the preceding date to get next date and do check that the next date is less than the given upper bound of the dates.
DATEADD(part , number, date) : This method is used to add the specified number to the given part  of the date .
For eg. DATEADD(year,2,’18/11/2001′) This results in the date : 18/11/2003.
So here is our SQL Query for this topic:
declare  @StartDate DateTime = '2021-02-01',
              @EndDate DateTime = '2021-02-28';
/*Creating a temporary view in sql(CTE) which recursively 
calls itself to find next date by incrementing the 
previous date and stores the result in it till the end date is reached*/
WITH CTE(date_list) AS (
      SELECT @StartDate
      UNION ALL
      SELECT DATEADD(day,1,date_list) FROM CTE
      WHERE date_list<=@EndDate
)
SELECT date_list as 'List of sundays'
FROM CTE
WHERE DATENAME(weekday ,date_list) IN ('Sunday');
/*In the where clause at last we are checking 
each day from the list whether it is in Sunday list or not*/
DBMS-SQL
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 Query to Convert VARCHAR to INT
SQL | Subquery
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
Bootstrap Buttons

Bootstrap provides different styles of buttons:

Basic
Default
Primary
Success
Info
Warning
Danger
Link

To achieve the button styles above, Bootstrap has the following classes:
.btn
.btn-default
.btn-primary
.btn-success
.btn-info
.btn-warning
.btn-danger
.btn-link
The following example shows the code for the different button styles:
The button classes can be used on an <a>, <button>, or 
<input> element:
Why do we put a # in the href attribute of the link?Since 
we do not have any page to link it to, and we do not want to get a "404" 
message, we put # as the link in our examples. It should be a real URL to a 
specific page.
Bootstrap provides four button sizes:

Large
Normal
Small
XSmall

The classes that define the different sizes are:
.btn-lg
.btn-sm
.btn-xs
The following example shows the code for different button sizes:
A block level button spans the entire width of the parent element.
Add class .btn-block to create a block level button:
A button can be set to an active (appear pressed) or a disabled (unclickable) state:

Active Primary
Disabled Primary

The class .active makes a button appear pressed, and the class 
.disabled 
makes a button unclickable:
Add a Bootstrap class to style the button properly as a "danger" button.
<button class="">Danger</button>

Start the Exercise
For a complete reference of all button classes, go to our complete
Bootstrap Button Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How can we create a MySQL view with INNER JOIN?

To illustrate of the making of MySQL view with INNER JOIN we are using the following data from ‘Customers’ and ‘Resreve’ tables −
mysql> Select * from customers;
+-------------+----------+
| Customer_Id | Name     |
+-------------+----------+
| 1           | Rahul    |
| 2           | Yashpal  |
| 3           | Gaurav   |
| 4           | Virender |
+-------------+----------+
4 rows in set (0.00 sec)

mysql> Select * from reserve;
+------+------------+
| ID   | Day        |
+------+------------+
| 1    | 2017-12-30 |
| 2    | 2017-12-28 |
| 2    | 2017-12-25 |
| 1    | 2017-12-24 |
| 3    | 2017-12-26 |
+------+------------+
5 rows in set (0.00 sec)
Now following query will create a view named ‘customer_V’, using INNER JOIN on the above-mentioned tables, which would have the names of the customers who have made a reservation for one or more than one car.
mysql> CREATE VIEW customer_V AS Select DISTINCT Name FROM customers c INNER JOIN Reserve R ON R.id = c.customer_id;
Query OK, 0 rows affected (0.08 sec)

mysql> Select * from customer_V;
+---------+
| Name    |
+---------+
| Rahul   |
| Yashpal |
| Gaurav  |
+---------+
3 rows in set (0.02 sec)
Python time clock() Method

Pythom time method clock() returns the current processor time as a floating point number expressed in seconds on Unix. The precision depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter.
Following is the syntax for clock() method −
time.clock()

NA
NA
This method returns the current processor time as a floating point number expressed in seconds on Unix and in Windows it returns wall-clock seconds elapsed since the first call to this function, as a floating point number.
The following example shows the usage of clock() method.
#!/usr/bin/python
import time

def procedure():
   time.sleep(2.5)

# measure process time
t0 = time.clock()
procedure()
print time.clock(), "seconds process time"

# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"
When we run above program, it produces following result −
0.0 seconds process time
2.50023603439 seconds wall time

Note − Not all systems can measure the true process time. On such systems (including Windows), clock usually measures the wall time since the program was started.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to open Node.js command prompt ? - GeeksforGeeks

20 Aug, 2021
Node js help us to execute JavaScript code outside a web browser. It is neither a framework nor a programming language but basically a backend JavaScript runtime environment that helps to execute the scripts outside the browser. You can install node js from the web. You’ll be able to visit the link Download Node and download the latest version of the node in your machine. In this article, we will discuss how to open the node.js using a command prompt.
Installing Node.js on the machine: First of all, we have to check whether the node.js is installed on our machine or not. To check type “node –version” on the command prompt. If the installed version appears on the machine .Node.js is already installed on your machine otherwise we have to install the latest version of the node.js. Refer to this article to know the process of installing Node.js on your machine. 
How to open node js in command prompt: Node js comes with a virtual environment called REPL (READ, EVAL, PRINT, LOOP). It is a computer environment the same as command prompt and an easy way to test simple Node.js/JavaScript code and allows to execute multiple javascript codes. we can simply run REPL on the command prompt using node command on the command prompt.
 
Syntax:
node
Performing some operations on REPl:
Addition of the two numbers: We can add two numbers using “+” Operator.
Defining variables and assigning values to the variables: When you print the value or write some valid statements like defining variables etc it also returns undefined. JavaScript functions always return something therefore by default undefined is returned.
Execution for loop on REPL: We can execute for loop on the Node.js REPL in multiline same as in the javascript. This is called multiline expression.
 REPL commands:  These commands help to manipulate or communicate with the node.js commands on the REPL
Executing REPL Commands:
Reference: https://nodejs.dev/learn/how-to-use-the-nodejs-repl
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Node.js Event Loop
Mongoose Populate() Method
Mongoose find() Function
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript